file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
ClientsDialAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ClientsDialAnswerDelayTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sip.Dialog; import javax.sip.address.SipURI; import javax.sip.header.UserAgentHeader; import javax.sip.message.Response; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.CreateClientsTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.restcomm.connect.commons.annotations.UnstableTests; /** * Test for clients with or without VoiceURL (Bitbucket issue 115). Clients without VoiceURL can dial anything. * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class ClientsDialAnswerDelayTest { private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); private static final String webRtcBody = "v=0\n" + "o=- 655836341935372758 2 IN IP4 24.217.142.20\n" + "s=Restcomm B2BUA\n" + "t=0 0\n" + "a=group:BUNDLE audio video\n" + "a=msid-semantic:WMS ARDAMS\n" + "m=audio 9 UDP/TLS/RTP/SAVPF 111 103 9 102 0 8 106 105 13 126\n" + "c=IN IP4 24.217.142.20\n" + "a=rtcp:9 IN IP4 0.0.0.0\n" + "a=candidate:704553097 1 udp 2122260223 192.168.1.3 60475 typ host generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:2158047068 1 udp 1686052607 24.217.142.20 60475 typ srflx raddr 192.168.1.3 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41885695 50.97.253.79 55954 typ relay raddr 24.217.142.20 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41886207 50.97.253.79 49214 typ relay raddr 24.217.142.20 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108735 50.97.253.79 63824 typ relay raddr 24.217.142.20 rport 54517 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108223 50.97.253.79 50246 typ relay raddr 24.217.142.20 rport 33927 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=ice-ufrag:PFs2\n" + "a=ice-pwd:MZHsJBkJ+vdWaNvb4Z7iCejt\n" + "a=fingerprint:sha-256 56:B1:98:06:06:EA:B1:BB:31:51:28:35:C7:8C:45:11:CD:3A:0D:28:C1:10:5B:D5:99:EA:21:46:8E:ED:08:89\n" + "a=setup:actpass\n" + "a=mid:audio\n" + "a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\n" + "a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n" + "a=sendrecv\n" + "a=rtcp-mux\n" + "a=rtpmap:111 opus/48000/2\n" + "a=rtcp-fb:111 transport-cc\n" + "a=fmtp:111 minptime=10;useinbandfec=1\n" + "a=rtpmap:103 ISAC/16000\n" + "a=rtpmap:9 G722/8000\n" + "a=rtpmap:102 ILBC/8000\n" + "a=rtpmap:0 PCMU/8000\n" + "a=rtpmap:8 PCMA/8000\n" + "a=rtpmap:106 CN/32000\n" + "a=rtpmap:105 CN/16000\n" + "a=rtpmap:13 CN/8000\n" + "a=rtpmap:126 telephone-event/8000\n" + "a=ssrc:743432057 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:743432057 msid:ARDAMS ARDAMSa0\n" + "a=ssrc:743432057 mslabel:ARDAMS\n" + "a=ssrc:743432057 label:ARDAMSa0\n" + "m=video 9 UDP/TLS/RTP/SAVPF 100 101 116 117 121 96 97 98 99\n" + "c=IN IP4 24.217.142.20\n" + "a=rtcp:9 IN IP4 0.0.0.0\n" + "a=candidate:704553097 1 udp 2122260223 192.168.1.3 40839 typ host generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:2158047068 1 udp 1686052607 24.217.142.20 40839 typ srflx raddr 192.168.1.3 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41886207 50.97.253.79 53691 typ relay raddr 24.217.142.20 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41885695 50.97.253.79 63503 typ relay raddr 24.217.142.20 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108735 50.97.253.79 56359 typ relay raddr 24.217.142.20 rport 33643 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108223 50.97.253.79 54107 typ relay raddr 24.217.142.20 rport 44827 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=ice-ufrag:PFs2\n" + "a=ice-pwd:MZHsJBkJ+vdWaNvb4Z7iCejt\n" + "a=fingerprint:sha-256 56:B1:98:06:06:EA:B1:BB:31:51:28:35:C7:8C:45:11:CD:3A:0D:28:C1:10:5B:D5:99:EA:21:46:8E:ED:08:89\n" + "a=setup:actpass\n" + "a=mid:video\n" + "a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\n" + "a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n" + "a=extmap:4 urn:3gpp:video-orientation\n" + "a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\n" + "a=sendrecv\n" + "a=rtcp-mux\n" + "a=rtcp-rsize\n" + "a=rtpmap:100 VP8/90000\n" + "a=rtcp-fb:100 ccm fir\n" + "a=rtcp-fb:100 nack\n" + "a=rtcp-fb:100 nack pli\n" + "a=rtcp-fb:100 goog-remb\n" + "a=rtcp-fb:100 transport-cc\n" + "a=rtpmap:101 VP9/90000\n" + "a=rtcp-fb:101 ccm fir\n" + "a=rtcp-fb:101 nack\n" + "a=rtcp-fb:101 nack pli\n" + "a=rtcp-fb:101 goog-remb\n" + "a=rtcp-fb:101 transport-cc\n" + "a=rtpmap:116 red/90000\n" + "a=rtpmap:117 ulpfec/90000\n" + "a=rtpmap:121 H264/90000\n" + "a=rtcp-fb:121 ccm fir\n" + "a=rtcp-fb:121 nack\n" + "a=rtcp-fb:121 nack pli\n" + "a=rtcp-fb:121 goog-remb\n" + "a=rtcp-fb:121 transport-cc\n" + "a=rtpmap:96 rtx/90000\n" + "a=fmtp:96 apt=100\n" + "a=rtpmap:97 rtx/90000\n" + "a=fmtp:97 apt=101\n" + "a=rtpmap:98 rtx/90000\n" + "a=fmtp:98 apt=116\n" + "a=rtpmap:99 rtx/90000\n" + "a=fmtp:99 apt=121\n" + "a=ssrc-group:FID 2457543170 3154322644\n" + "a=ssrc:2457543170 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:2457543170 msid:ARDAMS ARDAMSv0\n" + "a=ssrc:2457543170 mslabel:ARDAMS\n" + "a=ssrc:2457543170 label:ARDAMSv0\n" + "a=ssrc:3154322644 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:3154322644 msid:ARDAMS ARDAMSv0\n" + "a=ssrc:3154322644 mslabel:ARDAMS\n" + "a=ssrc:3154322644 label:ARDAMSv0"; @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; private static SipStackTool tool6; private static SipStackTool tool7; private static SipStackTool tool8; private static SipStackTool tool9; private String pstnNumber = "+151261006100"; private String clientPassword = "qwerty1234RT"; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStack; private SipPhone mariaPhone; private static String mariaPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String mariaContact = "sip:[email protected]:" + mariaPort; private String mariaRestcommClientSid; // Dimitris is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack dimitriSipStack; private SipPhone dimitriPhone; private static String dimitriPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String dimitriContact = "sip:[email protected]:" + dimitriPort; private String dimitriRestcommClientSid; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; private SipStack aliceSipStack2; private SipPhone alicePhone2; private static String alicePort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact2 = "sip:[email protected]:" + alicePort2; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:"+pstnNumber+"@127.0.0.1:" + georgePort; private SipStack clientWithAppSipStack; private SipPhone clientWithAppPhone; private static String clientWithAppPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String clientWithAppContact = "sip:[email protected]:" + clientWithAppPort; private String clientWithAppClientSid; private SipStack fotiniSipStackTcp; private SipPhone fotiniPhoneTcp; private static String fotiniPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String fotiniContactTcp = "sip:[email protected]:" + fotiniPort; private String fotiniClientSid; private SipStack bobSipStackTcp; private SipPhone bobPhoneTcp; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContactTcp = "sip:[email protected]:" + bobPort; private SipStack leftySipStack; private SipPhone leftyPhone; private static String leftyPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String leftyContact = "sip:[email protected]:" + leftyPort; private String leftyRestcommClientSid; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("ClientsDialAnswerDelayTest1"); tool2 = new SipStackTool("ClientsDialAnswerDelayTest2"); tool3 = new SipStackTool("ClientsDialAnswerDelayTest3"); tool4 = new SipStackTool("ClientsDialAnswerDelayTest4"); tool5 = new SipStackTool("ClientsDialAnswerDelayTest5"); tool6 = new SipStackTool("ClientsDialAnswerDelayTest6"); tool7 = new SipStackTool("ClientsDialAnswerDelayTest7"); tool8 = new SipStackTool("ClientsDialAnswerDelayTest8"); tool9 = new SipStackTool("ClientsDialAnswerDelayTest9"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { aliceSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); aliceSipStack2 = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort2, restcommContact); alicePhone2 = aliceSipStack2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact2); mariaSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", mariaPort, restcommContact); mariaPhone = mariaSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, mariaContact); dimitriSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", dimitriPort, restcommContact); dimitriPhone = dimitriSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, dimitriContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); clientWithAppSipStack = tool6.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", clientWithAppPort, restcommContact); clientWithAppPhone = clientWithAppSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, clientWithAppContact); mariaRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "maria", clientPassword, null); dimitriRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "dimitri", clientPassword, null); clientWithAppClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "clientWithApp", clientPassword, "http://127.0.0.1:" + mockPort + "/1111"); fotiniSipStackTcp = tool7.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", fotiniPort, restcommContact); fotiniPhoneTcp = fotiniSipStackTcp.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, fotiniContactTcp); fotiniClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "fotini", clientPassword, null); bobSipStackTcp = tool8.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", bobPort, restcommContact); bobPhoneTcp = bobSipStackTcp.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, bobContactTcp); leftySipStack = tool9.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", leftyPort, restcommContact); leftyPhone = leftySipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, leftyContact); } @After public void after() throws Exception { if (mariaPhone != null) { mariaPhone.dispose(); } if (mariaSipStack != null) { mariaSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (dimitriSipStack != null) { dimitriSipStack.dispose(); } if (dimitriPhone != null) { dimitriPhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (clientWithAppPhone != null) { clientWithAppPhone.dispose(); } if (clientWithAppSipStack != null) { clientWithAppSipStack.dispose(); } if (fotiniSipStackTcp != null) { fotiniSipStackTcp.dispose(); } if (fotiniPhoneTcp != null) { fotiniPhoneTcp.dispose(); } if (bobSipStackTcp != null) { bobSipStackTcp.dispose(); } if (bobPhoneTcp != null) { bobPhoneTcp.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(3000); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer public void testClientDialOutPstnSimulateWebRTCClient() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = mariaSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); assertNotNull(mariaDialog); } assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.sendInviteOkAck()); // For a reason the ACK will never reach Restcomm. This is only when working with the sipUnit // assertTrue(georgeCall.waitForAck(5 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category(FeatureExpTests.class) public void testClientDialOutPstnSimulateWebRTCClientBusy() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = mariaSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); assertNotNull(mariaDialog); } assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-George", 3600)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.BUSY_HERE, mariaCall.getLastReceivedResponse().getStatusCode()); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category({FeatureExpTests.class,UnstableTests.class}) public void testClientDialOutPstnSimulateWebRTCClientNoAnswer() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = mariaSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); assertNotNull(mariaDialog); } assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(mariaCall.waitOutgoingCallResponse(120 * 1000)); assertEquals(Response.REQUEST_TIMEOUT, mariaCall.getLastReceivedResponse().getStatusCode()); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category(FeatureExpTests.class) public void testClientDialOutPstnSimulateWebRTCClientServiceUnavailable() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = mariaSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); assertNotNull(mariaDialog); } assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.SERVICE_UNAVAILABLE, "RequestTerminated-George", 3600)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVICE_UNAVAILABLE, mariaCall.getLastReceivedResponse().getStatusCode()); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category(FeatureExpTests.class) public void testClientDialOutPstnSimulateWebRTCClientCancelBefore200() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = mariaSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); assertNotNull(mariaDialog); } assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600)); georgeCall.listenForCancel(); SipTransaction mariaCancelTransaction = mariaCall.sendCancel(); assertTrue(mariaCancelTransaction != null); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(5 * 1000); assertTrue(georgeCancelTransaction != null); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-George", 3600); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); // hangup. georgeCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } public synchronized void testDialClientForkWithWebRTCAliceFromAnotherInstance() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialWebRTCClientForkRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); // hangup. georgeCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } private String dialAliceDimitriRcml= "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client><Sip>"+dimitriContact+"</Sip></Dial></Response>"; @Test public synchronized void testDialForkClient_AliceMultipleRegistrations_George() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceDimitriRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); assertTrue(alicePhone2.register(uri, "alice", "1234", aliceContact2, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); SipCall aliceCall2 = alicePhone2.createSipCall(); aliceCall2.listenForIncomingCall(); SipCall dimitriCall = dimitriPhone.createSipCall(); dimitriCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall2.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall2.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice2", 3600)); aliceCall2.listenForCancel(); assertTrue(dimitriCall.waitForIncomingCall(30 * 1000)); assertTrue(dimitriCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Dimitri", 3600)); dimitriCall.listenForCancel(); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); SipTransaction aliceCall2CancelTransaction = aliceCall2.waitForCancel(5000); SipTransaction dimitriCallCancelTransaction = dimitriCall.waitForCancel(5000); assertNotNull(aliceCall2CancelTransaction); assertNotNull(dimitriCallCancelTransaction); aliceCall2.respondToCancel(aliceCall2CancelTransaction, 200, "OK-2-Cancel-Alice2", 3600); dimitriCall.respondToCancel(dimitriCallCancelTransaction, 200, "OK-2-Cancel-Dimitr", 3600); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); georgeCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(500); } private String dialWebRTCClientForkRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>bob</Client><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialForkClientWebRTCBob_And_AliceWithMultipleRegistrations() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialWebRTCClientForkRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); assertTrue(alicePhone2.register(uri, "alice", "1234", aliceContact2, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); SipCall aliceCall2 = alicePhone2.createSipCall(); aliceCall2.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall2.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall2.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice2", 3600)); aliceCall2.listenForCancel(); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); SipTransaction aliceCall2CancelTransaction = aliceCall2.waitForCancel(5000); assertNotNull(aliceCall2CancelTransaction); aliceCall2.respondToCancel(aliceCall2CancelTransaction, 200, "OK-2-Cancel-Alice2", 3600); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); georgeCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(500); } @Test public synchronized void testDialForkClientWebRTCBob_And_AliceWithMultipleRegistrationsBusyServiceUnavailable() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialWebRTCClientForkRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); assertTrue(alicePhone2.register(uri, "alice", "1234", aliceContact2, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); SipCall aliceCall2 = alicePhone2.createSipCall(); aliceCall2.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall2.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall2.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice2", 3600)); assertTrue(aliceCall2.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Alice2", 3600)); Thread.sleep(200); assertTrue(aliceCall.sendIncomingCallResponse(Response.SERVICE_UNAVAILABLE, "ServiceUnavailable-Alice", 3600)); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVICE_UNAVAILABLE, georgeCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(500); } private String clientWithAppHostedAppRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Number>+151261006100</Number></Dial></Response>"; @Test public synchronized void testClientWithHostedApplication() throws InterruptedException, ParseException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(clientWithAppHostedAppRcml))); assertNotNull(clientWithAppClientSid); SipURI uri = clientWithAppSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(clientWithAppPhone.register(uri, "clientWithApp", clientPassword, clientWithAppContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "clientWithApp", clientPassword); clientWithAppPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall clientWithAppCall = clientWithAppPhone.createSipCall(); clientWithAppCall.initiateOutgoingCall(clientWithAppContact, "sip:3090909090@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(clientWithAppCall); assertTrue(clientWithAppCall.waitForAuthorisation(5000)); assertTrue(clientWithAppCall.waitOutgoingCallResponse(5000)); final int response = clientWithAppCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(clientWithAppCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, clientWithAppCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50 * 1000)); assertTrue(clientWithAppCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, clientWithAppCall.getLastReceivedResponse().getStatusCode()); clientWithAppCall.sendInviteOkAck(); assertTrue(!(clientWithAppCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); // hangup. clientWithAppCall.disconnect(); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); assertTrue(georgeCall.respondToDisconnect()); } @Deployment(name = "ClientsDialAnswerDelayTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(mariaPort)); replacements.put("5093", String.valueOf(dimitriPort)); replacements.put("5094", String.valueOf(alicePort2)); replacements.put("5095", String.valueOf(clientWithAppPort)); replacements.put("5096", String.valueOf(fotiniPort)); replacements.put("5097", String.valueOf(bobPort)); replacements.put("5098", String.valueOf(leftyPort)); List<String> resources = new ArrayList( Arrays.asList( "dial-conference-entry.xml", "dial-fork-entry.xml", "dial-uri-entry.xml", "dial-client-entry.xml", "dial-number-entry.xml")); return WebArchiveUtil.createWebArchiveNoGw( "restcomm-delay.xml", "restcomm.script_dialTest", resources, replacements); } }
52,525
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientsDialAnswerDelayRingingErrorTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ClientsDialAnswerDelayRingingErrorTest.java
package org.restcomm.connect.testsuite.telephony; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import javax.sip.Dialog; import javax.sip.address.SipURI; import javax.sip.header.UserAgentHeader; import javax.sip.message.Response; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.testsuite.http.CreateClientsTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; /** * Test for clients with or without VoiceURL (Bitbucket issue 115). Clients without VoiceURL can dial anything. * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={SequentialClassTests.class}) public class ClientsDialAnswerDelayRingingErrorTest { private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); private static final String webRtcBody = "v=0\n" + "o=- 655836341935372758 2 IN IP4 24.217.142.20\n" + "s=Restcomm B2BUA\n" + "t=0 0\n" + "a=group:BUNDLE audio video\n" + "a=msid-semantic:WMS ARDAMS\n" + "m=audio 9 UDP/TLS/RTP/SAVPF 111 103 9 102 0 8 106 105 13 126\n" + "c=IN IP4 24.217.142.20\n" + "a=rtcp:9 IN IP4 0.0.0.0\n" + "a=candidate:704553097 1 udp 2122260223 192.168.1.3 60475 typ host generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:2158047068 1 udp 1686052607 24.217.142.20 60475 typ srflx raddr 192.168.1.3 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41885695 50.97.253.79 55954 typ relay raddr 24.217.142.20 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41886207 50.97.253.79 49214 typ relay raddr 24.217.142.20 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108735 50.97.253.79 63824 typ relay raddr 24.217.142.20 rport 54517 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108223 50.97.253.79 50246 typ relay raddr 24.217.142.20 rport 33927 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=ice-ufrag:PFs2\n" + "a=ice-pwd:MZHsJBkJ+vdWaNvb4Z7iCejt\n" + "a=fingerprint:sha-256 56:B1:98:06:06:EA:B1:BB:31:51:28:35:C7:8C:45:11:CD:3A:0D:28:C1:10:5B:D5:99:EA:21:46:8E:ED:08:89\n" + "a=setup:actpass\n" + "a=mid:audio\n" + "a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\n" + "a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n" + "a=sendrecv\n" + "a=rtcp-mux\n" + "a=rtpmap:111 opus/48000/2\n" + "a=rtcp-fb:111 transport-cc\n" + "a=fmtp:111 minptime=10;useinbandfec=1\n" + "a=rtpmap:103 ISAC/16000\n" + "a=rtpmap:9 G722/8000\n" + "a=rtpmap:102 ILBC/8000\n" + "a=rtpmap:0 PCMU/8000\n" + "a=rtpmap:8 PCMA/8000\n" + "a=rtpmap:106 CN/32000\n" + "a=rtpmap:105 CN/16000\n" + "a=rtpmap:13 CN/8000\n" + "a=rtpmap:126 telephone-event/8000\n" + "a=ssrc:743432057 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:743432057 msid:ARDAMS ARDAMSa0\n" + "a=ssrc:743432057 mslabel:ARDAMS\n" + "a=ssrc:743432057 label:ARDAMSa0\n" + "m=video 9 UDP/TLS/RTP/SAVPF 100 101 116 117 121 96 97 98 99\n" + "c=IN IP4 24.217.142.20\n" + "a=rtcp:9 IN IP4 0.0.0.0\n" + "a=candidate:704553097 1 udp 2122260223 192.168.1.3 40839 typ host generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:2158047068 1 udp 1686052607 24.217.142.20 40839 typ srflx raddr 192.168.1.3 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41886207 50.97.253.79 53691 typ relay raddr 24.217.142.20 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41885695 50.97.253.79 63503 typ relay raddr 24.217.142.20 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108735 50.97.253.79 56359 typ relay raddr 24.217.142.20 rport 33643 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108223 50.97.253.79 54107 typ relay raddr 24.217.142.20 rport 44827 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=ice-ufrag:PFs2\n" + "a=ice-pwd:MZHsJBkJ+vdWaNvb4Z7iCejt\n" + "a=fingerprint:sha-256 56:B1:98:06:06:EA:B1:BB:31:51:28:35:C7:8C:45:11:CD:3A:0D:28:C1:10:5B:D5:99:EA:21:46:8E:ED:08:89\n" + "a=setup:actpass\n" + "a=mid:video\n" + "a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\n" + "a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n" + "a=extmap:4 urn:3gpp:video-orientation\n" + "a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\n" + "a=sendrecv\n" + "a=rtcp-mux\n" + "a=rtcp-rsize\n" + "a=rtpmap:100 VP8/90000\n" + "a=rtcp-fb:100 ccm fir\n" + "a=rtcp-fb:100 nack\n" + "a=rtcp-fb:100 nack pli\n" + "a=rtcp-fb:100 goog-remb\n" + "a=rtcp-fb:100 transport-cc\n" + "a=rtpmap:101 VP9/90000\n" + "a=rtcp-fb:101 ccm fir\n" + "a=rtcp-fb:101 nack\n" + "a=rtcp-fb:101 nack pli\n" + "a=rtcp-fb:101 goog-remb\n" + "a=rtcp-fb:101 transport-cc\n" + "a=rtpmap:116 red/90000\n" + "a=rtpmap:117 ulpfec/90000\n" + "a=rtpmap:121 H264/90000\n" + "a=rtcp-fb:121 ccm fir\n" + "a=rtcp-fb:121 nack\n" + "a=rtcp-fb:121 nack pli\n" + "a=rtcp-fb:121 goog-remb\n" + "a=rtcp-fb:121 transport-cc\n" + "a=rtpmap:96 rtx/90000\n" + "a=fmtp:96 apt=100\n" + "a=rtpmap:97 rtx/90000\n" + "a=fmtp:97 apt=101\n" + "a=rtpmap:98 rtx/90000\n" + "a=fmtp:98 apt=116\n" + "a=rtpmap:99 rtx/90000\n" + "a=fmtp:99 apt=121\n" + "a=ssrc-group:FID 2457543170 3154322644\n" + "a=ssrc:2457543170 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:2457543170 msid:ARDAMS ARDAMSv0\n" + "a=ssrc:2457543170 mslabel:ARDAMS\n" + "a=ssrc:2457543170 label:ARDAMSv0\n" + "a=ssrc:3154322644 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:3154322644 msid:ARDAMS ARDAMSv0\n" + "a=ssrc:3154322644 mslabel:ARDAMS\n" + "a=ssrc:3154322644 label:ARDAMSv0"; @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; private static SipStackTool tool6; private static SipStackTool tool7; private static SipStackTool tool8; private static SipStackTool tool9; private String pstnNumber = "+151261006100"; private String clientPassword = "qwerty1234RT"; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStack; private SipPhone mariaPhone; private String mariaContact = "sip:[email protected]:5092"; private String mariaRestcommClientSid; // Dimitris is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack dimitriSipStack; private SipPhone dimitriPhone; private String dimitriContact = "sip:[email protected]:5093"; private String dimitriRestcommClientSid; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; private SipStack aliceSipStack2; private SipPhone alicePhone2; private String aliceContact2 = "sip:[email protected]:5094"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:"+pstnNumber+"@127.0.0.1:5070"; private SipStack clientWithAppSipStack; private SipPhone clientWithAppPhone; private String clientWithAppContact = "sip:[email protected]:5095"; private String clientWithAppClientSid; private SipStack fotiniSipStackTcp; private SipPhone fotiniPhoneTcp; private String fotiniContactTcp = "sip:[email protected]:5096"; private String fotiniClientSid; private SipStack bobSipStackTcp; private SipPhone bobPhoneTcp; private String bobContactTcp = "sip:[email protected]:5097"; private SipStack leftySipStack; private SipPhone leftyPhone; private String leftyContact = "sip:[email protected]:5098"; private String leftyRestcommClientSid; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("ClientsDialAnswerDelayTest1"); tool2 = new SipStackTool("ClientsDialAnswerDelayTest2"); tool3 = new SipStackTool("ClientsDialAnswerDelayTest3"); tool4 = new SipStackTool("ClientsDialAnswerDelayTest4"); tool5 = new SipStackTool("ClientsDialAnswerDelayTest5"); tool6 = new SipStackTool("ClientsDialAnswerDelayTest6"); tool7 = new SipStackTool("ClientsDialAnswerDelayTest7"); tool8 = new SipStackTool("ClientsDialAnswerDelayTest8"); tool9 = new SipStackTool("ClientsDialAnswerDelayTest9"); } @Before public void before() throws Exception { aliceSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); aliceSipStack2 = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5094", "127.0.0.1:5080"); alicePhone2 = aliceSipStack2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact2); mariaSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); mariaPhone = mariaSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContact); dimitriSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5093", "127.0.0.1:5080"); dimitriPhone = dimitriSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, dimitriContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); clientWithAppSipStack = tool6.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5095", "127.0.0.1:5080"); clientWithAppPhone = clientWithAppSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, clientWithAppContact); mariaRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "maria", clientPassword, null); dimitriRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "dimitri", clientPassword, null); clientWithAppClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "clientWithApp", clientPassword, "http://127.0.0.1:8090/1111"); fotiniSipStackTcp = tool7.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", "5096", "127.0.0.1:5080"); fotiniPhoneTcp = fotiniSipStackTcp.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, 5080, fotiniContactTcp); fotiniClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "fotini", clientPassword, null); bobSipStackTcp = tool8.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", "5097", "127.0.0.1:5080"); bobPhoneTcp = bobSipStackTcp.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, 5080, bobContactTcp); leftySipStack = tool9.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5098", "127.0.0.1:5080"); leftyPhone = leftySipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, leftyContact); } @After public void after() throws Exception { if (mariaPhone != null) { mariaPhone.dispose(); } if (mariaSipStack != null) { mariaSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (dimitriSipStack != null) { dimitriSipStack.dispose(); } if (dimitriPhone != null) { dimitriPhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (clientWithAppPhone != null) { clientWithAppPhone.dispose(); } if (clientWithAppSipStack != null) { clientWithAppSipStack.dispose(); } if (fotiniSipStackTcp != null) { fotiniSipStackTcp.dispose(); } if (fotiniPhoneTcp != null) { fotiniPhoneTcp.dispose(); } if (bobSipStackTcp != null) { bobSipStackTcp.dispose(); } if (bobPhoneTcp != null) { bobPhoneTcp.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(3000); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer public void testClientDialOutPstnSimulateWebRTCClient() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = mariaSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@127.0.0.1:5080", null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); assertNotNull(mariaDialog); } assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.sendInviteOkAck()); // For a reason the ACK will never reach Restcomm. This is only when working with the sipUnit // assertTrue(georgeCall.waitForAck(5 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Deployment(name = "ClientsDialAnswerDelayTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-delay-ringing-error.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-conference-entry.xml"); archive.addAsWebResource("dial-fork-entry.xml"); archive.addAsWebResource("dial-uri-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("dial-number-entry.xml"); return archive; } }
20,859
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialStatusCallbackTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialStatusCallbackTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; /** * Test for Dial status callback attribute. Reference: The 'statuscallback' * attribute takes a URL as an argument. As the call moves states, Restcomm will make a GET or POST request to this URL * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class DialStatusCallbackTest { private final static Logger logger = Logger.getLogger(DialStatusCallbackTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private String dialRestcomm = "sip:1111@" + restcommContact; // Application: dial-client-entry_wActionUrl.xml private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private String dialStatusCallback = "<Response><Dial><Client statusCallback=\"http://127.0.0.1:" + mockPort + "/status\">alice</Client></Dial></Response>"; @Test public void testDialStatusCallbackAliceDisconnects() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialStatusCallback))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); assertEquals(4, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(2).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=2")); assertTrue(requestBody.contains("CallStatus=answered")); requestBody = requests.get(3).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } @Test public void testDialStatusCallbackAliceUnavailable() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialStatusCallback))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.TEMPORARILY_UNAVAILABLE, "Alice-Unavailable", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(5000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); assertEquals(3, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(2).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } private String dialStatusCallbackGetMethod = "<Response><Dial><Client statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" " + "statusCallbackMethod=\"get\">alice</Client></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialStatusCallbackMethodGET() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialStatusCallbackGetMethod))); stubFor(get(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/status.*"))); assertEquals(4, requests.size()); String requestUrl = requests.get(0).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=0")); assertTrue(requestUrl.contains("CallStatus=initiated")); requestUrl = requests.get(1).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=1")); assertTrue(requestUrl.contains("CallStatus=ringing")); requestUrl = requests.get(2).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=2")); assertTrue(requestUrl.contains("CallStatus=answered")); requestUrl = requests.get(3).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=3")); assertTrue(requestUrl.contains("CallStatus=completed")); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } private String dialStatusCallbackGet = "<Response><Dial><Client statusCallback=\"http://127.0.0.1:" + mockPort +"/status\" statusCallbackMethod=\"GET\">alice</Client></Dial></Response>"; @Test @Category({UnstableTests.class, FeatureAltTests.class}) public void testDialStatusCallbackBobDisconnects() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialStatusCallback))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); stubFor(get(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); // List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/status.*"))); assertEquals(4, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(2).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=2")); assertTrue(requestBody.contains("CallStatus=answered")); requestBody = requests.get(3).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } private String dialStatusCallbackOnlyInitiatedAndAnswer = "<Response><Dial><Client statusCallback=\"http://127.0.0.1:"+ mockPort + "/status\" " + "statusCallbackEvent=\"initiated, answered\">alice</Client></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialStatusCallbackOnlyInitiatedAnswerEvent() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialStatusCallbackOnlyInitiatedAndAnswer))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); assertEquals(2, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=2")); assertTrue(requestBody.contains("CallStatus=answered")); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } private String dialStatusCallbackOnlyRingingCompleted = "<Response><Dial><Client statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" " + "statusCallbackEvent=\"ringing,completed\">alice</Client></Dial></Response>"; @Test @Category({UnstableTests.class, FeatureAltTests.class}) public void testDialStatusCallbackOnlyRingingCompleted() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialStatusCallbackOnlyRingingCompleted))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(12000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); assertEquals(2, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } private String dialStatusCallbackForSip = "<Response><Dial><Sip statusCallback=\"http://127.0.0.1:" + mockPort +"/status\">sip:[email protected]:" + henriquePort + "</Sip></Dial></Response>"; @Test public void testDialStatusCallbackDialSip() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialStatusCallbackForSip))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(henriqueCall.waitForIncomingCall(5000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Henrique-Trying", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Henrique-Ringing", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "Henrique-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(henriqueCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); assertEquals(4, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(2).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=2")); assertTrue(requestBody.contains("CallStatus=answered")); requestBody = requests.get(3).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } private String dialStatusCallbackForNumber = "<Response><Dial><Number statusCallback=\"http://127.0.0.1:" + mockPort + "/status\">+131313</Number></Dial></Response>"; @Test public void testDialStatusCallbackDialNumber() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialStatusCallbackForNumber))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); assertEquals(4, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(2).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=2")); assertTrue(requestBody.contains("CallStatus=answered")); requestBody = requests.get(3).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } private String dialFork = "<Response><Dial><Client statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" statusCallbackMethod=\"get\">alice</Client><Sip statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" statusCallbackMethod=\"get\">sip:[email protected]:" + henriquePort + "</Sip><Number statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" statusCallbackMethod=\"get\">+131313</Number></Dial></Response>"; @Test @Category({UnstableTests.class, FeatureAltTests.class}) public synchronized void testDialForkNoAnswerButHenriqueStatusCallbackOnAll() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); stubFor(get(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); georgeCall.listenForCancel(); aliceCall.listenForCancel(); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); //Wait to cancel the other branches Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(12000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/status.*"))); assertEquals(10, requests.size()); String requestUrl = requests.get(0).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=0")); assertTrue(requestUrl.contains("CallStatus=initiated")); requestUrl = requests.get(1).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=0")); assertTrue(requestUrl.contains("CallStatus=initiated")); requestUrl = requests.get(2).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=0")); assertTrue(requestUrl.contains("CallStatus=initiated")); requestUrl = requests.get(3).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=1")); assertTrue(requestUrl.contains("CallStatus=ringing")); requestUrl = requests.get(4).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=1")); assertTrue(requestUrl.contains("CallStatus=ringing")); requestUrl = requests.get(5).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=1")); assertTrue(requestUrl.contains("CallStatus=ringing")); requestUrl = requests.get(6).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=2")); assertTrue(requestUrl.contains("CallStatus=answered")); requestUrl = requests.get(7).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=3")); assertTrue(requestUrl.contains("CallStatus=completed")); requestUrl = requests.get(8).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=3")); assertTrue(requestUrl.contains("CallStatus=completed")); requestUrl = requests.get(9).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=3")); assertTrue(requestUrl.contains("CallStatus=completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialForkStatusCallbackWithPost = "<Response><Dial><Client statusCallback=\"http://127.0.0.1:" + mockPort + "/status\">alice</Client><Sip statusCallback=\"http://127.0.0.1:" + mockPort + "/status\">sip:[email protected]:" + henriquePort + "</Sip><Number statusCallback=\"http://127.0.0.1:" + mockPort + "/status\">+131313</Number></Dial></Response>"; @Test @Category({FeatureAltTests.class,UnstableTests.class}) public synchronized void testDialForkNoAnswerButHenriqueStatusCallbackOnAllPost() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkStatusCallbackWithPost))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); georgeCall.listenForCancel(); aliceCall.listenForCancel(); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); //Wait to cancel the other branches Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(12000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); assertEquals(10, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(2).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(3).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(4).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(5).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(6).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=2")); assertTrue(requestBody.contains("CallStatus=answered")); requestBody = requests.get(7).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); requestBody = requests.get(8).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); requestBody = requests.get(9).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialForkWithTimeoutStatusCallbackWithPost = "<Response><Dial timeout=\"60\"><Client statusCallback=\"http://127.0.0.1:" + mockPort + "/status\">alice</Client><Sip statusCallback=\"http://127.0.0.1:" + mockPort + "/status\">sip:[email protected]:" + henriquePort + "</Sip><Number statusCallback=\"http://127.0.0.1:" + mockPort + "/status\">+131313</Number></Dial></Response>"; @Test @Category({UnstableTests.class, FeatureAltTests.class}) public synchronized void testDialForkNoAnswerButHenriqueStatusCallbackOnAllPostWithTimeout() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeoutStatusCallbackWithPost))); stubFor(post(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); georgeCall.listenForCancel(); aliceCall.listenForCancel(); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); //Wait to cancel the other branches Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/status.*"))); assertEquals(10, requests.size()); String requestBody = requests.get(0).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(1).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(2).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=0")); assertTrue(requestBody.contains("CallStatus=initiated")); requestBody = requests.get(3).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(4).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(5).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=1")); assertTrue(requestBody.contains("CallStatus=ringing")); requestBody = requests.get(6).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=2")); assertTrue(requestBody.contains("CallStatus=answered")); requestBody = requests.get(7).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); requestBody = requests.get(8).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); requestBody = requests.get(9).getBodyAsString(); assertTrue(requestBody.contains("SequenceNumber=3")); assertTrue(requestBody.contains("CallStatus=completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialForkWithActionUrl = "<Response><Dial timeLimit=\"1000\" timeout=\"2\" action=\"http://127.0.0.1:" + mockPort + "/action\">" + "<Number statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" statusCallbackMethod=\"get\">+131313</Number>" + "<Sip statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" statusCallbackMethod=\"get\">sip:[email protected]:" + henriquePort + "</Sip>" + "<Client statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" statusCallbackMethod=\"get\">alice</Client></Dial></Response>"; private String rcmlToReturn = "<Response><Dial timeout=\"50\"><Client statusCallback=\"http://127.0.0.1:" + mockPort + "/status\" statusCallbackMethod=\"get\">alice</Client> </Dial></Response>"; //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test //TODO Fails when the whole test class runs but Passes when run individually @Category({UnstableTests.class, FeatureAltTests.class}) public synchronized void testDialForkNoAnswerExecuteRCML_ReturnedFromActionURLWithStatusCallbacks_BobDisconnects() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithActionUrl))); stubFor(post(urlEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlToReturn))); stubFor(get(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and RCML will move to the next verb to call Fotini assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); Thread.sleep(1000); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); // int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // //There will be the initial call from Bob and the new call to Fotini // logger.info("&&&& LiveCalls: "+liveCalls); // logger.info("&&&& LiveCallsArraySize: "+liveCallsArraySize); // assertTrue(liveCalls == 2); // assertTrue(liveCallsArraySize == 2); Thread.sleep(1000); //Now Fotini should receive a call assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); Thread.sleep(5000); // hangup. aliceCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(aliceCall.waitForDisconnect(50 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the StatusCallback Requests"); requests = findAll(getRequestedFor(urlPathMatching("/status.*"))); assertEquals(13, requests.size()); } //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test //TODO Fails when the whole test class runs but Passes when run individually @Category({UnstableTests.class, FeatureAltTests.class}) public synchronized void testDialForkNoAnswerExecuteRCML_ReturnedFromActionURLWithStatusCallbacks_AliceDisconnects() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithActionUrl))); stubFor(post(urlEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlToReturn))); stubFor(get(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and RCML will move to the next verb to call Fotini assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); Thread.sleep(1000); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); // int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // //There will be the initial call from Bob and the new call to Fotini // logger.info("&&&& LiveCalls: "+liveCalls); // logger.info("&&&& LiveCallsArraySize: "+liveCallsArraySize); // assertTrue(liveCalls == 2); // assertTrue(liveCallsArraySize == 2); //Now Fotini should receive a call assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); bobCall.listenForDisconnect(); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); Thread.sleep(2000); // hangup. assertTrue(aliceCall.disconnect()); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the StatusCallback Requests"); requests = findAll(getRequestedFor(urlPathMatching("/status.*"))); Map<String, String> requestMap = getRequestMap(requests); assertEquals(13, requests.size()); } private Map<String, String> getRequestMap(final List<LoggedRequest> requestList) { Map<String, String> resultMap = new HashMap<String, String>(); for(LoggedRequest request: requestList) { String[] tokens = request.getUrl().split("&"); String to = null; String callStatus = null; for (String token: tokens) { if (token.contains("To")) { to = token; } if (token.contains("SequenceNumber")) { to = to+token; } if (token.contains("CallStatus")) { callStatus = token; } } resultMap.put(to,callStatus); } return resultMap; } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); List<String> resources = new ArrayList(); return WebArchiveUtil.createWebArchiveNoGw("restcomm.xml", "restcomm.script_dialStatusCallbackTest",resources, replacements); } }
89,699
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TestMgcpOperations.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestMgcpOperations.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.monitoringservice.MonitoringMetrics; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; /** * Created by gvagenas on 6/15/16. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(SequentialClassTests.class) public class TestMgcpOperations { private final static Logger logger = Logger.getLogger(TestDialVerbPartOne.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // Fotini is a simple SIP Client. Will not register with Restcomm private SipStack fotiniSipStack; private SipPhone fotiniPhone; private String fotiniContact = "sip:[email protected]"; private String dialRestcomm = "sip:[email protected]:5080"; private String notFoundDialNumber = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialTest1Tool1"); tool2 = new SipStackTool("DialTest1Tool2"); tool3 = new SipStackTool("DialTest1Tool3"); tool4 = new SipStackTool("DialTest1Tool4"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); fotiniSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5060", "127.0.0.1:5080"); fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, fotiniContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (fotiniPhone != null) { fotiniPhone.dispose(); } if (fotiniSipStack != null) { fotiniSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } @Test public synchronized void testDialHelloPlay() throws InterruptedException, ParseException { Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); final SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForDisconnect(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(500); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int mgcpEndpoints = metrics.getAsJsonObject("Metrics").get("MgcpEndpoints").getAsInt(); int mgcpConnections = metrics.getAsJsonObject("Metrics").get("MgcpConnections").getAsInt(); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("MgcpEndpoints: "+mgcpEndpoints); logger.info("MgcpConnections: "+mgcpConnections); logger.info("LiveCalls: "+liveCalls); // int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); // logger.info("LiveCallsArraySize: "+liveCallsArraySize); // assertTrue(liveCalls==0); // assertTrue(liveCallsArraySize==0); // int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); // int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); // int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); // assertTrue(maxConcurrentCalls==0); // assertTrue(maxConcurrentIncomingCalls==0); // assertTrue(maxConcurrentOutgoingCalls==0); assertTrue(bobCall.waitForDisconnect(10000)); Thread.sleep(1000); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); mgcpEndpoints = metrics.getAsJsonObject("Metrics").get("MgcpEndpoints").getAsInt(); mgcpConnections = metrics.getAsJsonObject("Metrics").get("MgcpConnections").getAsInt(); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("MgcpEndpoints at the end: "+mgcpEndpoints); logger.info("MgcpConnections at the end: "+mgcpConnections); logger.info("Live calls at the end: "+liveCalls); int ivrEndpoints; int confEndpoints; int bridgeEndpoints; int packetRelayEndpoints; if (mgcpEndpoints > 0) { bridgeEndpoints = metrics.getAsJsonObject("Metrics").get(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS_BRIDGE).getAsInt(); ivrEndpoints = metrics.getAsJsonObject("Metrics").get(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS_IVR).getAsInt(); confEndpoints = metrics.getAsJsonObject("Metrics").get(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS_CONFERENCE).getAsInt(); packetRelayEndpoints = metrics.getAsJsonObject("Metrics").get(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS_PACKETRELAY).getAsInt(); logger.info("IVR Endpoints: "+ivrEndpoints); logger.info("Bridge Endpoints: "+bridgeEndpoints); logger.info("Conference Endpoints: "+confEndpoints); logger.info("PacketRelay Endpoints: "+packetRelayEndpoints); } assertEquals(0, liveCalls); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Deployment(name = "TestMgcpOperations", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_mgcpoperations", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
11,678
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ImsClientsDialTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ImsClientsDialTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.telephony.security.DigestServerAuthenticationMethod; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.Dialog; import javax.sip.InvalidArgumentException; import javax.sip.RequestEvent; import javax.sip.SipException; import javax.sip.address.Address; import javax.sip.address.SipURI; import javax.sip.address.URI; import javax.sip.header.CSeqHeader; import javax.sip.header.CallIdHeader; import javax.sip.header.ContactHeader; import javax.sip.header.FromHeader; import javax.sip.header.Header; import javax.sip.header.MaxForwardsHeader; import javax.sip.header.ProxyAuthenticateHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.header.UserAgentHeader; import javax.sip.header.ViaHeader; import javax.sip.header.WWWAuthenticateHeader; import javax.sip.message.Request; import javax.sip.message.Response; import java.net.URL; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Test for clients with or without VoiceURL (Bitbucket issue 115). Clients without VoiceURL can dial anything. * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, ParallelClassTests.class}) public class ImsClientsDialTest { private static final String version = Version.getVersion(); private static Logger logger = Logger.getLogger(ImsClientsDialTest.class); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private String pstnNumber = "+151261006100"; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack augustSipStack; private SipPhone augustPhone; private static String augustPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String augustContact = "sip:[email protected]:" + augustPort; private boolean isAugustRegistered = false; private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; private boolean isBobRegistered = false; private SipStack juliusSipStack; private SipPhone juliusPhone; private static String juliusPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String juliusContact = "sip:[email protected]:" + juliusPort; private boolean isJuliusRegistered = false; private SipStack imsSipStack; private SipPhone imsAugustPhone; private SipPhone imsAugustPhone2; private SipPhone imsJuliusPhone; private SipPhone imsBobPhone; private static String imsPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String imsContact = "sip:127.0.0.1:" + imsPort; private SipPhone pstnPhone; private String pstnContact = "sip:" + pstnNumber + "@127.0.0.1:" + imsPort; private String adminAccountSid = "AC27f2dd02ab51ba5d5a9ff7fc5537a09a"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("ImsClientsDialTest1"); tool2 = new SipStackTool("ImsClientsDialTest2"); tool3 = new SipStackTool("ImsClientsDialTest3"); tool4 = new SipStackTool("ImsClientsDialTest4"); Class.forName("org.hsqldb.jdbc.JDBCDriver"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { imsSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", imsPort, restcommContact); augustSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", augustPort, restcommContact); augustPhone = augustSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, augustContact); imsAugustPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, augustContact); imsAugustPhone.setLoopback(true); imsAugustPhone.setPassThroughRegisterRequests(true); imsAugustPhone2 = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, "sip:[email protected]"); imsAugustPhone2.setLoopback(true); imsAugustPhone2.setPassThroughRegisterRequests(true); juliusSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", juliusPort, restcommContact); juliusPhone = juliusSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, juliusContact); imsJuliusPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, juliusContact); imsJuliusPhone.setLoopback(true); imsJuliusPhone.setPassThroughRegisterRequests(true); bobSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); imsBobPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); imsBobPhone.setLoopback(true); imsBobPhone.setPassThroughRegisterRequests(true); pstnPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, pstnContact); if(isAugustRegistered){ unregisterAugust(); } if(isBobRegistered){ unregisterBob(); } if(isJuliusRegistered){ unregisterJulius(); } } @After public void after() throws Exception { if (augustPhone != null) { augustPhone.dispose(); } if (augustSipStack != null) { augustSipStack.dispose(); } if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (imsBobPhone != null) { imsBobPhone.dispose(); } if (imsSipStack != null) { imsSipStack.dispose(); } if (imsAugustPhone != null) { imsAugustPhone.dispose(); } if (imsAugustPhone2 != null) { imsAugustPhone2.dispose(); } if (imsJuliusPhone != null) { imsJuliusPhone.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(3000); } @Test public void testRegisterClients() throws ParseException, InterruptedException, SQLException { logger.info("testRegisterClients"); SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, restcommContact); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(401, requestEvent.getRequest()); WWWAuthenticateHeader wwwAuthenticateHeader = imsSipStack.getHeaderFactory().createWWWAuthenticateHeader("Digest realm=\"ims.tp.pl\",\n" + " nonce=\"b7c9036dbf357f7683f054aea940e9703dc8f84c1108\",\n" + " opaque=\"ALU:QbkRBthOEgEQAkgVEwwHRAIBHgkdHwQCQ1lFRkZWDhMyIXBqLCs0Zj06ZTwhdHpgZmI_\",\n" + " algorithm=MD5,\n" + " qop=\"auth\""); response.setHeader(wwwAuthenticateHeader); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); requestEvent = imsAugustPhone.waitRequest(10000); response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(600); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); }catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.register(uri, "august", "1234", augustContact, 3600, 3600)); isAugustRegistered = true; augustPhone.createSipCall().listenForIncomingCall(); Thread.sleep(500); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); }catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.unregister(augustContact, 0)); Thread.sleep(1000); assertEquals(0,MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); isAugustRegistered = false; } @Test public void testRegisterClientForbidden() throws ParseException, InterruptedException, SQLException { logger.info("testRegisterClients"); SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, restcommContact); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(401, requestEvent.getRequest()); WWWAuthenticateHeader wwwAuthenticateHeader = imsSipStack.getHeaderFactory().createWWWAuthenticateHeader("Digest realm=\"ims.tp.pl\",\n" + " nonce=\"b7c9036dbf357f7683f054aea940e9703dc8f84c1108\",\n" + " opaque=\"ALU:QbkRBthOEgEQAkgVEwwHRAIBHgkdHwQCQ1lFRkZWDhMyIXBqLCs0Zj06ZTwhdHpgZmI_\",\n" + " algorithm=MD5,\n" + " qop=\"auth\""); response.setHeader(wwwAuthenticateHeader); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); requestEvent = imsAugustPhone.waitRequest(10000); response = imsSipStack.getMessageFactory().createResponse(Response.FORBIDDEN, requestEvent.getRequest()); contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(600); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); }catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertFalse(augustPhone.register(uri, "august", "1234", augustContact, 3600, 3600)); Thread.sleep(500); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Test public void testReRegisterClientForbidden() throws ParseException, InterruptedException, SQLException { logger.info("testRegisterClients"); SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, restcommContact); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(401, requestEvent.getRequest()); WWWAuthenticateHeader wwwAuthenticateHeader = imsSipStack.getHeaderFactory().createWWWAuthenticateHeader("Digest realm=\"ims.tp.pl\",\n" + " nonce=\"b7c9036dbf357f7683f054aea940e9703dc8f84c1108\",\n" + " opaque=\"ALU:QbkRBthOEgEQAkgVEwwHRAIBHgkdHwQCQ1lFRkZWDhMyIXBqLCs0Zj06ZTwhdHpgZmI_\",\n" + " algorithm=MD5,\n" + " qop=\"auth\""); response.setHeader(wwwAuthenticateHeader); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); requestEvent = imsAugustPhone.waitRequest(10000); response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(600); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); }catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.register(uri, "august", "1234", augustContact, 3600, 3600)); isAugustRegistered = true; augustPhone.createSipCall().listenForIncomingCall(); Thread.sleep(500); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(Response.FORBIDDEN, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); }catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertFalse(augustPhone.register(uri, "august", "1234", augustContact, 3600, 3600)); Thread.sleep(500); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); isAugustRegistered = false; } @Test public void testReRegisterClientForbidden2() throws ParseException, InterruptedException, SQLException, InvalidArgumentException { try{ logger.info("testReRegisterImsClientForbidden"); SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, restcommContact); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone2.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone2.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(600); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone2.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); }catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); }catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }); ToHeader to = augustSipStack.getHeaderFactory().createToHeader( augustSipStack.getAddressFactory().createAddress( augustSipStack.getAddressFactory().createSipURI(null, "[email protected]")), "to_tag"); FromHeader from = augustSipStack.getHeaderFactory().createFromHeader( augustSipStack.getAddressFactory().createAddress( augustSipStack.getAddressFactory().createSipURI(null, "[email protected]")), "from_tag"); CallIdHeader callId = (CallIdHeader)augustSipStack.getHeaderFactory().createHeader("Call-ID", "12345"); CSeqHeader cseq = augustSipStack.getHeaderFactory().createCSeqHeader((long)1, "REGISTER"); ViaHeader via = augustSipStack.getHeaderFactory().createViaHeader("127.0.0.1", Integer.valueOf(augustPort), "wss", "branch_12345"); List<Header> vias = new ArrayList<Header>(); vias.add(via); MaxForwardsHeader maxForwards = (MaxForwardsHeader)augustSipStack.getHeaderFactory().createHeader("Max-Forwards", "70"); Header expires = augustSipStack.getHeaderFactory().createHeader("Expires", "600"); ContactHeader contact = augustSipStack.getHeaderFactory().createContactHeader(augustSipStack.getAddressFactory().createAddress( augustSipStack.getAddressFactory().createSipURI(null, "[email protected]:" + augustPort))); Request register = augustSipStack.getMessageFactory().createRequest(uri, "REGISTER", callId, cseq, from, to, vias, maxForwards); register.addHeader(expires); register.addHeader(contact); assertTrue(augustPhone.sendUnidirectionalRequest(register, true)); Thread.sleep(500); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone2.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone2.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(Response.FORBIDDEN, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone2.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); }catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); CallIdHeader callId2 = (CallIdHeader)augustSipStack.getHeaderFactory().createHeader("Call-ID", "67890"); Request cloneRegister = augustSipStack.getMessageFactory().createRequest(uri, "REGISTER", callId2, cseq, from, to, vias, maxForwards); cloneRegister.addHeader(expires); cloneRegister.addHeader(contact); assertTrue(augustPhone.sendUnidirectionalRequest(cloneRegister, true)); Thread.sleep(2000); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); isAugustRegistered = false; } catch(Exception e){ e.printStackTrace(); } } @Test public void testWebRTCClientOutgoingAdisconnect() throws ParseException, InterruptedException, SQLException { logger.info("testWebRTCClientOutgoingAdisconnect"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall,pstnContact,augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-pstn", 3600)); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "OK-pstn", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); pstnCall.listenForDisconnect(); assertTrue(augustCall.disconnect()); assertTrue(pstnCall.waitForDisconnect(5 * 1000)); assertTrue(pstnCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientOutgoingOtherDomain() throws ParseException, InterruptedException, SQLException { logger.info("testWebRTCClientOutgoingAdisconnect"); registerBob(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall bobCall = bobPhone.createSipCall(); initiateBob(pstnCall,pstnContact,bobCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-pstn", 3600)); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "OK-pstn", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(lastReceivedRequest.getRequestEvent().getRequest().getHeader("From").toString().contains("[email protected]")); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); pstnCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(pstnCall.waitForDisconnect(5 * 1000)); assertTrue(pstnCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterBob(); } @Test public void testWebRTCClientOutgoingAHold() throws SipException, ParseException, InterruptedException, InvalidArgumentException { logger.info("testWebRTCClientOutgoingAHold"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall,pstnContact,augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-pstn", 3600)); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "OK-pstn", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); //HOLD - start SipTransaction augustReinviteTx = augustCall.sendReinvite(augustContact, augustContact, body + "a=sendonly", "application", "sdp"); assertTrue(augustCall.waitReinviteResponse(augustReinviteTx, 5 * 1000)); augustCall.sendReinviteOkAck(augustReinviteTx); assertTrue(pstnCall.waitForMessage(5 * 1000)); lastReceivedRequest = pstnCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=onHold")); SipTransaction pstnMessageTx = pstnCall.getLastTransaction(); Request pstnMessage = pstnMessageTx.getServerTransaction().getRequest(); Response pstnMessageAccepted = imsSipStack.getMessageFactory().createResponse(Response.ACCEPTED, pstnMessage); pstnMessageTx.getServerTransaction().sendResponse(pstnMessageAccepted); augustReinviteTx = augustCall.sendReinvite(augustContact, augustContact, body + "a=sendrecv", "application", "sdp"); assertTrue(augustCall.waitReinviteResponse(augustReinviteTx, 5 * 1000)); augustCall.sendReinviteOkAck(augustReinviteTx); assertTrue(pstnCall.waitForMessage(5 * 1000)); lastReceivedRequest = pstnCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=offHold")); pstnMessageTx = pstnCall.getLastTransaction(); pstnMessage = pstnMessageTx.getServerTransaction().getRequest(); pstnMessageAccepted = imsSipStack.getMessageFactory().createResponse(Response.ACCEPTED, pstnMessage); pstnMessageTx.getServerTransaction().sendResponse(pstnMessageAccepted); //HOLD - end Thread.sleep(1000); pstnCall.listenForDisconnect(); assertTrue(augustCall.disconnect()); assertTrue(pstnCall.waitForDisconnect(5 * 1000)); assertTrue(pstnCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientOutgoingBHold() throws SipException, ParseException, InterruptedException, InvalidArgumentException { logger.info("testWebRTCClientOutgoingBHold"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall,pstnContact,augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-pstn", 3600)); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "OK-pstn", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); Thread.sleep(1000); //HOLD - start augustCall.listenForMessage(); SipTransaction pstnReinviteTx = pstnCall.sendReinvite(pstnContact, pstnContact, body + "a=sendonly", "application", "sdp"); assertTrue(pstnCall.waitReinviteResponse(pstnReinviteTx, 5 * 1000)); pstnCall.sendReinviteOkAck(pstnReinviteTx); assertTrue(augustCall.waitForMessage(5 * 1000)); lastReceivedRequest = augustCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=onHold")); SipTransaction augustMessageTx = augustCall.getLastTransaction(); Request augustMessage = augustMessageTx.getServerTransaction().getRequest(); Response augustMessageAccepted = augustSipStack.getMessageFactory().createResponse(Response.ACCEPTED, augustMessage); augustMessageTx.getServerTransaction().sendResponse(augustMessageAccepted); pstnReinviteTx = pstnCall.sendReinvite(pstnContact, pstnContact, body + "a=sendrecv", "application", "sdp"); assertTrue(pstnCall.waitReinviteResponse(pstnReinviteTx, 5 * 1000)); pstnCall.sendReinviteOkAck(pstnReinviteTx); assertTrue(augustCall.waitForMessage(5 * 1000)); lastReceivedRequest = augustCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=offHold")); augustMessageTx = augustCall.getLastTransaction(); augustMessage = augustMessageTx.getServerTransaction().getRequest(); augustMessageAccepted = augustSipStack.getMessageFactory().createResponse(Response.ACCEPTED, augustMessage); augustMessageTx.getServerTransaction().sendResponse(augustMessageAccepted); //HOLD - end Thread.sleep(1000); augustCall.listenForDisconnect(); assertTrue(pstnCall.disconnect()); assertTrue(augustCall.waitForDisconnect(5 * 1000)); assertTrue(augustCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingADisconnect() throws InterruptedException, ParseException { logger.info("testWebRTCClientIncomingADisconnect"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "Ringing-August", 3600)); String receivedBody = new String(augustCall.getLastReceivedRequest().getRawContent()); assertTrue(augustCall.sendIncomingCallResponse(Response.OK, "OK-August", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(augustCall.waitForAck(50 * 1000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); Thread.sleep(1000); // hangup. augustCall.listenForDisconnect(); pstnCall.disconnect(); assertTrue(augustCall.waitForDisconnect(30 * 1000)); assertTrue(augustCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingBusy() throws InterruptedException, ParseException { logger.info("testWebRTCClientIncomingBusy"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-August", 3600)); assertTrue(augustCall.waitForAck(50 * 1000)); pstnCall.listenForDisconnect(); assertTrue(pstnCall.waitForDisconnect(30 * 1000)); assertTrue(pstnCall.respondToDisconnect()); Thread.sleep(1000); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingAHold() throws SipException, InterruptedException, ParseException, InvalidArgumentException { logger.info("testWebRTCClientIncomingAHold"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "Ringing-August", 3600)); String receivedBody = new String(augustCall.getLastReceivedRequest().getRawContent()); assertTrue(augustCall.sendIncomingCallResponse(Response.OK, "OK-August", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(augustCall.waitForAck(50 * 1000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); Thread.sleep(1000); //HOLD - start SipTransaction pstnReinviteTx = pstnCall.sendReinvite(pstnContact, pstnContact, body + "a=sendonly", "application", "sdp"); assertTrue(pstnCall.waitReinviteResponse(pstnReinviteTx, 5 * 1000)); pstnCall.sendReinviteOkAck(pstnReinviteTx); assertTrue(augustCall.waitForMessage(5 * 1000)); SipRequest lastReceivedRequest = augustCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=onHold")); SipTransaction augustMessageTx = augustCall.getLastTransaction(); Request augustMessage = augustMessageTx.getServerTransaction().getRequest(); Response augustMessageAccepted = augustSipStack.getMessageFactory().createResponse(Response.ACCEPTED, augustMessage); augustMessageTx.getServerTransaction().sendResponse(augustMessageAccepted); pstnReinviteTx = pstnCall.sendReinvite(pstnContact, pstnContact, body + "a=sendrecv", "application", "sdp"); assertTrue(pstnCall.waitReinviteResponse(pstnReinviteTx, 5 * 1000)); pstnCall.sendReinviteOkAck(pstnReinviteTx); assertTrue(augustCall.waitForMessage(5 * 1000)); lastReceivedRequest = augustCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=offHold")); augustMessageTx = augustCall.getLastTransaction(); augustMessage = augustMessageTx.getServerTransaction().getRequest(); augustMessageAccepted = augustSipStack.getMessageFactory().createResponse(Response.ACCEPTED, augustMessage); augustMessageTx.getServerTransaction().sendResponse(augustMessageAccepted); //HOLD - end // hangup. augustCall.disconnect(); pstnCall.listenForDisconnect(); assertTrue(pstnCall.waitForDisconnect(30 * 1000)); assertTrue(pstnCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingBHold() throws SipException, InvalidArgumentException, InterruptedException, ParseException { logger.info("testWebRTCClientIncomingBHold"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "Ringing-August", 3600)); String receivedBody = new String(augustCall.getLastReceivedRequest().getRawContent()); assertTrue(augustCall.sendIncomingCallResponse(Response.OK, "OK-August", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(augustCall.waitForAck(50 * 1000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); Thread.sleep(1000); //HOLD - start pstnCall.listenForMessage(); SipTransaction augustReinviteTx = augustCall.sendReinvite(augustContact, augustContact, body + "a=sendonly", "application", "sdp"); assertTrue(augustCall.waitReinviteResponse(augustReinviteTx, 5 * 1000)); augustCall.sendReinviteOkAck(augustReinviteTx); assertTrue(pstnCall.waitForMessage(5 * 1000)); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=onHold")); SipTransaction pstnMessageTx = pstnCall.getLastTransaction(); Request pstnMessage = pstnMessageTx.getServerTransaction().getRequest(); Response pstnMessageAccepted = imsSipStack.getMessageFactory().createResponse(Response.ACCEPTED, pstnMessage); pstnMessageTx.getServerTransaction().sendResponse(pstnMessageAccepted); augustReinviteTx = augustCall.sendReinvite(augustContact, augustContact, body + "a=sendrecv", "application", "sdp"); assertTrue(augustCall.waitReinviteResponse(augustReinviteTx, 5 * 1000)); augustCall.sendReinviteOkAck(augustReinviteTx); assertTrue(pstnCall.waitForMessage(5 * 1000)); lastReceivedRequest = pstnCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=offHold")); pstnMessageTx = pstnCall.getLastTransaction(); pstnMessage = pstnMessageTx.getServerTransaction().getRequest(); pstnMessageAccepted = imsSipStack.getMessageFactory().createResponse(Response.ACCEPTED, pstnMessage); pstnMessageTx.getServerTransaction().sendResponse(pstnMessageAccepted); //HOLD - end // hangup. pstnCall.disconnect(); augustCall.listenForDisconnect(); assertTrue(augustCall.waitForDisconnect(30 * 1000)); assertTrue(augustCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingRequestTimeout() throws InterruptedException, ParseException { logger.info("testWebRTCClientIncomingRequestTimeout"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(5 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "RINGING-pstn", 3600)); SipTransaction augustInviteTx = augustCall.getLastTransaction(); assertTrue(augustCall.listenForCancel()); assertTrue(pstnCall.listenForDisconnect()); Thread.sleep(30000); SipTransaction augustCancelTransaction = augustCall.waitForCancel(5 * 1000); assertTrue(augustCancelTransaction != null); augustCall.respondToCancel(augustCancelTransaction, 200, "OK-pstn", 3600); logger.info("finish waiting"); Request augustInvite = augustInviteTx.getServerTransaction().getRequest(); Response augustResponseTerminated = imsSipStack.getMessageFactory().createResponse(Response.REQUEST_TERMINATED, augustInvite); try{ augustInviteTx.getServerTransaction().sendResponse(augustResponseTerminated); } catch(Exception e){ e.printStackTrace(); } assertTrue(pstnCall.waitForDisconnect(5 * 1000)); assertTrue(pstnCall.respondToDisconnect()); logger.info("august disconnected"); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer public void testWebRTCClientOutgoingBusy() throws ParseException, InterruptedException { logger.info("testWebRTCClientOutgoingBusy"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall,pstnContact,augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Pstn", 3600)); augustCall.listenForDisconnect(); assertTrue(augustCall.waitForDisconnect(30 * 1000)); assertTrue(augustCall.respondToDisconnect()); Thread.sleep(1000); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer public void testUnregisteredWebRTCClientOutgoing() throws ParseException, InterruptedException { logger.info("testUnregisteredWebRTCClientOutgoing"); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = augustSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // August initiates a call to pstn final SipCall augustCall = augustPhone.createSipCall(); URI uri1 = augustSipStack.getAddressFactory().createURI("sip:" + restcommContact); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = augustSipStack.getAddressFactory().createAddress(uri1); RouteHeader routeHeader = augustSipStack.getHeaderFactory().createRouteHeader(address); replaceHeaders.add(routeHeader.toString()); Header user = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-User", "myUser"); Header pass = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-Password", "myPass"); replaceHeaders.add(user.toString()); replaceHeaders.add(pass.toString()); augustCall.initiateOutgoingCall(augustContact, "sip:"+pstnNumber+"@127.0.0.1:5060", null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(augustCall); assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); int responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseAugust == Response.NOT_FOUND); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); } @Test @Category(UnstableTests.class) public void testUnregisteredWebRTCClientIncoming() throws InterruptedException, ParseException { logger.info("testUnregisteredWebRTCClientIncoming"); // Prepare august phone to receive call SipCall augustCall = augustPhone.createSipCall(); augustCall.listenForIncomingCall(); // Create outgoing call with pstn phone final SipCall pstnCall = pstnPhone.createSipCall(); pstnCall.initiateOutgoingCall(pstnContact, augustContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(pstnCall); assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); final int response = pstnCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.NOT_FOUND); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); } @Test @Category(UnstableTests.class) //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer public void testWebRTCClientOutgoingRequestTimeout() throws ParseException, InterruptedException { logger.info("testWebRTCClientOutgoingRequestTimeout"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall,pstnContact,augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-pstn", 3600)); SipTransaction pstnInviteTx = pstnCall.getLastTransaction(); assertTrue(pstnCall.listenForCancel()); assertTrue(augustCall.listenForDisconnect()); Thread.sleep(30000); SipTransaction pstnCancelTransaction = pstnCall.waitForCancel(5 * 1000); assertTrue(pstnCancelTransaction != null); pstnCall.respondToCancel(pstnCancelTransaction, 200, "OK-pstn", 3600); logger.info("finish waiting"); Request pstnInvite = pstnInviteTx.getServerTransaction().getRequest(); Response pstnResponseTerminated = imsSipStack.getMessageFactory().createResponse(Response.REQUEST_TERMINATED, pstnInvite); try{ pstnInviteTx.getServerTransaction().sendResponse(pstnResponseTerminated); } catch(Exception e){ e.printStackTrace(); } assertTrue(augustCall.waitForDisconnect(5 * 1000)); assertTrue(augustCall.respondToDisconnect()); logger.info("august disconnected"); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } private void unregisterAugust() throws InterruptedException{ ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.unregister(augustContact, 3600)); isAugustRegistered = false; Thread.sleep(1000); } private void unregisterBob() throws InterruptedException{ ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsBobPhone.listenRequestMessage(); RequestEvent requestEvent = imsBobPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = bobSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(bobSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsBobPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(bobPhone.unregister(bobContact, 3600)); isBobRegistered = false; Thread.sleep(1000); } private void unregisterJulius() throws InterruptedException{ ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsJuliusPhone.listenRequestMessage(); RequestEvent requestEvent = imsJuliusPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = juliusSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(juliusSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsJuliusPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(juliusPhone.unregister(juliusContact, 3600)); isJuliusRegistered = false; Thread.sleep(1000); } private void registerAugust() throws ParseException, InterruptedException{ SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, restcommContact); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(14400); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.register(uri, "august", "1234", augustContact, 14400, 3600)); isAugustRegistered = true; Thread.sleep(1000); Credential c = new Credential("127.0.0.1", "august", "1234"); augustPhone.addUpdateCredential(c); } private void registerBob() throws ParseException, InterruptedException{ SipURI uri = bobSipStack.getAddressFactory().createSipURI(null, restcommContact); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsBobPhone.listenRequestMessage(); RequestEvent requestEvent = imsBobPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = bobSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(14400); contactHeader.setAddress(bobSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsBobPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(bobPhone.register(uri, "[email protected]", "1234", bobContact, 14400, 3600)); isBobRegistered = true; Thread.sleep(1000); Credential c = new Credential("127.0.0.1", "[email protected]", "1234"); bobPhone.addUpdateCredential(c); } private void initiateAugust(SipCall toCall, String toUri, SipCall augustCall) throws ParseException, InterruptedException { toCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = augustSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // August initiates a call to pstn URI uri1 = augustSipStack.getAddressFactory().createURI("sip:" + restcommContact); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = augustSipStack.getAddressFactory().createAddress(uri1); RouteHeader routeHeader = augustSipStack.getHeaderFactory().createRouteHeader(address); replaceHeaders.add(routeHeader.toString()); Header user = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-User", "myUser"); Header pass = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-Password", "myPass"); replaceHeaders.add(user.toString()); replaceHeaders.add(pass.toString()); augustCall.initiateOutgoingCall(augustContact, toUri, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(augustCall); assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); int responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseAugust == Response.TRYING || responseAugust == Response.RINGING); Dialog augustDialog = null; if (responseAugust == Response.TRYING) { assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, augustCall.getLastReceivedResponse().getStatusCode()); augustDialog = augustCall.getDialog(); assertNotNull(augustDialog); } assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, augustCall.getLastReceivedResponse().getStatusCode()); assertTrue(augustCall.sendInviteOkAck()); assertTrue(toCall.waitForIncomingCall(5 * 1000)); DigestServerAuthenticationMethod dsam = new DigestServerAuthenticationMethod(); dsam.initialize(); // it should read values from file, now all static ProxyAuthenticateHeader proxyAuthenticate = augustSipStack.getHeaderFactory().createProxyAuthenticateHeader( dsam.getScheme()); proxyAuthenticate.setParameter("realm", dsam.getRealm(null)); proxyAuthenticate.setParameter("nonce", dsam.generateNonce()); // proxyAuthenticateImpl.setParameter("domain",authenticationMethod.getDomain()); proxyAuthenticate.setParameter("opaque", ""); proxyAuthenticate.setParameter("algorithm", dsam.getAlgorithm()); ArrayList<Header> headers = new ArrayList<Header>(); headers.add(proxyAuthenticate); assertTrue(toCall.sendIncomingCallResponse(Response.PROXY_AUTHENTICATION_REQUIRED, "Non authorized", 3600, headers, null, null)); } private void initiateBob(SipCall toCall, String toUri, SipCall bobCall) throws ParseException, InterruptedException { toCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = bobSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // Bob initiates a call to pstn URI uri1 = bobSipStack.getAddressFactory().createURI("sip:" + restcommContact); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = bobSipStack.getAddressFactory().createAddress(uri1); RouteHeader routeHeader = bobSipStack.getHeaderFactory().createRouteHeader(address); replaceHeaders.add(routeHeader.toString()); Header user = bobSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-User", "myUser"); Header pass = bobSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-Password", "myPass"); replaceHeaders.add(user.toString()); replaceHeaders.add(pass.toString()); bobCall.initiateOutgoingCall(bobContact, toUri, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); Dialog bobDialog = null; if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); bobDialog = bobCall.getDialog(); assertNotNull(bobDialog); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(toCall.waitForIncomingCall(5 * 1000)); DigestServerAuthenticationMethod dsam = new DigestServerAuthenticationMethod(); dsam.initialize(); // it should read values from file, now all static ProxyAuthenticateHeader proxyAuthenticate = bobSipStack.getHeaderFactory().createProxyAuthenticateHeader( dsam.getScheme()); proxyAuthenticate.setParameter("realm", dsam.getRealm(null)); proxyAuthenticate.setParameter("nonce", dsam.generateNonce()); // proxyAuthenticateImpl.setParameter("domain",authenticationMethod.getDomain()); proxyAuthenticate.setParameter("opaque", ""); proxyAuthenticate.setParameter("algorithm", dsam.getAlgorithm()); ArrayList<Header> headers = new ArrayList<Header>(); headers.add(proxyAuthenticate); assertTrue(toCall.sendIncomingCallResponse(Response.PROXY_AUTHENTICATION_REQUIRED, "Non authorized", 3600, headers, null, null)); } private void initiatePstn(SipCall pstnCall, SipCall augustCall) throws ParseException, InterruptedException { // Prepare august phone to receive call augustCall.listenForIncomingCall(); // Create outgoing call with pstn phone ArrayList<String> replaceHeaders = new ArrayList<String>(); URI uri1 = augustSipStack.getAddressFactory().createURI("sip:august@" + restcommContact); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = augustSipStack.getAddressFactory().createAddress(uri1); ToHeader toHeader = augustSipStack.getHeaderFactory().createToHeader(address, null); replaceHeaders.add(toHeader.toString()); pstnCall.initiateOutgoingCall(pstnContact, "sip:" + restcommContact, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(pstnCall); assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); int responsePstn = pstnCall.getLastReceivedResponse().getStatusCode(); assertTrue(responsePstn == Response.TRYING || responsePstn == Response.RINGING); if (responsePstn == Response.TRYING) { assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, pstnCall.getLastReceivedResponse().getStatusCode()); } } @Deployment(name = "ImsClientsDialTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String, String> webInfResources = new HashMap(); webInfResources.put("restcomm-ims.xml", "conf/restcomm.xml"); webInfResources.put("restcomm.script_imsDialTest", "data/hsql/restcomm.script"); webInfResources.put("sip-ims.xml", "/sip.xml"); webInfResources.put("akka_application.conf", "classes/application.conf"); Map<String, String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5092", String.valueOf(augustPort)); replacements.put("5094", String.valueOf(juliusPort)); replacements.put("5095", String.valueOf(bobPort)); replacements.put("5060", String.valueOf(imsPort)); replacements.put("9999", String.valueOf(imsPort)); List<String> resources = new ArrayList(Arrays.asList( "dial-conference-entry.xml", "dial-fork-entry.xml", "dial-number-entry.xml", "dial-client-entry.xml", "dial-uri-entry.xml" )); return WebArchiveUtil.createWebArchiveNoGw( webInfResources, resources, replacements); } }
76,384
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialConferenceTerminationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialConferenceTerminationTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommConferenceParticipantsTool; import org.restcomm.connect.testsuite.http.RestcommConferenceTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * Created by gvagenas on 5/19/16. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DialConferenceTerminationTest { private final static Logger logger = Logger.getLogger(DialConferenceTerminationTest.class.getName()); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static SipStackTool tool1; private static SipStackTool tool3; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialRestcomm = "sip:1111@"+restcommContact; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialConferenceTool1"); tool3 = new SipStackTool("DialConferenceTool3"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } private int getActiveConferencesSize() { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),adminAccountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); int activeConfSize = 0; for(int i = 0; i < conferenceArray.size(); i++) { JsonObject confObj = conferenceArray.get(i).getAsJsonObject(); String confStatus = confObj.get("status").getAsString(); logger.info("confStatus: "+confStatus); if (confStatus.matches("RUNNING.*")) { activeConfSize++; } } return activeConfSize; } private int getParticipantsSize(final String sid) { JsonObject participants = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, sid); JsonArray participantsArray = participants.getAsJsonArray("calls"); return participantsArray.size(); } private String getConferenceSid(final String name) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),adminAccountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); String confSid = null; for(int i = 0; i < conferenceArray.size(); i++) { JsonObject confObj = conferenceArray.get(i).getAsJsonObject(); String confName = confObj.get("friendly_name").getAsString(); String confStatus = confObj.get("status").getAsString(); logger.info("confStatus: "+confStatus); if (confName.equalsIgnoreCase(name) && confStatus.matches("RUNNING.*")) { confSid = confObj.get("sid").getAsString(); return confSid; } } return null; } private final String confRoom1 = "confRoom1"; private String dialConfernceRcml = "<Response><Dial><Conference>"+confRoom1+"</Conference></Dial></Response>"; @Test public synchronized void testDialConferenceTimeoutTest() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); String conferenceSid = getConferenceSid(confRoom1); assertEquals(2, getParticipantsSize(conferenceSid)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertTrue(mgcpEndpoints>0); assertTrue(mgcpConnections>0); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(80 * 1000)); assertTrue(georgeCall.waitForDisconnect(80 * 1000)); Thread.sleep(1000); assertEquals(0, getActiveConferencesSize()); assertEquals(0, getParticipantsSize(conferenceSid)); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Deployment(name = "DialConferenceTerminationTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm-conference.xml", "restcomm.script_dialTest_new", replacements); } }
13,361
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialRecordingS3UploadAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialRecordingS3UploadAnswerDelayTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Created by gvagenas on 08/01/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class DialRecordingS3UploadAnswerDelayTest { private final static Logger logger = Logger.getLogger(DialRecordingS3UploadAnswerDelayTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private String henriqueContact = "sip:[email protected]:5092"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; private String dialRestcomm = "sip:[email protected]:5080"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice_BobDisconnects() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") // .withHeader("ETag", "1b2cf535f27731c974343645a3985328") .withHeader("Server", "AmazonS3") )); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0,duration,0.5); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); Thread.sleep(5000); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); } @Test public synchronized void testDialClientAlice_AliceDisconnects() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") // .withHeader("ETag", "1b2cf535f27731c974343645a3985328") .withHeader("Server", "AmazonS3") )); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(3000); // hangup. bobCall.listenForDisconnect(); aliceCall.disconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0,duration, 0.5); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); Thread.sleep(5000); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); } @Deployment(name = "DialRecordingS3UploadSecureTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.delete("/WEB-INF/classes/application.conf"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_recording_s3_upload-delay.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest_new", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); logger.info("Packaged Test App"); return archive; } }
14,956
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialRecordingS3UploadSecureTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialRecordingS3UploadSecureTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.http.RecordingEndpointTool; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.deleteRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; /** * Created by gvagenas on 08/01/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DialRecordingS3UploadSecureTest { private final static Logger logger = Logger.getLogger(DialRecordingS3UploadSecureTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private String henriqueContact = "sip:[email protected]:5092"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; private String dialRestcomm = "sip:[email protected]:5080"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice_BobDisconnects() throws InterruptedException, ParseException, IOException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") .withHeader("Server", "AmazonS3") )); stubFor(get(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("X-Amz-Algorithm", "AWS4-HMAC-SHA256") )); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); DateTime start = DateTime.now(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); DateTime end = DateTime.now(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(7000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double recordedDuration = (end.getMillis() - start.getMillis())/1000; double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(recordedDuration, duration,1.0); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("http://127.0.0.1:8080/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); //Since we are in secure mode the s3_uri shouldn't be here assertNull(recording.get(0).getAsJsonObject().get("s3_uri")); URL url = new URL(recording.get(0).getAsJsonObject().get("file_uri").getAsString()); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); assertEquals(200, connection.getResponseCode()); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); } @Test @Category(FeatureAltTests.class) public synchronized void testDialClientAlice_BobDisconnects_AndRemoveRecording() throws InterruptedException, ParseException, IOException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") .withHeader("Server", "AmazonS3") )); stubFor(get(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("X-Amz-Algorithm", "AWS4-HMAC-SHA256") )); stubFor(delete(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("X-Amz-Algorithm", "AWS4-HMAC-SHA256"))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); DateTime start = DateTime.now(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); DateTime end = DateTime.now(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(7000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double recordedDuration = (end.getMillis() - start.getMillis())/1000; double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(recordedDuration, duration,1.0); String recordingSid = recording.get(0).getAsJsonObject().get("sid").getAsString(); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("http://127.0.0.1:8080/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); //Since we are in secure mode the s3_uri shouldn't be here assertNull(recording.get(0).getAsJsonObject().get("s3_uri")); URL url = new URL(recording.get(0).getAsJsonObject().get("file_uri").getAsString()); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); assertEquals(200, connection.getResponseCode()); RecordingEndpointTool.getInstance().deleteRecording(deploymentUrl.toString(), adminAccountSid, adminAuthToken, recordingSid); recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(0, recording.size()); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); verify(1, deleteRequestedFor(urlMatching("/s3/.*"))); } @Test public synchronized void testDialClientAlice_AliceDisconnects() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") // .withHeader("ETag", "1b2cf535f27731c974343645a3985328") .withHeader("Server", "AmazonS3") )); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.listenForDisconnect(); aliceCall.disconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(7000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0,duration, 1.0); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); //Since we are in secure mode the s3_uri shouldn't be here assertNull(recording.get(0).getAsJsonObject().get("s3_uri")); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); } final String recordCall = "<Response><Record timeout=\"15\" maxLength=\"60\"/></Response>"; @Test public synchronized void testRecordCall() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCall))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") // .withHeader("ETag", "1b2cf535f27731c974343645a3985328") .withHeader("Server", "AmazonS3") )); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(1,liveCalls); assertEquals(1, liveCallsArraySize); Thread.sleep(3000); bobCall.disconnect(); Thread.sleep(7000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration,1); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); //Since we are in secure mode the s3_uri shouldn't be here assertNull(recording.get(0).getAsJsonObject().get("s3_uri")); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); } final String recordCallWithAction = "<Response><Record timeout=\"15\" maxLength=\"60\" action=\"http://127.0.0.1:8090/record-action\"/></Response>"; final String hangupRcml = "<Response><Hangup/></Response>"; @Test public synchronized void testRecordCallWithAction() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCallWithAction))); stubFor(post(urlPathEqualTo("/record-action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") // .withHeader("ETag", "1b2cf535f27731c974343645a3985328") .withHeader("Server", "AmazonS3") )); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(1,liveCalls); assertEquals(1, liveCallsArraySize); bobCall.listenForDisconnect(); Thread.sleep(8000); assertTrue(bobCall.waitForDisconnect(5000)); Thread.sleep(1000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(6.0, duration,1); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); //Since we are in secure mode the s3_uri shouldn't be here assertNull(recording.get(0).getAsJsonObject().get("s3_uri")); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); } @Test public synchronized void testRecordCallWithActionWithMaxRecordingReached() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCallWithAction))); stubFor(post(urlPathEqualTo("/record-action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") // .withHeader("ETag", "1b2cf535f27731c974343645a3985328") .withHeader("Server", "AmazonS3") )); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(1,liveCalls); assertEquals(1, liveCallsArraySize); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(70000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(7000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(6.0, duration,0.5); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); //Since we are in secure mode the s3_uri shouldn't be here assertNull(recording.get(0).getAsJsonObject().get("s3_uri")); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); } @Deployment(name = "DialRecordingS3UploadSecureTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.delete("/WEB-INF/classes/application.conf"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_recording_s3_upload_secure.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest_new", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); logger.info("Packaged Test App"); return archive; } }
33,144
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ImsClientsDialAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ImsClientsDialAnswerDelayTest.java
package org.restcomm.connect.testsuite.telephony; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.net.URL; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.sip.Dialog; import javax.sip.InvalidArgumentException; import javax.sip.RequestEvent; import javax.sip.SipException; import javax.sip.address.Address; import javax.sip.address.SipURI; import javax.sip.address.URI; import javax.sip.header.ContactHeader; import javax.sip.header.Header; import javax.sip.header.ProxyAuthenticateHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.header.UserAgentHeader; import javax.sip.header.WWWAuthenticateHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.telephony.security.DigestServerAuthenticationMethod; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; import java.util.Arrays; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Test for clients with or without VoiceURL (Bitbucket issue 115). Clients * without VoiceURL can dial anything. * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, ParallelClassTests.class}) public class ImsClientsDialAnswerDelayTest { private static final String version = Version.getVersion(); private static Logger logger = Logger.getLogger(ImsClientsDialAnswerDelayTest.class); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private String pstnNumber = "+151261006100"; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack augustSipStack; private SipPhone augustPhone; private static String augustPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String augustContact = "sip:[email protected]:" + augustPort; private boolean isAugustRegistered = false; private SipStack juliusSipStack; private SipPhone juliusPhone; private static String juliusPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String juliusContact = "sip:[email protected]:" + juliusPort; private boolean isJuliusRegistered = false; private SipStack imsSipStack; private SipPhone imsAugustPhone; private SipPhone imsJuliusPhone; private static String imsPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String imsContact = "sip:127.0.0.1:" + imsPort; private SipPhone pstnPhone; private String pstnContact = "sip:" + pstnNumber + "@127.0.0.1:" + imsPort; private String adminAccountSid = "AC27f2dd02ab51ba5d5a9ff7fc5537a09a"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("ImsClientsDialTest1"); tool2 = new SipStackTool("ImsClientsDialTest2"); tool3 = new SipStackTool("ImsClientsDialTest3"); Class.forName("org.hsqldb.jdbc.JDBCDriver"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { imsSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", imsPort, restcommContact); augustSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", augustPort, restcommContact); augustPhone = augustSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, augustContact); imsAugustPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, augustContact); imsAugustPhone.setLoopback(true); imsAugustPhone.setPassThroughRegisterRequests(true); juliusSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", juliusPort, restcommContact); juliusPhone = juliusSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, juliusContact); imsJuliusPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, juliusContact); imsJuliusPhone.setLoopback(true); imsJuliusPhone.setPassThroughRegisterRequests(true); pstnPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, pstnContact); pstnPhone.setPassThroughRegisterRequests(true); if (isAugustRegistered) { unregisterAugust(); } if (isJuliusRegistered) { unregisterJulius(); } } @After public void after() throws Exception { if (augustPhone != null) { augustPhone.dispose(); } if (augustSipStack != null) { augustSipStack.dispose(); } if (imsSipStack != null) { imsSipStack.dispose(); } if (imsAugustPhone != null) { imsAugustPhone.dispose(); } if (imsJuliusPhone != null) { imsJuliusPhone.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(3000); } @Test public void testRegisterClients() throws ParseException, InterruptedException, SQLException { logger.info("testRegisterClients"); SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, restcommContact); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(401, requestEvent.getRequest()); WWWAuthenticateHeader wwwAuthenticateHeader = imsSipStack.getHeaderFactory().createWWWAuthenticateHeader("Digest realm=\"ims.tp.pl\",\n" + " nonce=\"b7c9036dbf357f7683f054aea940e9703dc8f84c1108\",\n" + " opaque=\"ALU:QbkRBthOEgEQAkgVEwwHRAIBHgkdHwQCQ1lFRkZWDhMyIXBqLCs0Zj06ZTwhdHpgZmI_\",\n" + " algorithm=MD5,\n" + " qop=\"auth\""); response.setHeader(wwwAuthenticateHeader); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); requestEvent = imsAugustPhone.waitRequest(10000); response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(600); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.register(uri, "august", "1234", augustContact, 3600, 3600)); isAugustRegistered = true; augustPhone.createSipCall().listenForIncomingCall(); Thread.sleep(1000); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.unregister(augustContact, 0)); isAugustRegistered = false; } @Test public void testWebRTCClientOutgoingAdisconnect() throws ParseException, InterruptedException, SQLException { logger.info("testWebRTCClientOutgoingAdisconnect"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall, pstnContact, augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-Pstn", 3600)); Thread.sleep(500); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "OK-Pstn", 3600, receivedBody, "application", "sdp", null, null)); int responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); while (responseAugust != Response.OK) { assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); } assertTrue(augustCall.sendInviteOkAck()); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); pstnCall.listenForDisconnect(); assertTrue(augustCall.disconnect()); assertTrue(pstnCall.waitForDisconnect(5 * 1000)); assertTrue(pstnCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test public void testWebRTCClientOutgoingAHold() throws SipException, ParseException, InterruptedException, InvalidArgumentException { logger.info("testWebRTCClientOutgoingAHold"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall, pstnContact, augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-Pstn", 3600)); Thread.sleep(500); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "OK-Pstn", 3600, receivedBody, "application", "sdp", null, null)); int responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); while (responseAugust != Response.OK) { assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); } assertTrue(augustCall.sendInviteOkAck()); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); //HOLD - start SipTransaction augustReinviteTx = augustCall.sendReinvite(augustContact, augustContact, body + "a=sendonly", "application", "sdp"); assertTrue(augustCall.waitReinviteResponse(augustReinviteTx, 5 * 1000)); augustCall.sendReinviteOkAck(augustReinviteTx); assertTrue(pstnCall.waitForMessage(5 * 1000)); lastReceivedRequest = pstnCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=onHold")); SipTransaction pstnMessageTx = pstnCall.getLastTransaction(); Request pstnMessage = pstnMessageTx.getServerTransaction().getRequest(); Response pstnMessageAccepted = imsSipStack.getMessageFactory().createResponse(Response.ACCEPTED, pstnMessage); pstnMessageTx.getServerTransaction().sendResponse(pstnMessageAccepted); augustReinviteTx = augustCall.sendReinvite(augustContact, augustContact, body + "a=sendrecv", "application", "sdp"); assertTrue(augustCall.waitReinviteResponse(augustReinviteTx, 5 * 1000)); augustCall.sendReinviteOkAck(augustReinviteTx); assertTrue(pstnCall.waitForMessage(5 * 1000)); lastReceivedRequest = pstnCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=offHold")); pstnMessageTx = pstnCall.getLastTransaction(); pstnMessage = pstnMessageTx.getServerTransaction().getRequest(); pstnMessageAccepted = imsSipStack.getMessageFactory().createResponse(Response.ACCEPTED, pstnMessage); pstnMessageTx.getServerTransaction().sendResponse(pstnMessageAccepted); //HOLD - end Thread.sleep(1000); pstnCall.listenForDisconnect(); assertTrue(augustCall.disconnect()); assertTrue(pstnCall.waitForDisconnect(5 * 1000)); assertTrue(pstnCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category({UnstableTests.class}) public void testWebRTCClientOutgoingBHold() throws SipException, ParseException, InterruptedException, InvalidArgumentException { logger.info("testWebRTCClientOutgoingBHold"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall, pstnContact, augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-Pstn", 3600)); Thread.sleep(500); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "OK-Pstn", 3600, receivedBody, "application", "sdp", null, null)); int responseAugust = Response.RINGING; while (responseAugust != Response.OK) { assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); } assertTrue(augustCall.sendInviteOkAck()); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); Thread.sleep(1000); //HOLD - start augustCall.listenForMessage(); SipTransaction pstnReinviteTx = pstnCall.sendReinvite(pstnContact, pstnContact, body + "a=sendonly", "application", "sdp"); assertTrue(pstnCall.waitReinviteResponse(pstnReinviteTx, 5 * 1000)); pstnCall.sendReinviteOkAck(pstnReinviteTx); assertTrue(augustCall.waitForMessage(5 * 1000)); lastReceivedRequest = augustCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=onHold")); SipTransaction augustMessageTx = augustCall.getLastTransaction(); Request augustMessage = augustMessageTx.getServerTransaction().getRequest(); Response augustMessageAccepted = augustSipStack.getMessageFactory().createResponse(Response.ACCEPTED, augustMessage); augustMessageTx.getServerTransaction().sendResponse(augustMessageAccepted); pstnReinviteTx = pstnCall.sendReinvite(pstnContact, pstnContact, body + "a=sendrecv", "application", "sdp"); assertTrue(pstnCall.waitReinviteResponse(pstnReinviteTx, 5 * 1000)); pstnCall.sendReinviteOkAck(pstnReinviteTx); assertTrue(augustCall.waitForMessage(5 * 1000)); lastReceivedRequest = augustCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=offHold")); augustMessageTx = augustCall.getLastTransaction(); augustMessage = augustMessageTx.getServerTransaction().getRequest(); augustMessageAccepted = augustSipStack.getMessageFactory().createResponse(Response.ACCEPTED, augustMessage); augustMessageTx.getServerTransaction().sendResponse(augustMessageAccepted); //HOLD - end Thread.sleep(1000); augustCall.listenForDisconnect(); assertTrue(pstnCall.disconnect()); assertTrue(augustCall.waitForDisconnect(5 * 1000)); assertTrue(augustCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingADisconnect() throws InterruptedException, ParseException { logger.info("testWebRTCClientIncomingADisconnect"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "Ringing-August", 3600)); String receivedBody = new String(augustCall.getLastReceivedRequest().getRawContent()); assertTrue(augustCall.sendIncomingCallResponse(Response.OK, "OK-August", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(augustCall.waitForAck(50 * 1000)); int responsePstn = Response.RINGING; while (responsePstn != Response.OK) { assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); responsePstn = pstnCall.getLastReceivedResponse().getStatusCode(); } assertTrue(pstnCall.sendInviteOkAck()); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); Thread.sleep(1000); // hangup. augustCall.listenForDisconnect(); pstnCall.disconnect(); assertTrue(augustCall.waitForDisconnect(30 * 1000)); assertTrue(augustCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingBusy() throws InterruptedException, ParseException { logger.info("testWebRTCClientIncomingBusy"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-August", 3600)); assertTrue(augustCall.waitForAck(50 * 1000)); int responsePstn = Response.RINGING; while (responsePstn != Response.BUSY_HERE) { assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); responsePstn = pstnCall.getLastReceivedResponse().getStatusCode(); } Thread.sleep(1000); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingFail() throws InterruptedException, ParseException { logger.info("testWebRTCClientIncomingFail"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.SERVICE_UNAVAILABLE, "ServiceUnavailable-August", 3600)); assertTrue(augustCall.waitForAck(50 * 1000)); int responsePstn = Response.RINGING; while (responsePstn != Response.SERVICE_UNAVAILABLE) { assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); responsePstn = pstnCall.getLastReceivedResponse().getStatusCode(); } Thread.sleep(1000); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingAHold() throws SipException, InterruptedException, ParseException, InvalidArgumentException { logger.info("testWebRTCClientIncomingAHold"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "Ringing-August", 3600)); String receivedBody = new String(augustCall.getLastReceivedRequest().getRawContent()); assertTrue(augustCall.sendIncomingCallResponse(Response.OK, "OK-August", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(augustCall.waitForAck(50 * 1000)); int responsePstn = Response.RINGING; while (responsePstn != Response.OK) { assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); responsePstn = pstnCall.getLastReceivedResponse().getStatusCode(); } assertTrue(pstnCall.sendInviteOkAck()); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); Thread.sleep(1000); //HOLD - start SipTransaction pstnReinviteTx = pstnCall.sendReinvite(pstnContact, pstnContact, body + "a=sendonly", "application", "sdp"); assertTrue(pstnCall.waitReinviteResponse(pstnReinviteTx, 5 * 1000)); pstnCall.sendReinviteOkAck(pstnReinviteTx); assertTrue(augustCall.waitForMessage(5 * 1000)); SipRequest lastReceivedRequest = augustCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=onHold")); SipTransaction augustMessageTx = augustCall.getLastTransaction(); Request augustMessage = augustMessageTx.getServerTransaction().getRequest(); Response augustMessageAccepted = augustSipStack.getMessageFactory().createResponse(Response.ACCEPTED, augustMessage); augustMessageTx.getServerTransaction().sendResponse(augustMessageAccepted); pstnReinviteTx = pstnCall.sendReinvite(pstnContact, pstnContact, body + "a=sendrecv", "application", "sdp"); assertTrue(pstnCall.waitReinviteResponse(pstnReinviteTx, 5 * 1000)); pstnCall.sendReinviteOkAck(pstnReinviteTx); assertTrue(augustCall.waitForMessage(5 * 1000)); lastReceivedRequest = augustCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=offHold")); augustMessageTx = augustCall.getLastTransaction(); augustMessage = augustMessageTx.getServerTransaction().getRequest(); augustMessageAccepted = augustSipStack.getMessageFactory().createResponse(Response.ACCEPTED, augustMessage); augustMessageTx.getServerTransaction().sendResponse(augustMessageAccepted); //HOLD - end // hangup. augustCall.disconnect(); pstnCall.listenForDisconnect(); assertTrue(pstnCall.waitForDisconnect(30 * 1000)); assertTrue(pstnCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingBHold() throws SipException, InvalidArgumentException, InterruptedException, ParseException { logger.info("testWebRTCClientIncomingBHold"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "Ringing-August", 3600)); String receivedBody = new String(augustCall.getLastReceivedRequest().getRawContent()); assertTrue(augustCall.sendIncomingCallResponse(Response.OK, "OK-August", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(augustCall.waitForAck(50 * 1000)); int responsePstn = Response.RINGING; while (responsePstn != Response.OK) { assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); responsePstn = pstnCall.getLastReceivedResponse().getStatusCode(); } assertTrue(pstnCall.sendInviteOkAck()); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(2, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); Thread.sleep(1000); //HOLD - start pstnCall.listenForMessage(); SipTransaction augustReinviteTx = augustCall.sendReinvite(augustContact, augustContact, body + "a=sendonly", "application", "sdp"); assertTrue(augustCall.waitReinviteResponse(augustReinviteTx, 5 * 1000)); augustCall.sendReinviteOkAck(augustReinviteTx); assertTrue(pstnCall.waitForMessage(5 * 1000)); SipRequest lastReceivedRequest = pstnCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=onHold")); SipTransaction pstnMessageTx = pstnCall.getLastTransaction(); Request pstnMessage = pstnMessageTx.getServerTransaction().getRequest(); Response pstnMessageAccepted = imsSipStack.getMessageFactory().createResponse(Response.ACCEPTED, pstnMessage); pstnMessageTx.getServerTransaction().sendResponse(pstnMessageAccepted); augustReinviteTx = augustCall.sendReinvite(augustContact, augustContact, body + "a=sendrecv", "application", "sdp"); assertTrue(augustCall.waitReinviteResponse(augustReinviteTx, 5 * 1000)); augustCall.sendReinviteOkAck(augustReinviteTx); assertTrue(pstnCall.waitForMessage(5 * 1000)); lastReceivedRequest = pstnCall.getLastReceivedRequest(); receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(receivedBody.equals("action=offHold")); pstnMessageTx = pstnCall.getLastTransaction(); pstnMessage = pstnMessageTx.getServerTransaction().getRequest(); pstnMessageAccepted = imsSipStack.getMessageFactory().createResponse(Response.ACCEPTED, pstnMessage); pstnMessageTx.getServerTransaction().sendResponse(pstnMessageAccepted); //HOLD - end // hangup. pstnCall.disconnect(); augustCall.listenForDisconnect(); assertTrue(augustCall.waitForDisconnect(30 * 1000)); assertTrue(augustCall.respondToDisconnect()); Thread.sleep(1000); filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingRequestTimeout() throws InterruptedException, ParseException { logger.info("testWebRTCClientIncomingRequestTimeout"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(5 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "RINGING-august", 3600)); assertTrue(augustCall.listenForCancel()); Thread.sleep(30000); SipTransaction augustCancelTransaction = augustCall.waitForCancel(5 * 1000); assertTrue(augustCancelTransaction != null); augustCall.respondToCancel(augustCancelTransaction, 200, "OK-august", 3600); assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TIMEOUT, pstnCall.getLastReceivedResponse().getStatusCode()); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category({UnstableTests.class}) public void testWebRTCClientOutgoingBusy() throws ParseException, InterruptedException { logger.info("testWebRTCClientOutgoingBusy"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall, pstnContact, augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Pstn", 3600)); int responseAugust = Response.RINGING; while (responseAugust != Response.BUSY_HERE) { assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); } Thread.sleep(1000); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category({UnstableTests.class}) public void testWebRTCClientOutgoingFail() throws ParseException, InterruptedException { logger.info("testWebRTCClientOutgoingFail"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall, pstnContact, augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.SERVICE_UNAVAILABLE, "ServiceUnavailable-Pstn", 3600)); int responseAugust = Response.RINGING; while (responseAugust != Response.SERVICE_UNAVAILABLE) { assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); } Thread.sleep(1000); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category({UnstableTests.class}) public void testUnregisteredWebRTCClientOutgoing() throws ParseException, InterruptedException { logger.info("testUnregisteredWebRTCClientOutgoing"); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = augustSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // August initiates a call to pstn final SipCall augustCall = augustPhone.createSipCall(); URI uri1 = augustSipStack.getAddressFactory().createURI("sip:" + restcommContact); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = augustSipStack.getAddressFactory().createAddress(uri1); RouteHeader routeHeader = augustSipStack.getHeaderFactory().createRouteHeader(address); replaceHeaders.add(routeHeader.toString()); Header user = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-User", "myUser"); Header pass = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-Password", "myPass"); replaceHeaders.add(user.toString()); replaceHeaders.add(pass.toString()); augustCall.initiateOutgoingCall(augustContact, "sip:" + pstnNumber + "@127.0.0.1:5060", null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(augustCall); assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); int responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseAugust == Response.NOT_FOUND); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); } @Test @Category({UnstableTests.class}) public void testUnregisteredWebRTCClientIncoming() throws InterruptedException, ParseException { logger.info("testUnregisteredWebRTCClientIncoming"); // Prepare august phone to receive call SipCall augustCall = augustPhone.createSipCall(); augustCall.listenForIncomingCall(); // Create outgoing call with pstn phone final SipCall pstnCall = pstnPhone.createSipCall(); pstnCall.initiateOutgoingCall(pstnContact, augustContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(pstnCall); assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); final int response = pstnCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.NOT_FOUND); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category({UnstableTests.class}) public void testWebRTCClientOutgoingRequestTimeout() throws ParseException, InterruptedException { logger.info("testWebRTCClientOutgoingRequestTimeout"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall, pstnContact, augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-pstn", 3600)); assertTrue(pstnCall.listenForCancel()); Thread.sleep(30000); SipTransaction pstnCancelTransaction = pstnCall.waitForCancel(5 * 1000); assertTrue(pstnCancelTransaction != null); pstnCall.respondToCancel(pstnCancelTransaction, 200, "OK-pstn", 3600); assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TIMEOUT, augustCall.getLastReceivedResponse().getStatusCode()); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } private void unregisterAugust() throws InterruptedException { ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.unregister(augustContact, 3600)); isAugustRegistered = false; Thread.sleep(1000); } private void unregisterJulius() throws InterruptedException { ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsJuliusPhone.listenRequestMessage(); RequestEvent requestEvent = imsJuliusPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = juliusSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(juliusSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsJuliusPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(juliusPhone.unregister(juliusContact, 3600)); isJuliusRegistered = false; Thread.sleep(1000); } private void registerAugust() throws ParseException, InterruptedException { SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, restcommContact); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(14400); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.register(uri, "august", "1234", augustContact, 14400, 3600)); isAugustRegistered = true; Thread.sleep(1000); Credential c = new Credential("127.0.0.1", "august", "1234"); augustPhone.addUpdateCredential(c); } private void initiateAugust(SipCall toCall, String toUri, SipCall augustCall) throws ParseException, InterruptedException { toCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = augustSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // August initiates a call to pstn URI uri1 = augustSipStack.getAddressFactory().createURI("sip:" + restcommContact); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = augustSipStack.getAddressFactory().createAddress(uri1); RouteHeader routeHeader = augustSipStack.getHeaderFactory().createRouteHeader(address); replaceHeaders.add(routeHeader.toString()); Header user = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-User", "myUser"); Header pass = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-Password", "myPass"); replaceHeaders.add(user.toString()); replaceHeaders.add(pass.toString()); augustCall.initiateOutgoingCall(augustContact, toUri, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(augustCall); assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); int responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseAugust == Response.TRYING || responseAugust == Response.RINGING); Dialog augustDialog = null; if (responseAugust == Response.TRYING) { assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, augustCall.getLastReceivedResponse().getStatusCode()); augustDialog = augustCall.getDialog(); assertNotNull(augustDialog); } assertTrue(toCall.waitForIncomingCall(5 * 1000)); DigestServerAuthenticationMethod dsam = new DigestServerAuthenticationMethod(); dsam.initialize(); // it should read values from file, now all static ProxyAuthenticateHeader proxyAuthenticate = augustSipStack.getHeaderFactory().createProxyAuthenticateHeader( dsam.getScheme()); proxyAuthenticate.setParameter("realm", dsam.getRealm(null)); proxyAuthenticate.setParameter("nonce", dsam.generateNonce()); // proxyAuthenticateImpl.setParameter("domain",authenticationMethod.getDomain()); proxyAuthenticate.setParameter("opaque", ""); proxyAuthenticate.setParameter("algorithm", dsam.getAlgorithm()); ArrayList<Header> headers = new ArrayList<Header>(); headers.add(proxyAuthenticate); assertTrue(toCall.sendIncomingCallResponse(Response.PROXY_AUTHENTICATION_REQUIRED, "Non authorized", 3600, headers, null, null)); } private void initiatePstn(SipCall pstnCall, SipCall augustCall) throws ParseException, InterruptedException { // Prepare august phone to receive call augustCall.listenForIncomingCall(); // Create outgoing call with pstn phone ArrayList<String> replaceHeaders = new ArrayList<String>(); URI uri1 = augustSipStack.getAddressFactory().createURI(augustContact); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = augustSipStack.getAddressFactory().createAddress(uri1); ToHeader toHeader = augustSipStack.getHeaderFactory().createToHeader(address, null); replaceHeaders.add(toHeader.toString()); pstnCall.initiateOutgoingCall(pstnContact, "sip:" + restcommContact, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(pstnCall); assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); int responsePstn = pstnCall.getLastReceivedResponse().getStatusCode(); assertTrue(responsePstn == Response.TRYING || responsePstn == Response.RINGING); } @Deployment(name = "ImsClientsDialTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String, String> webInfResources = new HashMap(); webInfResources.put("restcomm-ims-delay.xml", "conf/restcomm.xml"); webInfResources.put("restcomm.script_imsDialTest", "data/hsql/restcomm.script"); webInfResources.put("sip-ims.xml", "/sip.xml"); webInfResources.put("web.xml", "web.xml"); webInfResources.put("akka_application.conf", "classes/application.conf"); Map<String, String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5092", String.valueOf(augustPort)); replacements.put("5094", String.valueOf(juliusPort)); replacements.put("5060", String.valueOf(imsPort)); replacements.put("9999", String.valueOf(imsPort)); List<String> resources = new ArrayList(Arrays.asList( "dial-conference-entry.xml", "dial-fork-entry.xml", "dial-number-entry.xml", "dial-client-entry.xml", "dial-uri-entry.xml" )); return WebArchiveUtil.createWebArchiveNoGw( webInfResources, resources, replacements); } }
56,813
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallRegexTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/CallRegexTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sip.DialogState; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; /** * Test for Regex for IncomingPhoneNumbers * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class CallRegexTest { private final static Logger logger = Logger.getLogger(CallRegexTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; // subaccountclient is a simple SIP Client. Will register with Restcomm private SipStack subAccountClientSipStack; private SipPhone subAccountClientPhone; private static String subAccountPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String subAccountClientContact = "sip:[email protected]:" + subAccountPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String subAccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; private String subAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); tool5 = new SipStackTool("DialActionTest5"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); subAccountClientSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", subAccountPort, restcommContact); subAccountClientPhone = subAccountClientSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, subAccountClientContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (subAccountClientPhone != null) { subAccountClientPhone.dispose(); } if (subAccountClientSipStack != null) { subAccountClientSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test public void testDialClientAlice7777() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "7777|8888" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:7777@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice8888() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "7777|8888" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:8888@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice7711133() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^*77...33#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*7711133#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice7722233() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^*77...33#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*7722233#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice12233() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^[12]2233#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:12233#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice22233() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^[12]2233#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:22233#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice222_888_999_500() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^\\*222\\*...\\*...\\*500#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*222*888*999*500#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice222_333_444_500() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^\\*222\\*...\\*...\\*500#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*222*333*444*500#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice42342() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "[45]234[23]" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:42342@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice52343() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "[45]234[23]" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:52343@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice999111() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "999..." stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:999111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice999222() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "999..." stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:999222@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAliceNoRegex() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "999..." stubFor(get(urlPathEqualTo("/1313")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1313@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1313"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAliceStar() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "*" stubFor(get(urlPathEqualTo("/regexAll")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:987654321@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regexAll"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } static String ussdClientRequestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<ussd-data>\n" + "\t<language value=\"en\"/>\n" + "\t<ussd-string value=\"5544\"/>\n" + "</ussd-data>"; static String ussdRestcommResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ussd-data>\n" + "<language value=\"en\"></language>\n" + "<ussd-string value=\"The information you requested is 1234567890\"></ussd-string>\n" + "<anyExt>\n" + "<message-type>processUnstructuredSSRequest_Response</message-type>\n" + "</anyExt>\n" + "</ussd-data>\n"; private String ussdRcml = "<Response><UssdMessage>The information you requested is 1234567890</UssdMessage></Response>"; @Test public void testUssdPull() { stubFor(get(urlPathEqualTo("/ussd")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(ussdRcml))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*777#@" + restcommContact, null, ussdClientRequestBody, "application", "vnd.3gpp.ussd+xml", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING); } else { assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(bobCall.getDialog().getState().getValue()== DialogState._CONFIRMED); assertTrue(bobCall.listenForDisconnect()); assertTrue(bobCall.waitForDisconnect(30 * 1000)); bobCall.respondToDisconnect(); SipRequest bye = bobCall.getLastReceivedRequest(); String receivedUssdPayload = new String(bye.getRawContent()); assertTrue(receivedUssdPayload.equalsIgnoreCase(ussdRestcommResponse.trim())); bobCall.dispose(); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); replacements.put("5093", String.valueOf(subAccountPort)); List<String> resources = new ArrayList(Arrays.asList("dial-client-entry_wActionUrl.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm_callRegex.xml", "restcomm.script_callRegexTest",resources, replacements); } }
88,766
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TestDialVerbPartTwo.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestDialVerbPartTwo.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import gov.nist.javax.sip.header.ContentType; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import javax.sip.Dialog; import javax.sip.SipException; import javax.sip.address.SipURI; import javax.sip.header.FromHeader; import javax.sip.message.Request; import javax.sip.message.Response; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import java.util.ArrayList; import java.util.Arrays; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Test for Dial verb. Will test Dial Conference, Dial URI, Dial Client, Dial Number and Dial Fork * * @author <a href="mailto:[email protected]">gvagenas</a> * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(ParallelClassTests.class) public class TestDialVerbPartTwo { private final static Logger logger = Logger.getLogger(TestDialVerbPartTwo.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); // No-args constructor defaults to port 8080 private String dialClientWithRecordingRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\" action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\"><Client>alice</Client></Dial></Response>"; private String dialConferenceWithDialActionRcml = "<Response><Dial action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\"><Conference>test</Conference></Dial></Response>"; private String dialClientWithRecordingRcml2 = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\" action=\"http://127.0.0.1:" + mockPort + "/action&sticky_numToDial=00306986971731\" method=\"GET\"><Client>alice</Client></Dial></Response>"; private String dialRecordWithActionRcml = "<Response><Record action=\"http://127.0.0.1:" + mockPort + "/recordAction\" method=\"GET\" finishOnKey=\"*\" maxLength=\"10\" playBeep=\"true\"/></Response>"; private String dialClientWithActionRcml = "<Response><Dial action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\"><Client>alice</Client></Dial></Response>"; private String dialTimeOutClientWithActionRcml = "<Response><Dial timeout=\"3\" action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\"><Client>alice</Client></Dial></Response>"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + georgePort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialRestcomm = "sip:1111@" + restcommContact; private static String dialRestcommWithStatusCallback = "sip:7777@" + restcommContact; private static String dialNumberNoCallerId = "<Response><Dial><Number url=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; private static String dialNumberRcml = "<Response><Dial callerId=\"+13055872294\"><Number url=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialTest2Tool1"); tool2 = new SipStackTool("DialTest2Tool2"); tool3 = new SipStackTool("DialTest2Tool3"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialRestcomm = "sip:1111@" + restcommContact; dialRestcommWithStatusCallback = "sip:7777@" + restcommContact; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); dialNumberNoCallerId = "<Response><Dial><Number url=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; dialNumberRcml = "<Response><Dial callerId=\"+13055872294\"><Number url=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); /* these will only work in Java8, but seems unccesary wireMockRule.resetMappings(); wireMockRule.resetScenarios();*/ Thread.sleep(2000); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; //Test for issue RESTCOMM-617 @Test @Category(FeatureAltTests.class) public synchronized void testDialClientAliceToBigDID() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } private String sendSmsActionRcml = "<Response>\n" + "\t\t\t<Sms to=\"bob\" from=\"+12223334499\">Hello World!</Sms>\n" + "</Response>"; @Test @Category(UnstableTests.class) public synchronized void testDialClientAliceWithRecord() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithRecordingRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); assertEquals(7.0, ((JsonObject)recordings.get(0)).get("duration").getAsDouble(), 0.5); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); } @Test @Category(UnstableTests.class) public synchronized void testDialClientAliceWithRecord2() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithRecordingRcml2))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(10000); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); assertEquals(7.0, ((JsonObject)recordings.get(0)).get("duration").getAsDouble(), 0.5); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); } @Test @Category(FeatureAltTests.class) public synchronized void testDialConferenceWithDialActionSms() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConferenceWithDialActionRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //Now bob is connected to the conference room Thread.sleep(7000); // hangup. bobCall.disconnect(); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); } @Test @Category(FeatureAltTests.class) public synchronized void testDialConferenceWithDialActionNoRcml() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConferenceWithDialActionRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //Now bob is connected to the conference room Thread.sleep(7000); // hangup. bobCall.disconnect(); assertTrue(bobCall.waitForAnswer(5000)); } private String dialConferenceNoDialActionSendSMSRcml = "<Response><Dial><Conference>test</Conference></Dial>" + "<Sms to=\"bob\" from=\"+12223334499\">Hello World!</Sms></Response>"; private String dialConferenceNoDialActionRcml = "<Response><Dial><Conference>test</Conference></Dial></Response>"; @Test @Category({UnstableTests.class, FeatureAltTests.class}) public synchronized void testDialConferenceNoDialAction_SendSms() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConferenceNoDialActionSendSMSRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //Now bob is connected to the conference room Thread.sleep(7000); // hangup. bobCall.disconnect(); assertTrue(bobCall.waitForAnswer(5000)); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); } @Test @Category(FeatureAltTests.class) public synchronized void testDialConferenceNoDialAction_NoSms() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConferenceNoDialActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //Now bob is connected to the conference room Thread.sleep(7000); // hangup. bobCall.disconnect(); assertTrue(bobCall.waitForAnswer(5000)); } @Test //Test case for issue 320 @Category(FeatureAltTests.class) public synchronized void testDialClientAliceWithRecordAndStatusCallbackForApp() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithRecordingRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcommWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); assertEquals(7.0, ((JsonObject)recordings.get(0)).get("duration").getAsDouble(), 0.5); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); logger.info("About to check the Status Callback Requests"); Map<String, String> statusCallbacks = new HashMap<String,String>(); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); assertEquals(3,requests.size()); // for (LoggedRequest loggedRequest : requests) { // String queryParam = loggedRequest.getUrl().replaceFirst("/StatusCallBack?", ""); // String[] params = queryParam.split("&"); // String callSid = params[0].split("=")[1]; // String callStatus = params[4].split("=")[1]; // if (statusCallbacks.containsKey(callSid)) { // statusCallbacks.remove(callSid); // } // statusCallbacks.put(callSid, callStatus); // } // assertTrue(statusCallbacks.size()==1); // Iterator<String> iter = statusCallbacks.keySet().iterator(); // while (iter.hasNext()) { // String key = iter.next(); // assertTrue(statusCallbacks.get(key).equalsIgnoreCase("completed")); // } } @Test //Test case for issue 320 @Category({UnstableTests.class,FeatureAltTests.class}) public synchronized void testDialClientAliceWithRecordAndStatusCallbackForAppForThreeCalls() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithRecordingRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcommWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); int recordingsSize = recordings.size(); logger.info("Recording Size: "+recordingsSize); assertTrue(recordingsSize >= 1 || recordingsSize <= 3); assertEquals(7.0, ((JsonObject)recordings.get(0)).get("duration").getAsDouble(), 0.5); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); /* * Start the second call */ Thread.sleep(2000); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(3000); recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue(recordings.size() >= 2); double duration = recordings.get(1).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration, 0.5); assertNotNull(((JsonObject)recordings.get(1)).get("uri").getAsString()); /* * Start the third call */ Thread.sleep(2000); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); bobCall.stopListeningForRequests(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(3000); recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue(recordings.size() >= 3); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(2)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(2)).get("uri").getAsString()); logger.info("About to check the Status Callback Requests"); Map<String, String> statusCallbacks = new HashMap<String,String>(); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); assertTrue(requests.size() == 3); // for (LoggedRequest loggedRequest : requests) { // String queryParam = loggedRequest.getUrl().replaceFirst("/StatusCallBack?", ""); // String[] params = queryParam.split("&"); // String callSid = params[0].split("=")[1]; // String callStatus = params[4].split("=")[1]; // if (statusCallbacks.containsKey(callSid)) { // statusCallbacks.remove(callSid); // } // statusCallbacks.put(callSid, callStatus); // } // assertTrue(statusCallbacks.size()==3); // Iterator<String> iter = statusCallbacks.keySet().iterator(); // while (iter.hasNext()) { // String key = iter.next(); // assertTrue(statusCallbacks.get(key).equalsIgnoreCase("completed")); // } } @Test //Test case for github issue 859 public synchronized void testRecordWithActionAndStatusCallbackForAppWithDisconnectFromBob() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialRecordWithActionRcml))); stubFor(get(urlPathEqualTo("/recordAction")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcommWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //Here we have Restcomm voice mail app for 10 sec Thread.sleep(9000); // hangup. bobCall.disconnect(); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); double recordingDuration = ((JsonObject)recordings.get(0)).get("duration").getAsDouble(); assertTrue(recordingDuration <= 9.0 || recordingDuration <= 10.0); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); logger.info("About to check the Status Callback Requests"); Map<String, String> statusCallbacks = new HashMap<String,String>(); List<LoggedRequest> statusCallbackRequests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); assertTrue(statusCallbackRequests.size()==3); List<LoggedRequest> recordActionRequests = findAll(getRequestedFor(urlPathMatching("/recordAction.*"))); assertTrue(recordActionRequests.size()==1); } @Test @Category(UnstableTests.class) //Test case for github issue 859 public synchronized void testRecordWithActionAndStatusCallbackForAppWithBobSendsFinishKey() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialRecordWithActionRcml))); stubFor(get(urlPathEqualTo("/recordAction")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcommWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //Here we have Restcomm voice mail app for 10 sec Thread.sleep(5000); Dialog dialog = bobCall.getDialog(); String infoBody = "\n" + "Signal=*\n" + "Duration=28"; Request info = null; try { info = dialog.createRequest(Request.INFO); } catch (SipException e) { e.printStackTrace(); } ContentType contentType = new ContentType(); contentType.setContentType("application"); contentType.setContentSubType("dtmf-relay"); info.setContent(infoBody.getBytes(), contentType); String ruri = info.getRequestURI().toString(); SipTransaction infoTransaction = bobPhone.sendRequestWithTransaction(info, false, dialog); assertNotNull(infoTransaction); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); double recordingDuration = ((JsonObject)recordings.get(0)).get("duration").getAsDouble(); assertTrue(recordingDuration <= 9.0 || recordingDuration <= 10.0); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); logger.info("About to check the Status Callback Requests"); Map<String, String> statusCallbacks = new HashMap<String,String>(); List<LoggedRequest> statusCallbackRequests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); assertTrue(statusCallbackRequests.size()==3); List<LoggedRequest> recordActionRequests = findAll(getRequestedFor(urlPathMatching("/recordAction.*"))); assertTrue(recordActionRequests.size()==1); } @Test public synchronized void testDialNumberGeorge() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); final SipRequest lastRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // the number dialed uses a callerId of "+13055872294", which is what George should receive String contactHeader = georgeCall.getLastReceivedRequest().getMessage().getHeader("Contact").toString().replaceAll("\r\n",""); assertTrue(contactHeader.equalsIgnoreCase("Contact: \"+13055872294\" <sip:+13055872294@" + restcommContact + ">")); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(!bobCall.callTimeoutOrError()); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); assertTrue(georgeCall.respondToDisconnect()); } private String dialNumberRcmlWrongScreeningUrl = "<Response><Dial callerId=\"+13055872294\"><Number url=\"/restcomm/invalid.xml\">131313</Number></Dial></Response>"; @Test @Category(FeatureAltTests.class) public synchronized void testDialNumberGeorgeWithWrongScreeningUrl() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcmlWrongScreeningUrl))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); final SipRequest lastRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // the number dialed uses a callerId of "+13055872294", which is what George should receive String contactHeader = georgeCall.getLastReceivedRequest().getMessage().getHeader("Contact").toString().replaceAll("\r\n",""); assertTrue(contactHeader.equalsIgnoreCase("Contact: \"+13055872294\" <sip:+13055872294@" + restcommContact + ">")); assertTrue(georgeCall.waitForAck(50 * 1000)); //Since the Screening URL is not valid, Restcomm will disconnect call bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); assertTrue(georgeCall.respondToDisconnect()); // Thread.sleep(3000); // georgeCall.listenForDisconnect(); // // hangup. // bobCall.disconnect(); // assertTrue(!bobCall.callTimeoutOrError()); // assertTrue(georgeCall.waitForDisconnect(30 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } //Non-regression test for https://github.com/Mobicents/RestComm/issues/505 @Test @Category(FeatureExpTests.class) public synchronized void testDialNumberGeorge_403Forbidden() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); // SipURI uri = bobSipStack.getAddressFactory().createSipURI(null, restcommContact); // assertTrue(bobPhone.register(uri, "bob", "1234", bobContact, 3600, 3600)); // // Credential c = new Credential("127.0.0.1", "bob", "1234"); // bobPhone.addUpdateCredential(c); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.FORBIDDEN, "FORBIDDEN-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); } //Non-regression test for https://github.com/Mobicents/RestComm/issues/505 @Test @Category(FeatureExpTests.class) public synchronized void testDialNumberGeorge_404_OnBye() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); bobCall.disconnect(); georgeCall.listenForDisconnect(); georgeCall.waitForDisconnect(5000); georgeCall.respondToDisconnect(404, "Not Here"); georgeCall.disposeNoBye(); } //Test for Issue 210: https://telestax.atlassian.net/browse/RESTCOMM-210 //Bob callerId should pass to the call created by Dial Number @Test public synchronized void testDialNumberGeorgePassInitialCallerId() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberNoCallerId))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); SipRequest georgeInvite = georgeCall.getLastReceivedRequest(); assertTrue(((FromHeader)georgeInvite.getMessage().getHeader("From")).getAddress().getDisplayName().contains("bob")); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); assertTrue(georgeCall.respondToDisconnect()); } private String didRcml = "<Response><Play>/restcomm/audio/demo-prompt.wav</Play></Response>"; @Test @Category(FeatureAltTests.class) public synchronized void testDialNumberWithPlusSign() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/12349876543")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(didRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:+12349876543@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); Thread.sleep(3000); assertTrue(bobCall.waitForDisconnect(10000)); assertTrue(bobCall.respondToDisconnect()); } @Test @Category(FeatureAltTests.class) public synchronized void testDialNumberWithOUTPlusSign() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/12349876543")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(didRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:12349876543@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); Thread.sleep(3000); assertTrue(bobCall.waitForDisconnect(10000)); assertTrue(bobCall.respondToDisconnect()); } @Test @Category(FeatureExpTests.class) public synchronized void testDialNumberNoCountryAccessCode() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/12349876543")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(didRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:2349876543@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.NOT_FOUND); } private String rejectRejectedRcml = "<Response>" + "<Reject reason=\"rejected\"/>" + "<Dial><Number>131313</Number></Dial>" + "</Response>"; @Test public synchronized void testDialNumberRejectRejectedRcml() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rejectRejectedRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.DECLINE, bobCall.getLastReceivedResponse().getStatusCode()); } private String rejectBusyRcml = "<Response>" + "<Reject reason=\"busy\"/>" + "<Dial><Number>131313</Number></Dial>" + "</Response>"; @Test public synchronized void testDialNumberRejectBusyRcml() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rejectBusyRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.BUSY_HERE, bobCall.getLastReceivedResponse().getStatusCode()); } private String hangupActionRcml = "<Response><Hangup /></Response>"; @Category(UnstableTests.class) @Test // (customised from testDialClientAliceWithRecordAndStatusCallbackForApp) public synchronized void testDialClientAliceWithActionAndStatusCallbackForApp() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithActionRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupActionRcml))); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcommWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(3 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5 * 1000)); Thread.sleep(3000); // hangup (must be as alice, the callee, hanging up in order to test the specific issue found) aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(3 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(5000); logger.info("About to check the Status Callback Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); for (LoggedRequest loggedRequest : requests) { logger.info("Status callback received: " + loggedRequest.getUrl()); } assertTrue(requests.size()==3); } @Test // (customised from testDialClientAliceWithRecordAndStatusCallbackForApp) @Category(FeatureAltTests.class) public synchronized void testDialTimeOutClientAliceWithActionAndStatusCallbackForApp() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialTimeOutClientWithActionRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupActionRcml))); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcommWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(3 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); aliceCall.listenForCancel(); SipTransaction cancelTransaction = aliceCall.waitForCancel(100 * 1000); assertNotNull(cancelTransaction); assertTrue(aliceCall.respondToCancel(cancelTransaction, Response.OK, "Alice-OK-2-Cancel", 3600)); // hangup (must be as alice, the callee, hanging up in order to test the specific issue found) bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(3 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(5000); logger.info("About to check the Status Callback Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); for (LoggedRequest loggedRequest : requests) { logger.info("Status callback received: " + loggedRequest.getUrl()); } assertEquals(3, requests.size()); } @Deployment(name = "TestDialVerbPartTwo", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); List<String> resources = new ArrayList(Arrays.asList("hello-play.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm.xml", "restcomm.script_dialTest_new",resources, replacements); } }
81,038
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialActionOrganizationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialActionOrganizationTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import javax.sip.Dialog; import javax.sip.ListeningPoint; import javax.sip.address.Hop; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mobicents.api.annotations.GetDeployableContainer; import org.jboss.arquillian.container.mss.extension.ContainerManagerTool; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.spi.client.container.DeploymentException; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.mobicents.ext.javax.sip.dns.DNSLookupPerformer; import org.mobicents.ext.javax.sip.dns.DefaultDNSLookupPerformer; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.http.RestcommConferenceParticipantsTool; import org.restcomm.connect.testsuite.http.RestcommConferenceTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import org.xbill.DNS.DClass; import org.xbill.DNS.NAPTRRecord; import org.xbill.DNS.Name; import org.xbill.DNS.Record; import org.xbill.DNS.SRVRecord; import org.xbill.DNS.TextParseException; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import gov.nist.javax.sip.stack.HopImpl; import org.junit.experimental.categories.Category; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; /** * Test for Dial Action attribute for organization * * @author maria * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={WithInMinsTests.class, SequentialClassTests.class}) public class DialActionOrganizationTest { private final static Logger logger = Logger.getLogger(DialActionOrganizationTest.class.getName()); private static final String TRANSPORT = "udp"; private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @GetDeployableContainer private ContainerManagerTool containerManager; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; private static SipStackTool tool6; private static SipStackTool tool7; private static SipStackTool tool8; private SipStack bobSipStackOrg2; private SipPhone bobPhoneOrg2; private String bobContactOrg2 = "sip:[email protected]"; private SipStack bobSipStackOrg3; private SipPhone bobPhoneOrg3; private String bobContactOrg3 = "sip:[email protected]"; private SipStack bobSipStackDefaultOrg; private SipPhone bobPhoneDefaultOrg; private String bobContactDefaultOrg = "sip:[email protected]:5096"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. Alice belong to organization org2.restcomm.com private SipStack aliceSipStackOrg2; private SipPhone alicePhoneOrg2; private String aliceContactOrg2 = "sip:[email protected]"; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStackOrg2; private SipPhone mariaPhoneOrg2; private String mariaContactOrg2 = "sip:[email protected]"; // Shoaibs is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack shoaibSipStackOrg2; private SipPhone shoaibPhoneOrg2; private String shoaibContactOrg2 = "sip:[email protected]"; // pstn is a simple SIP Client. Will not register with Restcomm private SipStack pstnSipStack; private SipPhone pstnPhone; private String pstnContact = "sip:[email protected]:5070"; private String clientPassword = "qwerty1234RT"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. Alice belong to organization: org3.restcomm.com private SipStack aliceSipStackOrg3; private SipPhone alicePhoneOrg3; private String aliceContactOrg3 = "sip:[email protected]"; private String providerNumberOrg2 = "sip:[email protected]"; // Application: dial-number-entry_wActionUrl.xml private String pureSipNumberOrg3 = "sip:[email protected]"; // Application: dial-client-entry_wActionUrl.xml private String numberWithDefaultDomain = "sip:[email protected]:5080"; // Application: dial-client-entry_wActionUrl.xml private String dialClientWithActionUrlOrg2 = "sip:[email protected]"; // Application: dial-client-entry_wActionUrl.xml private String dialClientWithActionUrlOrg3 = "sip:[email protected]"; // Application: dial-client-entry_wActionUrl.xml of organization: org3.restcomm.com private String dialRestcommOrg2 = "sip:[email protected]"; private String dialRestcommOrg3 = "sip:[email protected]"; private final String confRoom2 = "confRoom2"; private String dialConfernceRcml = "<Response><Dial><Conference>"+confRoom2+"</Conference></Dial></Response>"; private String dialNumberRcml = "<Response><Dial><Number>+131313</Number></Dial></Response>"; private String dialSipRcmlOrg2 = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Sip>sip:[email protected]</Sip></Dial></Response>"; private String superAdminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAccountSidOrg2 = "ACae6e420f425248d6a26948c17a9e2acg"; private String adminAccountSidOrg3 = "ACae6e420f425248d6a26948c17a9e2ach"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static final String HOST_ORG2 = "org2.restcomm.com"; private static final String HOST_ORG3 = "org3.restcomm.com"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); tool5 = new SipStackTool("DialActionTest5"); tool6 = new SipStackTool("DialActionTest6"); tool7 = new SipStackTool("DialActionTest7"); tool8 = new SipStackTool("DialActionTest8"); } @Before public void before() throws Exception { bobSipStackOrg2 = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhoneOrg2 = bobSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContactOrg2); aliceSipStackOrg2 = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhoneOrg2 = aliceSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContactOrg2); bobSipStackOrg3 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); bobPhoneOrg3 = bobSipStackOrg3.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContactOrg3); mariaSipStackOrg2 = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5093", "127.0.0.1:5080"); mariaPhoneOrg2 = mariaSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContactOrg2); shoaibSipStackOrg2 = tool6.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5094", "127.0.0.1:5080"); shoaibPhoneOrg2 = shoaibSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, shoaibContactOrg2); aliceSipStackOrg3 = tool7.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5095", "127.0.0.1:5080"); alicePhoneOrg3 = aliceSipStackOrg3.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContactOrg3); bobSipStackDefaultOrg = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5096", "127.0.0.1:5080"); bobPhoneDefaultOrg = bobSipStackDefaultOrg.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContactDefaultOrg); pstnSipStack = tool8.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); pstnPhone = pstnSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, pstnContact); } private void mockDNSLookup(String host, String transport) throws TextParseException { DNSLookupPerformer dnsLookupPerformer = mock(DefaultDNSLookupPerformer.class); //mocking the DNS Lookups to match our test cases containerManager.getSipStandardService().getSipApplicationDispatcher().getDNSServerLocator().setDnsLookupPerformer(dnsLookupPerformer); Set<String> supportedTransports = new HashSet<String>(); supportedTransports.add(TRANSPORT.toUpperCase()); supportedTransports.add(ListeningPoint.TCP.toUpperCase()); supportedTransports.add(ListeningPoint.TLS.toUpperCase()); Queue<Hop> hops = new ConcurrentLinkedQueue(); hops = new ConcurrentLinkedQueue(); //dont use "localhost" or DNS will not work (wouldnt be external) hops.add(new HopImpl("127.0.0.1", 5080, transport)); when(dnsLookupPerformer.locateHopsForNonNumericAddressWithPort("localhost", 5080, transport)).thenReturn(hops); when(dnsLookupPerformer.locateHopsForNonNumericAddressWithPort("localhost", 5082, transport)).thenReturn(null); when(dnsLookupPerformer.locateHopsForNonNumericAddressWithPort("localhost", 5081, transport)).thenReturn(null); List<NAPTRRecord> mockedNAPTRRecords = new LinkedList<NAPTRRecord>(); // mocking the name because localhost is not absolute and localhost. cannot be resolved Name name = mock(Name.class); when(name.isAbsolute()).thenReturn(true); when(name.toString()).thenReturn("localhost"); mockedNAPTRRecords.add(new NAPTRRecord(new Name(host + "."), DClass.IN, 1000, 0, 0, "s", "SIP+D2U", "", new Name("_sip._" + TRANSPORT.toLowerCase() + "." + host + "."))); when(dnsLookupPerformer.performNAPTRLookup(host, false, supportedTransports)).thenReturn(mockedNAPTRRecords); List<Record> mockedSRVRecords = new LinkedList<Record>(); mockedSRVRecords.add(new SRVRecord(new Name("_sip._" + TRANSPORT.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5080, name)); mockedSRVRecords.add(new SRVRecord(new Name("_sip._" + TRANSPORT.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 0, 0, 5081, name)); when(dnsLookupPerformer.performSRVLookup("_sip._" + TRANSPORT.toLowerCase() + "." + host)).thenReturn(mockedSRVRecords); List<Record> mockedSRVTCPRecords = new LinkedList<Record>(); mockedSRVTCPRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5080, name)); mockedSRVTCPRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 0, 0, 5081, name)); // mockedSRVTLSRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TLS.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5081, name)); when(dnsLookupPerformer.performSRVLookup("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host)).thenReturn(mockedSRVTCPRecords); List<Record> mockedSRVTLSRecords = new LinkedList<Record>(); mockedSRVTLSRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5080, name)); mockedSRVTLSRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 0, 0, 5081, name)); // mockedSRVTLSRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TLS.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5081, name)); when(dnsLookupPerformer.performSRVLookup("_sips._" + ListeningPoint.TLS.toLowerCase() + "." + host)).thenReturn(mockedSRVTLSRecords); } @Ignore @Test public void testDialSipNumberSameAndDifferentOrganization() throws ParseException, InterruptedException, DeploymentException, TextParseException{ stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipRcmlOrg2))); /* * test case: * bob@org3 will dial a sip number X@org2 * X is mapped on an RCML that dials sip like <Dial><Sip>sip:[email protected]</Sip></Dial> * */ //Reload Context //containerManagercontainerManager.reloadContext(); mockDNSLookup(HOST_ORG2, TRANSPORT); //bob@org3 will dial a sip number X@org3 SipURI uri = bobSipStackOrg3.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg3.register(uri, "bob", clientPassword, "sip:[email protected]:5092", 3600, 3600)); Credential c = new Credential("org3.restcomm.com", "bob", clientPassword); bobPhoneOrg3.addUpdateCredential(c); final SipCall bobCallOrg3 = bobPhoneOrg3.createSipCall(); bobCallOrg3.initiateOutgoingCall(bobContactOrg3, dialRestcommOrg3, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg3); assertTrue(bobCallOrg3.waitForAuthorisation(3000)); assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); int responseBobOrg3 = bobCallOrg3.getLastReceivedResponse().getStatusCode(); logger.info("responseBobOrg3: "+responseBobOrg3); assertTrue(responseBobOrg3 == Response.TRYING || responseBobOrg3 == Response.RINGING); if (responseBobOrg3 == Response.TRYING) { assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg3.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg3.getLastReceivedResponse().getStatusCode()); bobCallOrg3.sendInviteOkAck(); assertTrue(!(bobCallOrg3.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); Thread.sleep(3000); bobCallOrg3.disconnect(); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test public void testOutboundPstn() throws ParseException, InterruptedException, UnknownHostException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); //prepare pstn phone to receive call SipCall pstnCall = pstnPhone.createSipCall(); pstnCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, dialRestcommOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg2.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg2.getLastReceivedResponse().getStatusCode()); assertTrue(bobCallOrg2.sendInviteOkAck()); assertTrue(pstnCall.waitForIncomingCall(5000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(pstnCall.getLastReceivedRequest().getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(pstnCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)==2); Thread.sleep(3000); bobCallOrg2.listenForDisconnect(); assertTrue(pstnCall.disconnect()); Thread.sleep(500); assertTrue(bobCallOrg2.waitForDisconnect(5000)); assertTrue(bobCallOrg2.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertEquals(1, requests.size()); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSidOrg2, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertEquals(0, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)); assertEquals(0, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)); } /** * testDialNumberExistingInMultipleOrganization: * * given we have 5 clients: * 1. alice @ org2. * 2. alice @ org3. * 3. bob @ org2. * 4. bob @ org3. * 5. alice @ defaultOrg. * * we have 2 number: * [email protected] is provider number and mapped on dial action to call alice@org2. * [email protected] is pure sip number and mapped on dial action to call alice@org3. * * test case 1: bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org3 (bcz [email protected] is pure sip) - instead call should FAIL * test case 2: bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org2 (bcz number does not exist in default.restcomm.com) - so call should FAIL * test case 3: bob@org3 created INVITE - sip:[email protected](a conference in org2) -> able to join conference (bcz [email protected] is provider number) * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialNumberExistingInMultipleOrganizationCase1() throws ParseException, InterruptedException, UnknownHostException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); /* * test case 1 - bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org3 (bcz [email protected] is pure sip) - instead call should FAIL */ SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); // [email protected] - dials a pure sip number in org3. final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, pureSipNumberOrg3, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode(); logger.info("bobCallOrg2 response: "+response); assertEquals(Response.NOT_FOUND, response); } /** * testDialNumberExistingInMultipleOrganization: * * given we have 5 clients: * 1. alice @ org2. * 2. alice @ org3. * 3. bob @ org2. * 4. bob @ org3. * 5. alice @ defaultOrg. * * we have 2 number: * [email protected] is provider number and mapped on dial action to call alice@org2. * [email protected] is pure sip number and mapped on dial action to call alice@org3. * * test case 1: bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org3 (bcz [email protected] is pure sip) - instead call should FAIL * test case 2: bob@org2 created INVITE - sip:[email protected] -> call should FAIL (bcz defaulOrg does not have that number) * test case 3: bob@org3 created INVITE - sip:[email protected](a conference in org2) -> able to join conference (bcz [email protected] is provider number) * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialNumberExistingInMultipleOrganizationCase2() throws ParseException, InterruptedException, UnknownHostException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); /* * test case 2: bob@org2 created INVITE - sip:[email protected] -> call should FAIL (bcz defaulOrg does not have that number) */ SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); //register as [email protected] uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600)); SipCall aliceCallOrg2 = alicePhoneOrg2.createSipCall(); aliceCallOrg2.listenForIncomingCall(); // [email protected] - dials a pure sip number in org3. final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, numberWithDefaultDomain, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode(); logger.info("bobCallOrg2 response: "+response); assertEquals(Response.NOT_FOUND, response); } /** * testDialNumberExistingInMultipleOrganization: * * given we have 5 clients: * 1. alice @ org2. * 2. alice @ org3. * 3. bob @ org2. * 4. bob @ org3. * 5. alice @ defaultOrg. * * we have 2 number: * [email protected] is provider number and mapped on dial action to call alice@org2. * [email protected] is pure sip number and mapped on dial action to call alice@org3. * * test case 1: bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org3 (bcz [email protected] is pure sip) - instead call should FAIL * test case 2: bob@org2 created INVITE - sip:[email protected] -> call should FAIL (bcz defaulOrg does not have that number) * test case 3: bob@org3 created INVITE - sip:[email protected](a conference in org2) -> able to join conference (bcz [email protected] is provider number) * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialNumberExistingInMultipleOrganizationJoinConferenceOfDifferentOrgCase3() throws ParseException, InterruptedException, UnknownHostException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); /* * test case 3: bob@org3 created INVITE - sip:[email protected](a conference in org2) -> able to join conference (bcz [email protected] is provider number) */ //bob@org3 joins conference via sip:[email protected] SipURI uri = bobSipStackOrg3.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg3.register(uri, "bob", clientPassword, "sip:[email protected]:5092", 3600, 3600)); Credential c = new Credential("org3.restcomm.com", "bob", clientPassword); bobPhoneOrg3.addUpdateCredential(c); final SipCall bobCallOrg3 = bobPhoneOrg3.createSipCall(); bobCallOrg3.initiateOutgoingCall(bobContactOrg3, dialRestcommOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg3); assertTrue(bobCallOrg3.waitForAuthorisation(3000)); assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); int responseBobOrg3 = bobCallOrg3.getLastReceivedResponse().getStatusCode(); logger.info("responseBobOrg3: "+responseBobOrg3); assertTrue(responseBobOrg3 == Response.TRYING || responseBobOrg3 == Response.RINGING); if (responseBobOrg3 == Response.TRYING) { assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg3.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg3.getLastReceivedResponse().getStatusCode()); bobCallOrg3.sendInviteOkAck(); assertTrue(!(bobCallOrg3.getLastReceivedResponse().getStatusCode() >= 400)); //bob@org2 joins conference via sip:[email protected] uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, dialRestcommOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); int responseBobOrg2 = bobCallOrg2.getLastReceivedResponse().getStatusCode(); assertTrue(responseBobOrg2 == Response.TRYING || responseBobOrg2 == Response.RINGING); if (responseBobOrg2 == Response.TRYING) { assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg2.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg2.getLastReceivedResponse().getStatusCode()); bobCallOrg2.sendInviteOkAck(); assertTrue(!(bobCallOrg2.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); assertTrue(getConferencesSize(adminAccountSidOrg2)>=1); int numOfParticipants = getParticipantsSize(confRoom2, adminAccountSidOrg2); logger.info("Number of participants: "+numOfParticipants); assertTrue(numOfParticipants==2); Thread.sleep(3000); bobCallOrg3.disconnect(); bobCallOrg2.disconnect(); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); assertTrue(getConferencesSize(adminAccountSidOrg2)>=1); int confRoom2Participants = getParticipantsSize(confRoom2, adminAccountSidOrg2); logger.info("&&&&& ConfRoom2Participants: "+confRoom2Participants); assertEquals(0, confRoom2Participants); } private int getConferencesSize(String accountSid) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),accountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); return conferenceArray.size(); } private int getParticipantsSize(final String name, String accountSid) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),accountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); String confSid = null; for(int i = 0; i < conferenceArray.size(); i++) { JsonObject confObj = conferenceArray.get(i).getAsJsonObject(); String confName = confObj.get("friendly_name").getAsString(); if (confName.equalsIgnoreCase(name)) { confSid = confObj.get("sid").getAsString(); break; } } JsonObject participants = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), accountSid, adminAuthToken, confSid); JsonArray participantsArray = participants.getAsJsonArray("calls"); return participantsArray.size(); } /** * testClientsCallEachOtherSameOrganization * given clients: * * maria belongs to org: org2.restcomm.com * shoaib belong to org: org2.restcomm.com * * test case: maria calls shoaib. * * result: call goes through * * @throws ParseException * @throws InterruptedException */ @Test public void testClientsCallEachOtherSameOrganization() throws ParseException, InterruptedException { SipURI uri = mariaSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(mariaPhoneOrg2.register(uri, "maria", clientPassword, "sip:[email protected]:5093", 3600, 3600)); assertTrue(shoaibPhoneOrg2.register(uri, "shoaib", clientPassword, "sip:[email protected]:5094", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "maria", clientPassword); mariaPhoneOrg2.addUpdateCredential(c); final SipCall shoaibCall = shoaibPhoneOrg2.createSipCall(); shoaibCall.listenForIncomingCall(); Thread.sleep(1000); // Maria initiates a call to Shoaib final SipCall mariaCall = mariaPhoneOrg2.createSipCall(); mariaCall.initiateOutgoingCall(mariaContactOrg2, shoaibContactOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(shoaibCall.waitForIncomingCall(5000)); assertTrue(shoaibCall.sendIncomingCallResponse(100, "Trying-Shoaib", 1800)); assertTrue(shoaibCall.sendIncomingCallResponse(180, "Ringing-Shoaib", 1800)); String receivedBody = new String(shoaibCall.getLastReceivedRequest().getRawContent()); assertTrue(shoaibCall.sendIncomingCallResponse(Response.OK, "OK-Shoaib", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 4000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.getDialog().equals(mariaDialog)); mariaCall.sendInviteOkAck(); assertTrue(mariaCall.getDialog().equals(mariaDialog)); assertTrue(!(mariaCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(shoaibCall.waitForAck(3000)); //Talk time ~ 3sec Thread.sleep(3000); shoaibCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); assertTrue(shoaibCall.waitForDisconnect(5 * 1000)); assertTrue(shoaibCall.respondToDisconnect()); Thread.sleep(5000); //Check live calls int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0,liveCallsArraySize); } /** * testClientsCallEachOtherDifferentOrganization * given clients: * * maria belongs to org: org2.restcomm.com * alice belong to org: org3.restcomm.com * * test case: maria calls alice. * * result: call do not go through * * @throws ParseException * @throws InterruptedException */ @Test public void testClientsCallEachOtherDifferentOrganization() throws ParseException, InterruptedException { SipURI uri = mariaSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(mariaPhoneOrg2.register(uri, "maria", clientPassword, "sip:[email protected]:5093", 3600, 3600)); assertTrue(alicePhoneOrg3.register(uri, "alice", "1234", "sip:[email protected]:5095", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "maria", clientPassword); mariaPhoneOrg2.addUpdateCredential(c); final SipCall aliceCallOrg3 = alicePhoneOrg3.createSipCall(); aliceCallOrg3.listenForIncomingCall(); Thread.sleep(1000); // Maria initiates a call to Alice long startTime = System.currentTimeMillis(); final SipCall mariaCall = mariaPhoneOrg2.createSipCall(); mariaCall.initiateOutgoingCall(mariaContactOrg2, aliceContactOrg3, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); //alice should not get the call assertTrue(!aliceCallOrg3.waitForIncomingCall(5000)); } /** * testDialActionAliceAnswers: * given: * clients: * bob@org2, alice@org2. * * given numbers: * 12223334455@org2 * 12223334455@org3 * * test case: bob@org2 INVITE 12223334455@org2 * result: call goes to alice@org2. * * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialActionDialClient() throws ParseException, InterruptedException, UnknownHostException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); //register as alice@org2 uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600)); // Prepare alice's phone to receive call SipCall aliceCall = alicePhoneOrg2.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with bob@org final SipCall bobCall = bobPhoneOrg2.createSipCall(); bobCall.initiateOutgoingCall(bobContactOrg2, dialClientWithActionUrlOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(3000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } Thread.sleep(3000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=3")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSidOrg2, adminAuthToken, dialCallSid); assertNotNull(cdr); } /** * testDialActionHangupWithLCM: * given: * clients: * bob@org2, alice@org2. * * given numbers: * 12223334455@org2 * 12223334455@org3 * * test case1: bob@org2 INVITE 12223334455@org2 * result: call goes to alice@org2. * * test case2: hangup using LCM * result: call completes * * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialActionHangupWithLCM() throws Exception { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); // Phone2 register as alice uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600)); // Prepare second phone to receive call SipCall aliceCallOrg2 = alicePhoneOrg2.createSipCall(); aliceCallOrg2.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, dialClientWithActionUrlOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg2.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg2.getLastReceivedResponse().getStatusCode()); String callSid = bobCallOrg2.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCallOrg2.sendInviteOkAck(); assertTrue(!(bobCallOrg2.getLastReceivedResponse().getStatusCode() >= 400)); bobCallOrg2.listenForDisconnect(); assertTrue(aliceCallOrg2.waitForIncomingCall(30 * 1000)); aliceCallOrg2.listenForCancel(); logger.info("About to execute LCM to hangup the call"); RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(),adminAccountSidOrg2,adminAuthToken,callSid,"completed", null); assertTrue(bobCallOrg2.waitForDisconnect(50 * 1000)); assertTrue(bobCallOrg2.respondToDisconnect()); Thread.sleep(10 * 1000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); logger.info("DialAction requestBody: "+requestBody); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); assertTrue(requestBody.contains("CallStatus=completed")); Iterator iter = Arrays.asList(params).iterator(); } @After public void after() throws Exception { if (bobPhoneOrg2 != null) { bobPhoneOrg2.dispose(); } if (bobSipStackOrg2 != null) { bobSipStackOrg2.dispose(); } if (bobPhoneOrg3 != null) { bobPhoneOrg3.dispose(); } if (bobSipStackOrg3 != null) { bobSipStackOrg3.dispose(); } if (bobPhoneDefaultOrg != null) { bobPhoneDefaultOrg.dispose(); } if (bobSipStackDefaultOrg != null) { bobSipStackDefaultOrg.dispose(); } if (mariaPhoneOrg2 != null) { mariaPhoneOrg2.dispose(); } if (mariaSipStackOrg2 != null) { mariaSipStackOrg2.dispose(); } if (aliceSipStackOrg2 != null) { aliceSipStackOrg2.dispose(); } if (alicePhoneOrg2 != null) { alicePhoneOrg2.dispose(); } if (aliceSipStackOrg3 != null) { aliceSipStackOrg3.dispose(); } if (alicePhoneOrg3 != null) { alicePhoneOrg3.dispose(); } if (shoaibSipStackOrg2 != null) { shoaibSipStackOrg2.dispose(); } if (shoaibPhoneOrg2 != null) { shoaibPhoneOrg2.dispose(); } if (pstnSipStack != null) { pstnSipStack.dispose(); } if (pstnPhone != null) { pstnPhone.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialActionTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-client-entry_wActionUrl.xml"); logger.info("Packaged Test App"); return archive; } }
53,235
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialForkAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialForkAnswerDelayTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.*; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.Arrays; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.*; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNotNull; import org.junit.experimental.categories.Category; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Tests for the Dial forking * Created by gvagenas on 12/19/15. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class DialForkAnswerDelayTest { private final static Logger logger = Logger.getLogger(CallLifecycleTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; // Fotini is a simple SIP Client. Will not register with Restcomm private SipStack fotiniSipStack; private SipPhone fotiniPhone; private static String fotiniPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String fotiniContact = "sip:[email protected]:" + fotiniPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private String dialAliceRcmlWithPlay; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialForkAnswerDelay1"); tool2 = new SipStackTool("DialForkAnswerDelay2"); tool3 = new SipStackTool("DialForkAnswerDelay3"); tool4 = new SipStackTool("DialForkAnswerDelay4"); tool5 = new SipStackTool("DialForkAnswerDelay5"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { dialAliceRcmlWithPlay = "<Response><Play>" + deploymentUrl.toString() + "/audio/demo-prompt.wav</Play><Dial><Client>alice</Client></Dial></Response>"; bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); fotiniSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", fotiniPort, restcommContact); fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, fotiniContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (fotiniPhone != null) { fotiniPhone.dispose(); } if (fotiniSipStack != null) { fotiniSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private String dialFork = "<Response><Dial><Client>alice</Client><Sip>sip:[email protected]:" + henriquePort + "</Sip><Number>+131313</Number></Dial></Response>"; @Test public synchronized void testDialForkNoAnswerButHenrique() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(henriqueCall.waitForAck(50 * 1000)); georgeCall.listenForCancel(); aliceCall.listenForCancel(); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); //Wait to cancel the other branches Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test public synchronized void testDialForkNoAnswerButFromAliceClient() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(henriqueCall.listenForCancel()); assertTrue(georgeCall.listenForCancel()); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(30 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); aliceCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(bobCall.waitForAnswer(5000)); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject jsonObj = cdr.getAsJsonObject(); String status = jsonObj.get("status").getAsString(); System.out.println("%%%%Status : "+status); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } @Test public synchronized void testDialForkWithBusy() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(486, "Busy Here-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(486, "Busy Here-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(henriqueCall.waitForAck(50 * 1000)); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("%%%% CallSID: "+callSid+" Status : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } @Test public synchronized void testDialForkWithDecline() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //int DECLINE = 603; assertTrue(georgeCall.sendIncomingCallResponse(Response.DECLINE, "Busy Here-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.DECLINE, "Busy Here-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(henriqueCall.waitForAck(50 * 1000)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("%%%% CallSID: "+callSid+" Status : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialForkWithTimeout = "<Response><Dial timeout=\"2\"><Client>alice</Client><Sip>sip:[email protected]:" + henriquePort + "</Sip><Number>+131313</Number></Dial></Response>"; @Test public synchronized void testDialForkNoAnswer() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeout))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TIMEOUT, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and Bob will receive disconnect assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); assertTrue(bobCall.listenForDisconnect()); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } @Test @Category(WithInMinsTests.class) public synchronized void testDialForkNoAnswerAndNoResponseFromAlice() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeout))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TIMEOUT, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); aliceCall.disposeNoBye(); //Alice will send no response at all // assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); // assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and Bob will receive disconnect assertTrue(georgeCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); assertTrue(bobCall.listenForDisconnect()); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); Thread.sleep(60000); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Thread.sleep(5000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialForkWithTimeout15 = "<Response><Dial timeout=\"15\"><Client>alice</Client><Sip>sip:[email protected]:" + henriquePort + "</Sip><Number>+131313</Number></Dial></Response>"; @Test public synchronized void testDialForkNoAnswerWith183() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeout15))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(183, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); //No one will answer the call and Bob will receive disconnect assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); assertTrue(bobCall.listenForDisconnect()); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TIMEOUT, bobCall.getLastReceivedResponse().getStatusCode()); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialForkWithActionUrl = "<Response><Dial timeLimit=\"1000\" timeout=\"2\" action=\"http://127.0.0.1:" + mockPort +"/test\">" + "<Number>+131313</Number><Uri>sip:[email protected]:" + henriquePort + "</Uri><Client>alice</Client></Dial></Response>"; private String rcmlToReturn = "<Response><Dial timeout=\"50\"><Uri>sip:[email protected]:" + fotiniPort + "</Uri></Dial></Response>"; //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test //TODO Fails when the whole test class runs but Passes when run individually @Category(UnstableTests.class) public synchronized void testDialForkNoAnswerExecuteRCML_ReturnedFromActionURL() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithActionUrl))); stubFor(post(urlEqualTo("/test")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlToReturn))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and RCML will move to the next verb to call Fotini assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); Thread.sleep(1000); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); // int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // //There will be the initial call from Bob and the new call to Fotini // logger.info("&&&& LiveCalls: "+liveCalls); // logger.info("&&&& LiveCallsArraySize: "+liveCallsArraySize); // assertTrue(liveCalls == 2); // assertTrue(liveCallsArraySize == 2); assertTrue(alicePhone.unregister(aliceContact, 3600)); //Now Fotini should receive a call assertTrue(fotiniCall.waitForIncomingCall(30 * 1000)); assertTrue(fotiniCall.sendIncomingCallResponse(100, "Trying-Fotini", 600)); assertTrue(fotiniCall.sendIncomingCallResponse(180, "Ringing-Fotini", 600)); String receivedBody = new String(fotiniCall.getLastReceivedRequest().getRawContent()); assertTrue(fotiniCall.sendIncomingCallResponse(Response.OK, "OK-Fotini", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(fotiniCall.waitForAck(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); fotiniCall.listenForDisconnect(); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); Thread.sleep(2000); // hangup. assertTrue(bobCall.disconnect()); assertTrue(fotiniCall.waitForDisconnect(50 * 1000)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test //TODO Fails when the whole test class runs but Passes when run individually @Category(UnstableTests.class) public void testDialClientAlice() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } @Test public void testDialClientAliceWithPlay() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcmlWithPlay))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialSequential = "<Response><Dial timeout=\"5\"><Sip>sip:[email protected]:5566</Sip></Dial><Dial timeout=\"5\"><Sip>sip:[email protected]:6655</Sip></Dial><Dial><Sip>sip:[email protected]:" + henriquePort + "</Sip></Dial></Response>"; @Test public synchronized void testDialSequentialFirstCallTimeouts() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSequential))); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } Thread.sleep(9000); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //Wait to cancel the other branches Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String dialForkTwoSipUrisRcml = "<Response><Dial><Sip>sip:[email protected]:" + fotiniPort + "</Sip><Sip>sip:[email protected]:" + henriquePort + "</Sip></Dial></Response>"; @Test public synchronized void testDialForkWithServerErrorReponse() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkTwoSipUrisRcml))); //Prepare Fotini to receive call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(fotiniCall.waitForIncomingCall(30 * 1000)); assertTrue(fotiniCall.sendIncomingCallResponse(Response.TRYING, "Trying-Fotini", 600)); assertTrue(fotiniCall.sendIncomingCallResponse(Response.SERVER_INTERNAL_ERROR, "Fotini-Internal-Server-Error", 600)); assertTrue(fotiniCall.waitForAck(5000)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(henriqueCall.respondToDisconnect()); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("%%%% CallSID: "+callSid+" Status : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } @Deployment(name = "DialForkAnswerDelayTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); replacements.put("5093", String.valueOf(fotiniPort)); List<String> resources = new ArrayList(Arrays.asList("hello-play.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm-delay.xml", "restcomm.script_dialForkTest",resources, replacements); } }
76,240
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallLifecycleTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/CallLifecycleTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.header.Header; import javax.sip.message.Response; import gov.nist.javax.sip.header.HeaderExt; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; /** * Test for Dial Action attribute. Reference: https://www.twilio.com/docs/api/twiml/dial#attributes-action The 'action' * attribute takes a URL as an argument. When the dialed call ends, Restcomm will make a GET or POST request to this URL * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class CallLifecycleTest { private final static Logger logger = Logger.getLogger(CallLifecycleTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; private static SipStackTool tool6; private static SipStackTool tool7; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; // subaccountclient is a simple SIP Client. Will register with Restcomm private SipStack subAccountClientSipStack; private SipPhone subAccountClientPhone; private static String subAccountPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String subAccountClientContact = "sip:[email protected]:" + subAccountPort; private SipStack closedSipStack; private SipPhone closedPhone; private static String closedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String closedContact = "sip:[email protected]:" + closedPort; private SipStack suspendedSipStack; private SipPhone suspendedPhone; private static String suspendedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String suspendedContact = "sip:[email protected]:" + suspendedPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String subAccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; private String subAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); tool5 = new SipStackTool("DialActionTest5"); tool6 = new SipStackTool("DialActionTest6"); tool7 = new SipStackTool("DialActionTest7"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); subAccountClientSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", subAccountPort, restcommContact); subAccountClientPhone = subAccountClientSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, subAccountClientContact); closedSipStack = tool6.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", closedPort, restcommContact); closedPhone = closedSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, closedContact); suspendedSipStack = tool7.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", suspendedPort, restcommContact); suspendedPhone = suspendedSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, suspendedContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (subAccountClientPhone != null) { subAccountClientPhone.dispose(); } if (subAccountClientSipStack != null) { subAccountClientSipStack.dispose(); } if (closedPhone != null) { closedPhone.dispose(); } if (closedSipStack != null) { closedSipStack.dispose(); } if (suspendedPhone != null) { suspendedPhone.dispose(); } if (suspendedSipStack != null) { suspendedSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } @Test @Category({FeatureExpTests.class, UnstableTests.class}) public void testDialCancelBeforeDialingClientAliceAfterTrying() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING); SipTransaction cancelTransaction = bobCall.sendCancel(); assertNotNull(cancelTransaction); assertTrue(bobCall.waitForCancelResponse(cancelTransaction,5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.OK); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TERMINATED, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(10000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertEquals(0, maxConcurrentCalls); assertEquals(0, maxConcurrentIncomingCalls); assertEquals(0, maxConcurrentOutgoingCalls); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category({FeatureExpTests.class, UnstableTests.class}) public void testDialCancelBeforeDialingClientAliceAfterRinging() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING); SipTransaction cancelTransaction = bobCall.sendCancel(); assertNotNull(cancelTransaction); assertTrue(bobCall.waitForCancelResponse(cancelTransaction,5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.OK); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.REQUEST_TERMINATED); // Thread.sleep(15000); // // int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); // logger.info("LiveCalls: "+liveCalls); // int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); // logger.info("LiveCallsArraySize: "+liveCallsArraySize); // assertEquals(0, liveCalls); // assertEquals(0, liveCallsArraySize); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); String status = jsonObj.get("status").getAsString(); logger.info("Status: "+status); assertTrue(status.equalsIgnoreCase("canceled")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test public void testDialClientAlice() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialClosedClientRcml = "<Response><Dial><Client>closed</Client></Dial></Response>"; @Test public void testDialNumberClosedAccount() throws ParseException, InterruptedException, MalformedURLException { //Dialed client belongs to a closed account stubFor(get(urlPathEqualTo("/2222")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClosedClientRcml))); SipCall closedCall = closedPhone.createSipCall(); closedCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:2222@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.NOT_ACCEPTABLE); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertFalse(closedCall.waitForIncomingCall(5000)); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertEquals(0, liveCalls); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertEquals(0, liveCallsArraySize); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/2222"))); assertEquals(0, requests.size()); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialSuspendedClientRcml = "<Response><Dial><Client>suspended</Client></Dial></Response>"; @Test public void testDialNumberSuspendedAccount() throws ParseException, InterruptedException, MalformedURLException { //Dialed client belongs to a closed account stubFor(get(urlPathEqualTo("/3333")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSuspendedClientRcml))); SipCall suspendedCall = suspendedPhone.createSipCall(); suspendedCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:3333@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.FORBIDDEN); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertFalse(suspendedCall.waitForIncomingCall(5000)); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertEquals(0, liveCalls); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertEquals(0, liveCallsArraySize); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/2222"))); assertEquals(0, requests.size()); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialClosedClient() throws ParseException, InterruptedException, MalformedURLException { // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:closed@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.FORBIDDEN); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, georgeCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+georgeCall.getLastReceivedResponse().getStatusCode()); } Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertEquals(0, liveCalls); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertEquals(0, liveCallsArraySize); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/2222"))); assertEquals(0, requests.size()); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialSuspendedClient() throws ParseException, InterruptedException, MalformedURLException { // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:suspended@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.FORBIDDEN); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, georgeCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+georgeCall.getLastReceivedResponse().getStatusCode()); } Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertEquals(0, liveCalls); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertEquals(0, liveCallsArraySize); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/2222"))); assertEquals(0, requests.size()); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialClientAliceBehindLB() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); ArrayList<String> additionalHeaders = new ArrayList<String>(); Header lbIpAddr = aliceSipStack.getHeaderFactory().createHeader("X-Sip-Balancer-InitialRemoteAddr","127.0.0.1"); Header lbPort = aliceSipStack.getHeaderFactory().createHeader("X-Sip-Balancer-InitialRemotePort",alicePort); additionalHeaders.add(lbIpAddr.toString()); additionalHeaders.add(lbPort.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", additionalHeaders, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialClient_CheckVIParameters() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); assertTrue(requestBody.contains("CallSid")); assertTrue(requestBody.contains("InstanceId")); assertTrue(requestBody.contains("AccountSid")); assertTrue(requestBody.contains("From")); assertTrue(requestBody.contains("To")); assertTrue(requestBody.contains("CallStatus")); assertTrue(requestBody.contains("ApiVersion")); assertTrue(requestBody.contains("Direction")); assertTrue(requestBody.contains("CallerName")); assertTrue(requestBody.contains("ForwardedFrom")); assertTrue(requestBody.contains("CallTimestamp")); } private String dialAliceRcmlWithTimeLimit = "<Response><Dial timeLimit=\"10\"><Client>alice</Client></Dial></Response>"; @Test @Category({FeatureAltTests.class, UnstableTests.class}) public void testDialClientAliceWithTimeLimit() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcmlWithTimeLimit))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); bobCall.listenForDisconnect(); aliceCall.listenForDisconnect(); Thread.sleep(8000); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(6000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); String cdrStatus = jsonObj.get("status").getAsString().toLowerCase(); logger.info("CDR Status: "+ cdrStatus); assertEquals("completed", cdrStatus); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialAliceRcmlWithCustomHeaders = "<Response><Dial><Client>alice?X-Custom-Header1=1234&X-Custom-Header2=4321</Client></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialClientAliceWithCustomHeaders() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcmlWithCustomHeaders))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); SipRequest invite = aliceCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header1")).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header2")).getValue(); assertEquals("1234", customHeader1); assertEquals("4321", customHeader2); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialAliceRcmlWithCustomHeaders2 = "<Response><Dial><Client>alice?X-Custom-Header1=1234</Client></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialClientAliceWithCustomHeaders2() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcmlWithCustomHeaders2))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); SipRequest invite = aliceCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header1")).getValue(); assertEquals("1234", customHeader1); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialInvalidClientRcml = "<Response><Dial><Client>invalidClient</Client></Dial></Response>"; @Test @Category(FeatureExpTests.class) public void testDialInvalidClient() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialInvalidClientRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); bobCall.respondToDisconnect(); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialInvalidClientRcmlAndThenAlice = "<Response><Dial><Client>invalidClient</Client></Dial><Dial><Client>alice</Client></Dial></Response>"; @Test @Category(FeatureExpTests.class) public void testDialInvalidClientAndThenAlice() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialInvalidClientRcmlAndThenAlice))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertEquals(2, liveCalls); assertEquals(1, liveIncomingCalls); assertEquals(1, liveOutgoingCalls); assertEquals(2,liveCallsArraySize); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0 ,liveCalls); assertEquals(0,liveCallsArraySize); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertEquals(1, requests.size()); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialInvalidClientRcmlAndThenAliceWithDialAction = "<Response><Dial action=\"http://127.0.0.1:" + mockPort + "/DialAction\"><Client>invalidClient</Client></Dial><Dial><Client>alice</Client></Dial></Response>"; private String dialActionRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialInvalidClientAndThenAliceWithDialAction() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialInvalidClientRcmlAndThenAliceWithDialAction))); stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialActionRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertEquals(2, liveCalls); assertEquals(1, liveIncomingCalls); assertEquals(1, liveOutgoingCalls); assertEquals(2,liveCallsArraySize); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0 ,liveCalls); assertEquals(0,liveCallsArraySize); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertEquals(1, requests.size()); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialNumberRcml = "<Response><Dial><Number>+131313</Number></Dial></Response>"; @Test public void testDialNumberPstn() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialNumberRcmlWithCustomHeaders = "<Response><Dial><Number>+131313?X-Custom-Header1=1234&X-Custom-Header2=4321</Number></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialNumberPstnWithCustomHeaders() throws InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcmlWithCustomHeaders))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); //Check custom headers SipRequest invite = georgeCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header1")).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header2")).getValue(); assertEquals("1234", customHeader1); assertEquals("4321", customHeader2); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } String sdpToFailConnection = "v=0\n" + "o=user1 53655765 2353687637 IN IP4 127.0.0.1\n" + "s=PleaseFailThisConnection\n" + "c=IN IP4 127.0.0.1\n" + "t=0 0\n" + "m=audio 6000 RTP/AVP 0\n" + "a=rtpmap:0 PCMU/8000\n"; @Test @Category(FeatureExpTests.class) public void testDialNumberPstnAbortCallWith569() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, sdpToFailConnection, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(569, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(3000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("failed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialSipRcmlWithCustomHeaders = "<Response><Dial><Sip>sip:[email protected]:"+georgePort+"?X-Custom-Header1=1234&X-Custom-Header2=4321</Sip></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialSipPstnWithCustomHeaders() throws InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipRcmlWithCustomHeaders))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); //Check custom headers SipRequest invite = georgeCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header1")).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header2")).getValue(); assertEquals("1234", customHeader1); assertEquals("4321", customHeader2); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstnRegisteredClientTimesOutCallDisconnects() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "alice", "1234"); alicePhone.addUpdateCredential(c); // Create outgoing call with first phone final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(aliceCall); assertTrue(aliceCall.waitForAuthorisation(5000)); assertTrue(aliceCall.waitOutgoingCallResponse(5 * 1000)); final int response = aliceCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(aliceCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, aliceCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, aliceCall.getLastReceivedResponse().getStatusCode()); assertTrue(aliceCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); alicePhone.setAutoResponseOptionsRequests(false); aliceCall.disposeNoBye(); georgeCall.listenForDisconnect(); Thread.sleep(50000); assertTrue(georgeCall.waitForDisconnect(500000)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); alicePhone.setAutoResponseOptionsRequests(true); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstnForbidden() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.sendIncomingCallResponse(Response.FORBIDDEN, "George-Forbidden", 3600)); assertTrue(georgeCall.waitForAck(5000)); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureAltTests.class) public void testDialNumberPstnBobDisconnects() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstn_404NotHere() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect(Response.NOT_FOUND, "Not Here")); georgeCall.disposeNoBye(); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); bobPhone.dispose(); bobPhone = null; georgePhone.dispose(); georgePhone = null; assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialNumberRcmlWithTimeout = "<Response><Dial timeout=\"10\"><Number>+131313</Number></Dial></Response>"; @Test @Category(FeatureExpTests.class) public void testDialNumberPstnNoAnswer() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcmlWithTimeout))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); assertTrue(georgeCall.listenForCancel()); SipTransaction cancelTransaction = georgeCall.waitForCancel(100 * 1000); assertNotNull(cancelTransaction); assertTrue(georgeCall.respondToCancel(cancelTransaction, Response.OK, "George-OK-2-Cancel", 3600)); Thread.sleep(1000); assertTrue(bobCall.disconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); String status = jsonObj.get("status").getAsString(); logger.info("Status: "+status); assertTrue(status.equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstn_500ServerInternalError() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.SERVER_INTERNAL_ERROR, "George-Server Internal Error", 3600)); assertTrue(georgeCall.waitForAck(5000)); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstn_BusyHere() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.BUSY_HERE, "George-Busy Here", 3600)); assertTrue(georgeCall.waitForAck(5000)); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialAliceRcmlInvalidRCML = "%%<Response><Dial><Client>alice</Client></Dial></Response>"; @Test @Category(FeatureExpTests.class) public void testDialClientAlice_InvalidRCML() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcmlInvalidRCML))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVER_INTERNAL_ERROR, bobCall.getLastReceivedResponse().getStatusCode()); String reason = bobCall.getLastReceivedResponse().getMessage().getHeader("Reason").toString(); assertTrue(bobCall.getLastReceivedResponse().getMessage().getHeader("Reason").toString().contains("Problem_to_parse_downloaded_RCML")); Thread.sleep(5000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); Thread.sleep(5000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } /** * testSubAccountClientDialsParentAccountNumber * https://github.com/RestComm/Restcomm-Connect/issues/1939 * CDR sid should be sub-account-sid * Parent and Child both account should be able to access the CDR * @throws ParseException * @throws InterruptedException * @throws MalformedURLException */ @Test @Category(FeatureAltTests.class) public void testSubAccountClientDialsParentAccountNumber() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipURI uri = subAccountClientSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(subAccountClientPhone.register(uri, "subaccountclient", "1234", subAccountClientContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "subaccountclient", "1234"); subAccountClientPhone.addUpdateCredential(c); // Create outgoing call with subAccountClient phone to parent number final SipCall subAccountClientCall = subAccountClientPhone.createSipCall(); subAccountClientCall.initiateOutgoingCall(subAccountClientContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(subAccountClientCall); assertTrue(subAccountClientCall.waitForAuthorisation(5000)); assertTrue(subAccountClientCall.waitOutgoingCallResponse(5 * 1000)); final int response = subAccountClientCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(subAccountClientCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, subAccountClientCall.getLastReceivedResponse().getStatusCode()); } assertTrue(subAccountClientCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, subAccountClientCall.getLastReceivedResponse().getStatusCode()); assertTrue(subAccountClientCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(subAccountClientCall.disconnect()); Thread.sleep(500); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } //parent account should be able to access the CDR JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, subAccountSid, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); //subAccount/child should be able to access the CDR cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), subAccountSid, subAuthToken, callSid); jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureExpTests.class) public void testDialClientAlice_DownloaderError_408Timeout() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(408))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5000)); assertEquals(500, bobCall.getLastReceivedResponse().getStatusCode()); // // assertTrue(bobCall.waitForDisconnect(5000)); // assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertEquals(0, liveCalls); assertTrue(liveIncomingCalls==0); assertEquals(0, liveCallsArraySize); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); // Thread.sleep(10000); // // logger.info("About to check the Requests"); // List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); // assertTrue(requests.size() == 1); // // requests.get(0).g; // String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); // List<String> params = Arrays.asList(requestBody.split("&")); // String callSid = ""; // for (String param : params) { // if (param.contains("CallSid")) { // callSid = param.split("=")[1]; // } // } // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); // JsonObject jsonObj = cdr.getAsJsonObject(); // assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); // // JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); // assertNotNull(metrics); // liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); // logger.info("LiveCalls: "+liveCalls); // liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); // logger.info("LiveCallsArraySize: "+liveCallsArraySize); // assertEquals(0, liveCalls); // assertEquals(0, liveCallsArraySize); // int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); // int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); // int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); // assertTrue(maxConcurrentCalls==2); // assertTrue(maxConcurrentIncomingCalls==1); // assertTrue(maxConcurrentOutgoingCalls==1); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); replacements.put("5093", String.valueOf(subAccountPort)); List<String> resources = new ArrayList(Arrays.asList("dial-client-entry_wActionUrl.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm_calllifecycle.xml", "restcomm.script_callLifecycleTest",resources, replacements); } }
147,009
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialRecordingTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialRecordingTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.apache.http.HttpRequest; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RecordingEndpointTool; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.restcomm.connect.commons.annotations.ParallelClassTests; /** * Created by gvagenas on 08/01/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(ParallelClassTests.class) public class DialRecordingTest { private final static Logger logger = Logger.getLogger(DialRecordingTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private String dialRestcomm = "sip:1111@" + restcommContact; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); //do not use this as it requires Java8 wireMockRule.resetMappings(); Thread.sleep(4000); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice_BobDisconnects() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(1000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration, 1.1); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test @Category(FeatureAltTests.class) public synchronized void testDialClientAlice_BobDisconnectsAndRemoveRecording() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(1000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration, 1.0); String recordingSid = recording.get(0).getAsJsonObject().get("sid").getAsString(); RecordingEndpointTool.getInstance().deleteRecording(deploymentUrl.toString(), adminAccountSid, adminAuthToken, recordingSid); recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(0, recording.size()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test @Category({FeatureExpTests.class,UnstableTests.class}) public synchronized void testDialClientAliceGetRecordindNoFile() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0 ,duration, 0.5); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(6000) .setConnectionRequestTimeout(6000) .setSocketTimeout(6000) .setCookieSpec(CookieSpecs.STANDARD).build(); CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).build(); String recordingUri = recording.get(0).getAsJsonObject().get("file_uri").getAsString(); HttpRequest request = new HttpGet(recordingUri); CloseableHttpResponse httpResponse = null; try { httpResponse = client.execute((HttpUriRequest) request); } catch (IOException e) { e.printStackTrace(); } assertTrue(httpResponse != null); int code = httpResponse.getStatusLine().getStatusCode(); assertEquals(200, code); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test public synchronized void testDialClientAlice_AliceDisconnects() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.listenForDisconnect(); aliceCall.disconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration, 0.5);; JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); } @Test //@Ignore //Currently using the MockMediaGateway its not possible to test this use case @Category(FeatureExpTests.class) public synchronized void testDialClientAlice_AliceDisconnects_NoRecording() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCall.listenForDisconnect(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); aliceCall.disconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(0, recording.size()); } final String recordCall = "<Response><Record timeout=\"15\" maxLength=\"50\"/></Response>"; @Test public synchronized void testRecordVerb() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCall))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(1, liveCalls); assertEquals(1, liveCallsArraySize); Thread.sleep(4000); bobCall.disconnect(); Thread.sleep(1000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(5.0, duration,1.5); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test @Category(FeatureAltTests.class) public synchronized void testRecordVerbAndDeleteRecording() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCall))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(1, liveCalls); assertEquals(1, liveCallsArraySize); Thread.sleep(4000); bobCall.disconnect(); Thread.sleep(1000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(5.0, duration,1.5); String recordingSid = recording.get(0).getAsJsonObject().get("sid").getAsString(); RecordingEndpointTool.getInstance().deleteRecording(deploymentUrl.toString(), adminAccountSid, adminAuthToken, recordingSid); recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(0, recording.size()); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test //@Ignore //Currently using the MockMediaGateway its not possible to test this use case @Category(FeatureExpTests.class) public synchronized void testRecordVerb_Disconnect_NoRecordFile() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCall))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); bobCall.disconnect(); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); Thread.sleep(5000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(0, recording.size()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); } final String recordCallWithAction = "<Response><Record timeout=\"15\" maxLength=\"60\" action=\"http://127.0.0.1:"+mockPort+"/record-action\"/></Response>"; final String hangupRcml = "<Response><Hangup/></Response>"; @Test public synchronized void testRecordCallWithAction() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCallWithAction))); stubFor(post(urlPathEqualTo("/record-action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupRcml))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(1, liveCalls); assertEquals(1, liveCallsArraySize); Thread.sleep(3000); bobCall.disconnect(); Thread.sleep(1000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration,0.5); Thread.sleep(3000); logger.info("\n\n &&&&&& About to check liveCalls &&&&&& \n"); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test @Category(UnstableTests.class) public synchronized void testRecordCallWithActionWithMaxRecordingReached() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCallWithAction))); stubFor(post(urlPathEqualTo("/record-action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupRcml))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCall.listenForDisconnect(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(1, liveCalls); assertEquals(1, liveCallsArraySize); assertTrue(bobCall.waitForDisconnect(70000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(500); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(6.0, duration,0.5); logger.info("\n\n &&&&&& About to check liveCalls &&&&&& \n"); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } final String recordCallWithTimeLimit = "<Response><Record timeLimit=\"10\" action=\"http://127.0.0.1:" + mockPort +"/record-action\"/></Response>"; @Test @Category(FeatureExpTests.class) public synchronized void testRecordWithErrorOnRecordAction() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordCallWithTimeLimit))); stubFor(post(urlPathEqualTo("/record-action")) .willReturn(aResponse() .withStatus(408))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCall.sendInviteOkAck(); bobCall.disconnect(); // assertTrue(bobCall.waitOutgoingCallResponse(10000)); // assertEquals(500, bobCall.getLastReceivedResponse()); Thread.sleep(3000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); // bobCall.listenForDisconnect(); // assertTrue(bobCall.waitForDisconnect(70000)); // assertTrue(bobCall.respondToDisconnect()); Thread.sleep(500); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(0, recording.size()); logger.info("\n\n &&&&&& About to check liveCalls &&&&&& \n"); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Ignore //The code we used to support old DB schema was removed - George 26/06/2018 @Category(FeatureAltTests.class) public void testGetRecordingWithOldS3Url() { String callSid = "CA2d3f6354e75e46b3ac76f534129ff511"; JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertTrue(duration == 3.0); //Since for this test the S3Accesstoll is not enabled, the file_uri will still point to the old S3 URL. //Check test org.restcomm.connect.testsuite.telephony.DialRecordingS3UploadNoneSecurityTest.testGetRecordingWithOldS3Url() assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().startsWith("https://s3.amazonaws.com")); } @Deployment(name = "DialRecordingTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String, String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); List<String> resources = new ArrayList(); return WebArchiveUtil.createWebArchiveNoGw("restcomm_dialrecording.xml", "restcomm.script_DialRecording", resources, replacements); } }
51,968
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SequentialDialingTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/SequentialDialingTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; /** * Created by gvagenas on 22/02/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(SequentialClassTests.class) public class SequentialDialingTest { private final static Logger logger = Logger.getLogger(SequentialDialingTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; private SipStack carolSipStack; private SipPhone carolPhone; private String carolContact = "sip:[email protected]:5092"; private SipStack daveSipStack; private SipPhone davePhone; private String daveContact = "sip:[email protected]:5093"; private String dialRestcomm = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("SequentialDialingTool1"); tool2 = new SipStackTool("SequentialDialingTool12"); tool3 = new SipStackTool("SequentialDialingTool13"); tool4 = new SipStackTool("SequentialDialingTool14"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); carolSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); carolPhone = carolSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, carolContact); daveSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5093", "127.0.0.1:5080"); davePhone = daveSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, daveContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (carolSipStack != null) { carolSipStack.dispose(); } if (carolPhone != null) { carolPhone.dispose(); } if (daveSipStack != null) { daveSipStack.dispose(); } if (davePhone != null) { davePhone.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } private String sequentialDialingRcml = "<Response><Dial timeout=\"3\"><Uri>"+aliceContact+"</Uri></Dial><Dial timeout=\"3\"><Uri>" + carolContact + "</Uri></Dial><Dial timeout=\"3\"><Uri>" + daveContact + "</Uri></Dial></Response>"; @Test public void testSequentialDialing() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sequentialDialingRcml))); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); final SipCall carolCall = carolPhone.createSipCall(); carolCall.listenForIncomingCall(); final SipCall daveCall = davePhone.createSipCall(); daveCall.listenForIncomingCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); aliceCall.listenForCancel(); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(5000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(carolCall.waitForIncomingCall(5000)); assertTrue(carolCall.sendIncomingCallResponse(100, "Trying-Carol", 600)); assertTrue(carolCall.sendIncomingCallResponse(180, "Ringing-Carol", 600)); carolCall.listenForCancel(); SipTransaction carolCancelTransaction = carolCall.waitForCancel(5000); assertNotNull(carolCancelTransaction); carolCall.respondToCancel(carolCancelTransaction, 200, "OK-2-Cancel-Carol", 3600); assertTrue(daveCall.waitForIncomingCall(5000)); assertTrue(daveCall.sendIncomingCallResponse(100, "Trying-Dave", 600)); assertTrue(daveCall.sendIncomingCallResponse(180, "Ringing-Dave", 600)); daveCall.listenForCancel(); SipTransaction daveCancelTransaction = daveCall.waitForCancel(5000); assertNotNull(daveCancelTransaction); daveCall.respondToCancel(daveCancelTransaction, 200, "OK-2-Cancel-Dave", 3600); Thread.sleep(1000); bobCall.disconnect(); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); assertEquals(0 ,liveCalls); assertEquals(0,liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testSequentialDialingAliceAnswerBobDisconnects() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sequentialDialingRcml))); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); final SipCall carolCall = carolPhone.createSipCall(); carolCall.listenForIncomingCall(); final SipCall daveCall = davePhone.createSipCall(); daveCall.listenForIncomingCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); assertTrue(!carolCall.waitForIncomingCall(5000)); assertTrue(!daveCall.waitForIncomingCall(5000)); Thread.sleep(1000); bobCall.disconnect(); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); assertEquals(0 ,liveCalls); assertEquals(0,liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testSequentialDialingCarolAnswerBobDisconnects() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sequentialDialingRcml))); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); final SipCall carolCall = carolPhone.createSipCall(); carolCall.listenForIncomingCall(); final SipCall daveCall = davePhone.createSipCall(); daveCall.listenForIncomingCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); aliceCall.listenForCancel(); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(5000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(carolCall.waitForIncomingCall(5000)); assertTrue(carolCall.sendIncomingCallResponse(100, "Trying-Carol", 600)); assertTrue(carolCall.sendIncomingCallResponse(180, "Ringing-Carol", 600)); String receivedBody = new String(carolCall.getLastReceivedRequest().getRawContent()); assertTrue(carolCall.sendIncomingCallResponse(Response.OK, "Carol-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(carolCall.waitForAck(5000)); Thread.sleep(3000); carolCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(carolCall.waitForDisconnect(5000)); assertTrue(carolCall.respondToDisconnect()); assertTrue(!daveCall.waitForIncomingCall(5000)); Thread.sleep(1000); bobCall.disconnect(); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); assertEquals(0 ,liveCalls); assertEquals(0,liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testSequentialDialingAliceAnswerAliceDisconnects() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sequentialDialingRcml))); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); final SipCall carolCall = carolPhone.createSipCall(); carolCall.listenForIncomingCall(); final SipCall daveCall = davePhone.createSipCall(); daveCall.listenForIncomingCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(!carolCall.waitForIncomingCall(5000)); assertTrue(!daveCall.waitForIncomingCall(5000)); Thread.sleep(1000); bobCall.disconnect(); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); assertEquals(0 ,liveCalls); assertEquals(0,liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testSequentialDialingCarolAnswerCarolDisconnects() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sequentialDialingRcml))); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); final SipCall carolCall = carolPhone.createSipCall(); carolCall.listenForIncomingCall(); final SipCall daveCall = davePhone.createSipCall(); daveCall.listenForIncomingCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); aliceCall.listenForCancel(); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(5000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(carolCall.waitForIncomingCall(5000)); assertTrue(carolCall.sendIncomingCallResponse(100, "Trying-Carol", 600)); assertTrue(carolCall.sendIncomingCallResponse(180, "Ringing-Carol", 600)); String receivedBody = new String(carolCall.getLastReceivedRequest().getRawContent()); assertTrue(carolCall.sendIncomingCallResponse(Response.OK, "Carol-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(carolCall.waitForAck(5000)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(carolCall.disconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(!daveCall.waitForIncomingCall(5000)); Thread.sleep(1000); bobCall.disconnect(); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); assertEquals(0 ,liveCalls); assertEquals(0,liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String sequentialDialingRcml1 = "<Response><Dial action=\"http://127.0.0.1:8090/action1\" timeout=\"3\"><Uri>" + aliceContact + "</Uri></Dial></Response>"; private String action1 = "<Response><Dial action=\"http://127.0.0.1:8090/action2\" timeout=\"3\"><Uri>" + carolContact + "</Uri></Dial></Response>"; private String action2 = "<Response><Dial timeout=\"3\"><Uri>" + daveContact + "</Uri></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testSequentialDialingWithDialAction() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sequentialDialingRcml1))); stubFor(post(urlPathEqualTo("/action1")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(action1))); stubFor(post(urlPathEqualTo("/action2")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(action2))); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); final SipCall carolCall = carolPhone.createSipCall(); carolCall.listenForIncomingCall(); final SipCall daveCall = davePhone.createSipCall(); daveCall.listenForIncomingCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); aliceCall.listenForCancel(); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(5000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(carolCall.waitForIncomingCall(5000)); assertTrue(carolCall.sendIncomingCallResponse(100, "Trying-Carol", 600)); assertTrue(carolCall.sendIncomingCallResponse(180, "Ringing-Carol", 600)); carolCall.listenForCancel(); SipTransaction carolCancelTransaction = carolCall.waitForCancel(5000); assertNotNull(carolCancelTransaction); carolCall.respondToCancel(carolCancelTransaction, 200, "OK-2-Cancel-Carol", 3600); assertTrue(daveCall.waitForIncomingCall(5000)); assertTrue(daveCall.sendIncomingCallResponse(100, "Trying-Dave", 600)); assertTrue(daveCall.sendIncomingCallResponse(180, "Ringing-Dave", 600)); daveCall.listenForCancel(); SipTransaction daveCancelTransaction = daveCall.waitForCancel(5000); assertNotNull(daveCancelTransaction); daveCall.respondToCancel(daveCancelTransaction, 200, "OK-2-Cancel-Dave", 3600); Thread.sleep(1000); bobCall.disconnect(); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); assertEquals(0 ,liveCalls); assertEquals(0,liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Deployment(name = "SequentialDialingTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest_new", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
27,256
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/CallTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; import javax.sip.message.Response; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.SequentialClassTests; //import org.restcomm.connect.telephony.Version; /** * @author [email protected] (Thomas Quintana) */ @Ignore @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={SequentialClassTests.class}) public final class CallTest { private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; private static SipStackTool tool; private SipStack receiver; private SipPhone phone; private SipPhone phone2; public CallTest() { super(); } @BeforeClass public static void beforeClass() throws Exception { tool = new SipStackTool("CallTest"); } @Before public void before() throws Exception { receiver = tool.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); phone = receiver.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, "sip:[email protected]:5070"); phone2 = receiver.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, "sip:[email protected]:5070"); } @After public void after() throws Exception { if (phone != null) { phone.dispose(); } if (phone2 != null) { phone2.dispose(); } if (receiver != null) { receiver.dispose(); } deployer.undeploy("CallTest"); } @Ignore @Test public synchronized void testInboundRedirectAndSms() { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); // Wait for an sms. final SipCall receiver = phone.createSipCall(); phone.listenRequestMessage(); assertTrue(receiver.waitForMessage(10 * 1000)); receiver.sendMessageResponse(202, "Accepted", -1); final List<String> messages = receiver.getAllReceivedMessagesContent(); assertTrue(messages.size() > 0); assertTrue(messages.get(0).equals("Hello World!")); // HangUp the call. assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(call.waitForDisconnect(5 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test public synchronized void testPauseRejectBusy() { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.BUSY_HERE, call.getLastReceivedResponse().getStatusCode()); } @Ignore @Test public synchronized void testPauseRejectRejected() throws InterruptedException { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. assertTrue(call.waitForDisconnect(10 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test public synchronized void testPlaySay() throws InterruptedException { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. assertTrue(call.waitForDisconnect(10 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test public synchronized void testRecord() throws InterruptedException { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. assertTrue(call.waitForDisconnect(60 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test public synchronized void testFax() throws InterruptedException { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. assertTrue(call.waitForDisconnect(10 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test public synchronized void testGather() throws InterruptedException { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. assertTrue(call.waitForDisconnect(10 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test public synchronized void testGatherAndFollowAction() throws InterruptedException { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. assertTrue(call.waitForDisconnect(10 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test public synchronized void testDialConference() throws InterruptedException { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. assertTrue(call.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test public synchronized void testDialFork() throws InterruptedException { deployer.deploy("CallTest"); phone.setLoopback(true); final SipCall call = phone.createSipCall(); call.initiateOutgoingCall("sip:[email protected]:5070", "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(call); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, call.getLastReceivedResponse().getStatusCode()); } assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, call.getLastReceivedResponse().getStatusCode()); call.sendInviteOkAck(); assertTrue(!(call.getLastReceivedResponse().getStatusCode() >= 400)); // hangup. assertTrue(call.waitForDisconnect(120 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Deployment(name = "CallTest", managed = false, testable = false) public static WebArchive createWebArchive() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script", "data/hsql/restcomm.script"); archive.addAsWebResource("redirect-sms-entry.xml"); archive.addAsWebResource("redirect-sms-sms.xml"); archive.addAsWebResource("pause-reject-busy-entry.xml"); archive.addAsWebResource("pause-reject-rejected-entry.xml"); archive.addAsWebResource("play-say-entry.xml"); archive.addAsWebResource("record-entry.xml"); archive.addAsWebResource("fax-entry.xml"); archive.addAsWebResource("fax.pdf"); archive.addAsWebResource("gather-entry.xml"); archive.addAsWebResource("dial-conference-entry.xml"); archive.addAsWebResource("dial-fork-entry.xml"); archive.addAsWebResource("gather-action-entry.xml"); archive.addAsWebResource("gather-action-finish.xml"); return archive; } }
19,706
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RegisterClientTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/RegisterClientTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.text.ParseException; import javax.sip.*; import javax.sip.address.SipURI; import javax.sip.message.Request; import javax.sip.message.Response; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.http.CreateClientsTool; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; /** * Client registration Test. * Maria client is using two sip clients to register * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(ParallelClassTests.class) public class RegisterClientTest { private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStack; private SipPhone mariaPhone; private String mariaContact = "sip:[email protected]:5092"; private String mariaRestcommClientSid; // Dimitris is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStack2; private SipPhone mariaPhone2; private String mariaContact2 = "sip:[email protected]:5093"; private String mariaRestcommContact = "sip:[email protected]:5080"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5091"; private String georgeRestcommClientSid; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String strongPassword = "Qwert12345"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("RegisterClientTest1"); tool2 = new SipStackTool("RegisterClientTest2"); tool3 = new SipStackTool("RegisterClientTest3"); } @Before public void before() throws Exception { georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); mariaSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); mariaPhone = mariaSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContact); mariaSipStack2 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5093", "127.0.0.1:5080"); mariaPhone2 = mariaSipStack2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContact2); mariaRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "maria", strongPassword, null); georgeRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "george", strongPassword, null); } @After public void after() throws Exception { if (mariaPhone != null) { mariaPhone.dispose(); } if (mariaSipStack != null) { mariaSipStack.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (mariaSipStack2 != null) { mariaSipStack2.dispose(); } if (mariaPhone2 != null) { mariaPhone2.dispose(); } Thread.sleep(2000); } @Test @Category(value={UnstableTests.class}) public void testRegisterClients() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(georgeRestcommClientSid); SipURI uri = georgeSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(georgePhone.register(uri, "george", strongPassword, georgeContact, 3600, 3600)); assertTrue(mariaPhone.register(uri, "maria", strongPassword, mariaContact, 3600, 3600)); assertTrue(mariaPhone2.register(uri, "maria", strongPassword, mariaContact2, 3600, 3600)); Thread.sleep(1000); assertTrue(georgePhone.unregister(georgeContact, 0)); assertTrue(mariaPhone.unregister(mariaContact, 0)); assertTrue(mariaPhone2.unregister(mariaContact2, 0)); } @Test @Category(value={UnstableTests.class}) public void testRegisterClientAndRemoveItAfterNoResponseToOptions() throws ParseException, InterruptedException, SipException, InvalidArgumentException, IOException { assertNotNull(georgeRestcommClientSid); SipURI uri = georgeSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(georgePhone.register(uri, "george", strongPassword, georgeContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "george", strongPassword); georgePhone.addUpdateCredential(c); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid,adminAuthToken)==1); Thread.sleep(1000); georgePhone.listenRequestMessage(); RequestEvent reqEvent = georgePhone.waitRequest(65000); assertTrue(reqEvent != null); assertTrue(reqEvent.getRequest().getMethod().equals(Request.OPTIONS)); Thread.sleep(40000); // assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid,adminAuthToken)); } @Test @Category(value={UnstableTests.class}) public void testGeorgeCallMaria() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(georgeRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(georgePhone.register(uri, "george", strongPassword, georgeContact, 3600, 3600)); Thread.sleep(3000); assertTrue(mariaPhone.register(uri, "maria", strongPassword, mariaContact, 3600, 3600)); Thread.sleep(3000); assertTrue(mariaPhone2.register(uri, "maria", strongPassword, mariaContact2, 3600, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "george", strongPassword); georgePhone.addUpdateCredential(c); Credential c2 = new Credential("127.0.0.1", "maria", strongPassword); mariaPhone.addUpdateCredential(c2); Credential c3 = new Credential("127.0.0.1", "maria", strongPassword); mariaPhone2.addUpdateCredential(c3); Thread.sleep(1000); final SipCall mariaCall_1 = mariaPhone.createSipCall(); mariaCall_1.listenForIncomingCall(); final SipCall mariaCall_2 = mariaPhone2.createSipCall(); mariaCall_2.listenForIncomingCall(); // Alice initiates a call to Maria final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, mariaRestcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitForAuthorisation(3000)); //According to issue 106: https://telestax.atlassian.net/browse/RESTCOMM-106 //Restcomm will only use the last REGISTER address //Last REGISTRATION was from Maria-2 assertTrue(mariaCall_2.waitForIncomingCall(3000)); assertTrue(mariaCall_2.sendIncomingCallResponse(100, "Trying-Maria-2", 1800)); assertTrue(mariaCall_2.sendIncomingCallResponse(180, "Ringing-Maria-2", 1800)); String receivedBody = new String(mariaCall_2.getLastReceivedRequest().getRawContent()); assertTrue(mariaCall_2.sendIncomingCallResponse(Response.OK, "OK-Maria-2", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(!mariaCall_1.waitForIncomingCall(3000)); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int georgeResponse = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(georgeResponse == Response.TRYING || georgeResponse == Response.RINGING); Dialog georgeDialog = null; if (georgeResponse == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); georgeDialog = georgeCall.getDialog(); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); assertTrue(georgeCall.sendInviteOkAck()); assertTrue(georgeCall.getDialog().equals(georgeDialog)); assertTrue(georgeCall.getDialog().equals(georgeDialog)); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); // Thread.sleep(3000); // assertTrue(georgeCall.disconnect()); // // assertTrue(mariaCall_2.waitForDisconnect(5 * 1000)); // assertTrue(mariaCall_2.respondToDisconnect()); //Check CDR JsonObject cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); assertTrue(cdrsArray.size() == 1); } @Deployment(name = "RegisterClientTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-conference-entry.xml"); archive.addAsWebResource("dial-fork-entry.xml"); archive.addAsWebResource("dial-uri-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("dial-number-entry.xml"); return archive; } }
13,950
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommActingAsProxyAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/RestcommActingAsProxyAnswerDelayTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.message.Response; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; /** * Created by gvagenas on 26/06/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class RestcommActingAsProxyAnswerDelayTest { private final static Logger logger = Logger.getLogger(RestcommActingAsProxyAnswerDelayTest.class.getName()); @Deployment(name = "RestcommActingAsProxyTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.delete("/WEB-INF/classes/application.conf"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_acting_as_proxy_answer_delay.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_acting_as_proxy", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); logger.info("Packaged Test App"); return archive; } private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack otherRestcommSipStack; private SipPhone otherRestcommPhone; private String otherRestcommContact = "sip:[email protected]:5091"; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private String henriqueContact = "sip:[email protected]:5092"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // subaccountclient is a simple SIP Client. Will register with Restcomm // private SipStack subAccountClientSipStack; // private SipPhone subAccountClientPhone; // private String subAccountClientContact = "sip:[email protected]:5093"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; // private String subAccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; // private String subAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("RestcommActingAsProxyTest1"); tool2 = new SipStackTool("RestcommActingAsProxyTest2"); tool3 = new SipStackTool("RestcommActingAsProxyTest3"); tool4 = new SipStackTool("RestcommActingAsProxyTest4"); // tool5 = new SipStackTool("DialActionTest5"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); otherRestcommSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); otherRestcommPhone = otherRestcommSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, otherRestcommContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, henriqueContact); // georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); // // subAccountClientSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5093", "127.0.0.1:5080"); // subAccountClientPhone = subAccountClientSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, subAccountClientContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (otherRestcommSipStack != null) { otherRestcommSipStack.dispose(); } if (otherRestcommPhone != null) { otherRestcommPhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } // if (georgePhone != null) { // georgePhone.dispose(); // } // if (georgeSipStack != null) { // georgeSipStack.dispose(); // } // // if (subAccountClientPhone != null) { // subAccountClientPhone.dispose(); // } // if (subAccountClientSipStack != null) { // subAccountClientSipStack.dispose(); // } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @Test public void testDialNumberToProxyFromClient() throws ParseException, InterruptedException, MalformedURLException { SipCall otherRestcommCall = otherRestcommPhone.createSipCall(); otherRestcommCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(otherRestcommCall.waitForIncomingCall(10000)); assertTrue(otherRestcommCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(otherRestcommCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(otherRestcommCall.getLastReceivedRequest().getRawContent()); assertTrue(otherRestcommCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int response = bobCall.getLastReceivedResponse().getStatusCode(); while (response != Response.OK) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); response = bobCall.getLastReceivedResponse().getStatusCode(); } assertTrue(bobCall.sendInviteOkAck()); assertTrue(otherRestcommCall.waitForAck(50000)); assertEquals(2, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(1, MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(1, MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(2, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(1000); otherRestcommCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(otherRestcommCall.waitForDisconnect(5000)); otherRestcommCall.respondToDisconnect(); Thread.sleep(10000); // logger.info("About to check the Requests"); // List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); // assertTrue(requests.size() == 1); // // requests.get(0).g; // String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); // List<String> params = Arrays.asList(requestBody.split("&")); // String callSid = ""; // for (String param : params) { // if (param.contains("CallSid")) { // callSid = param.split("=")[1]; // } // } // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); // JsonObject jsonObj = cdr.getAsJsonObject(); // String status = jsonObj.get("status").getAsString(); // logger.info("Status: "+status); // assertTrue(status.equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Test public void testDialNumberToProxyFromNonClient() throws ParseException, InterruptedException, MalformedURLException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.initiateOutgoingCall(henriqueContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(henriqueCall); assertTrue(georgeCall.waitForIncomingCall(10000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); int response = henriqueCall.getLastReceivedResponse().getStatusCode(); while (response != Response.OK) { assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); response = henriqueCall.getLastReceivedResponse().getStatusCode(); } assertTrue(henriqueCall.sendInviteOkAck()); assertTrue(georgeCall.waitForAck(50000)); assertEquals(2, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(1, MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(1, MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(2, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(1000); georgeCall.listenForDisconnect(); assertTrue(henriqueCall.disconnect()); assertTrue(georgeCall.waitForDisconnect(5000)); georgeCall.respondToDisconnect(); Thread.sleep(10000); // logger.info("About to check the Requests"); // List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); // assertTrue(requests.size() == 1); // // requests.get(0).g; // String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); // List<String> params = Arrays.asList(requestBody.split("&")); // String callSid = ""; // for (String param : params) { // if (param.contains("CallSid")) { // callSid = param.split("=")[1]; // } // } // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); // JsonObject jsonObj = cdr.getAsJsonObject(); // String status = jsonObj.get("status").getAsString(); // logger.info("Status: "+status); // assertTrue(status.equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } }
15,706
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommActingAsProxyTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/RestcommActingAsProxyTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.message.Response; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; /** * Created by gvagenas on 26/06/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category({FeatureAltTests.class, SequentialClassTests.class}) public class RestcommActingAsProxyTest { private final static Logger logger = Logger.getLogger(RestcommActingAsProxyTest.class.getName()); @Deployment(name = "RestcommActingAsProxyTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.delete("/WEB-INF/classes/application.conf"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_acting_as_proxy.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_acting_as_proxy", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); logger.info("Packaged Test App"); return archive; } private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack otherRestcommSipStack; private SipPhone otherRestcommPhone; private String otherRestcommContact = "sip:[email protected]:5091"; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private String henriqueContact = "sip:[email protected]:5092"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // subaccountclient is a simple SIP Client. Will register with Restcomm // private SipStack subAccountClientSipStack; // private SipPhone subAccountClientPhone; // private String subAccountClientContact = "sip:[email protected]:5093"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; // private String subAccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; // private String subAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("RestcommActingAsProxyTest1"); tool2 = new SipStackTool("RestcommActingAsProxyTest2"); tool3 = new SipStackTool("RestcommActingAsProxyTest3"); tool4 = new SipStackTool("RestcommActingAsProxyTest4"); // tool5 = new SipStackTool("DialActionTest5"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); otherRestcommSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); otherRestcommPhone = otherRestcommSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, otherRestcommContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, henriqueContact); // georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); // // subAccountClientSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5093", "127.0.0.1:5080"); // subAccountClientPhone = subAccountClientSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, subAccountClientContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (otherRestcommSipStack != null) { otherRestcommSipStack.dispose(); } if (otherRestcommPhone != null) { otherRestcommPhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } // if (georgePhone != null) { // georgePhone.dispose(); // } // if (georgeSipStack != null) { // georgeSipStack.dispose(); // } // // if (subAccountClientPhone != null) { // subAccountClientPhone.dispose(); // } // if (subAccountClientSipStack != null) { // subAccountClientSipStack.dispose(); // } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @Test public void testDialNumberToProxyFromClient() throws ParseException, InterruptedException, MalformedURLException { SipCall otherRestcommCall = otherRestcommPhone.createSipCall(); otherRestcommCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int response = bobCall.getLastReceivedResponse().getStatusCode(); while (response != Response.OK) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); response = bobCall.getLastReceivedResponse().getStatusCode(); } assertTrue(bobCall.sendInviteOkAck()); assertTrue(otherRestcommCall.waitForIncomingCall(10000)); assertTrue(otherRestcommCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(otherRestcommCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(otherRestcommCall.getLastReceivedRequest().getRawContent()); assertTrue(otherRestcommCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(otherRestcommCall.waitForAck(50000)); assertEquals(2, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(1, MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(1, MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(2, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(1000); otherRestcommCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(otherRestcommCall.waitForDisconnect(5000)); otherRestcommCall.respondToDisconnect(); Thread.sleep(10000); // logger.info("About to check the Requests"); // List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); // assertTrue(requests.size() == 1); // // requests.get(0).g; // String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); // List<String> params = Arrays.asList(requestBody.split("&")); // String callSid = ""; // for (String param : params) { // if (param.contains("CallSid")) { // callSid = param.split("=")[1]; // } // } // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); // JsonObject jsonObj = cdr.getAsJsonObject(); // String status = jsonObj.get("status").getAsString(); // logger.info("Status: "+status); // assertTrue(status.equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Test public void testDialNumberToProxyFromNonClient() throws ParseException, InterruptedException, MalformedURLException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.initiateOutgoingCall(henriqueContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(henriqueCall); assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); int response = henriqueCall.getLastReceivedResponse().getStatusCode(); while (response != Response.OK) { assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); response = henriqueCall.getLastReceivedResponse().getStatusCode(); } assertTrue(henriqueCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(10000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50000)); assertEquals(2, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(1, MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(1, MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertEquals(2, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(1000); georgeCall.listenForDisconnect(); assertTrue(henriqueCall.disconnect()); assertTrue(georgeCall.waitForDisconnect(5000)); georgeCall.respondToDisconnect(); Thread.sleep(10000); // logger.info("About to check the Requests"); // List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); // assertTrue(requests.size() == 1); // // requests.get(0).g; // String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); // List<String> params = Arrays.asList(requestBody.split("&")); // String callSid = ""; // for (String param : params) { // if (param.contains("CallSid")) { // callSid = param.split("=")[1]; // } // } // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); // JsonObject jsonObj = cdr.getAsJsonObject(); // String status = jsonObj.get("status").getAsString(); // logger.info("Status: "+status); // assertTrue(status.equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } }
15,729
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientMessageTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ClientMessageTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import java.util.List; import javax.sip.address.SipURI; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.testsuite.http.CreateClientsTool; /** * Client SIP MESSAGE Test. * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={SequentialClassTests.class}) public class ClientMessageTest { private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); private String messageBody = "Hello from George"; @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStack; private SipPhone mariaPhone; private String mariaContact = "sip:[email protected]:5092"; private String mariaRestcommClientSid; private String mariaRestcommContact = "sip:[email protected]:5080"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5091"; private String georgeRestcommClientSid; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("RegisterClientTest1"); tool2 = new SipStackTool("RegisterClientTest2"); } @Before public void before() throws Exception { georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); mariaSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); mariaPhone = mariaSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContact); mariaRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "maria", "1234qwerT", null); georgeRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "george", "1234qwerT", null); Thread.sleep(500); } @After public void after() throws Exception { if (mariaPhone != null) { mariaPhone.dispose(); } if (mariaSipStack != null) { mariaSipStack.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } } @Test public void testRegisterClients() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(georgeRestcommClientSid); SipURI uri = georgeSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(georgePhone.register(uri, "george", "1234qwerT", georgeContact, 3600, 3600)); assertTrue(mariaPhone.register(uri, "maria", "1234qwerT", mariaContact, 3600, 3600)); Thread.sleep(1000); assertTrue(georgePhone.unregister(georgeContact, 0)); assertTrue(mariaPhone.unregister(mariaContact, 0)); } @Test public void testGeorgeSendMessageTolMaria() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(georgeRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(georgePhone.register(uri, "george", "1234qwerT", georgeContact, 3600, 3600)); Thread.sleep(3000); assertTrue(mariaPhone.register(uri, "maria", "1234qwerT", mariaContact, 3600, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "george", "1234qwerT"); georgePhone.addUpdateCredential(c); Credential c2 = new Credential("127.0.0.1", "maria", "1234qwerT"); mariaPhone.addUpdateCredential(c2); Thread.sleep(1000); final SipCall mariaCall_1 = mariaPhone.createSipCall(); mariaCall_1.listenForMessage(); // Alice initiates a call to Maria final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingMessage(mariaRestcommContact, null, messageBody); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitForAuthorisation(3000)); assertTrue(mariaCall_1.waitForMessage(3000)); assertTrue(mariaCall_1.sendMessageResponse(200, "OK-Maria-Mesasge-Receieved", 1800)); List<String> msgsFromGeorge = mariaCall_1.getAllReceivedMessagesContent(); assertTrue(msgsFromGeorge.size()>0); assertTrue(msgsFromGeorge.get(0).equals(messageBody)); } @Deployment(name = "RegisterClientTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-conference-entry.xml"); archive.addAsWebResource("dial-fork-entry.xml"); archive.addAsWebResource("dial-uri-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("dial-number-entry.xml"); return archive; } }
9,121
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialRecordingAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialRecordingAnswerDelayTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Created by gvagenas on 08/01/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, ParallelClassTests.class}) public class DialRecordingAnswerDelayTest { private final static Logger logger = Logger.getLogger(DialRecordingAnswerDelayTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private String dialRestcomm = "sip:1111@" + restcommContact; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice_BobDisconnects() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration, 0.5); } @Test public synchronized void testDialClientAlice_AliceDisconnects() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(3000); // hangup. bobCall.listenForDisconnect(); aliceCall.disconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration, 0.5); } @Deployment(name = "DialRecordingTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String, String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); List<String> resources = new ArrayList(); return WebArchiveUtil.createWebArchiveNoGw("restcomm-delay.xml", "restcomm.script_dialTest_new", resources, replacements); } }
14,738
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ImsClientsDialAnswerDelayCancelTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ImsClientsDialAnswerDelayCancelTest.java
package org.restcomm.connect.testsuite.telephony; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.net.URL; import java.sql.SQLException; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.sip.Dialog; import javax.sip.InvalidArgumentException; import javax.sip.RequestEvent; import javax.sip.address.Address; import javax.sip.address.SipURI; import javax.sip.address.URI; import javax.sip.header.ContactHeader; import javax.sip.header.Header; import javax.sip.header.ProxyAuthenticateHeader; import javax.sip.header.RouteHeader; import javax.sip.header.ToHeader; import javax.sip.header.UserAgentHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.telephony.security.DigestServerAuthenticationMethod; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; /** * Test for clients with or without VoiceURL (Bitbucket issue 115). Clients without VoiceURL can dial anything. * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class ImsClientsDialAnswerDelayCancelTest { private static final String version = Version.getVersion(); private static Logger logger = Logger.getLogger(ImsClientsDialAnswerDelayCancelTest.class); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private String pstnNumber = "+151261006100"; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack augustSipStack; private SipPhone augustPhone; private String augustContact = "sip:[email protected]:5092"; private boolean isAugustRegistered = false; private SipStack juliusSipStack; private SipPhone juliusPhone; private String juliusContact = "sip:[email protected]:5094"; private boolean isJuliusRegistered = false; private SipStack imsSipStack; private SipPhone imsAugustPhone; private SipPhone imsJuliusPhone; private String imsContact = "sip:127.0.0.1"; private SipPhone pstnPhone; private String pstnContact = "sip:"+pstnNumber+"@127.0.0.1:5060"; private String adminAccountSid = "AC27f2dd02ab51ba5d5a9ff7fc5537a09a"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("ImsClientsDialTest1"); tool2 = new SipStackTool("ImsClientsDialTest2"); tool3 = new SipStackTool("ImsClientsDialTest3"); Class.forName("org.hsqldb.jdbc.JDBCDriver"); } @Before public void before() throws Exception { imsSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5060", "127.0.0.1:5080"); augustSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); augustPhone = augustSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, augustContact); imsAugustPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, augustContact); imsAugustPhone.setLoopback(true); imsAugustPhone.setPassThroughRegisterRequests(true); juliusSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5094", "127.0.0.1:5080"); juliusPhone = juliusSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, juliusContact); imsJuliusPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, juliusContact); imsJuliusPhone.setLoopback(true); imsJuliusPhone.setPassThroughRegisterRequests(true); pstnPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, pstnContact); pstnPhone.setPassThroughRegisterRequests(true); if(isAugustRegistered){ unregisterAugust(); } if(isJuliusRegistered){ unregisterJulius(); } } @After public void after() throws Exception { if (augustPhone != null) { augustPhone.dispose(); } if (augustSipStack != null) { augustSipStack.dispose(); } if (imsSipStack != null) { imsSipStack.dispose(); } if (imsAugustPhone != null) { imsAugustPhone.dispose(); } if (imsJuliusPhone != null) { imsJuliusPhone.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(3000); } @Test @Category(UnstableTests.class) public void testWebRTCClientOutgoingCancel() throws ParseException, InterruptedException, SQLException { logger.info("testWebRTCClientOutgoingCancel"); registerAugust(); SipCall pstnCall = pstnPhone.createSipCall(); final SipCall augustCall = augustPhone.createSipCall(); initiateAugust(pstnCall,pstnContact,augustCall); assertTrue(pstnCall.waitForIncomingCall(5 * 1000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "RINGING-Pstn", 3600)); SipTransaction pstnInviteTx = pstnCall.getLastTransaction(); Request pstnInvite = pstnInviteTx.getServerTransaction().getRequest(); Thread.sleep(500); pstnCall.listenForCancel(); SipTransaction augustCancelTransaction = augustCall.sendCancel(); assertTrue(augustCancelTransaction != null); SipTransaction pstnCancelTransaction = pstnCall.waitForCancel(5 * 1000); assertTrue(pstnCancelTransaction != null); pstnCall.respondToCancel(pstnCancelTransaction, 200, "OK-pstn", 3600); Response pstnResponseTerminated = imsSipStack.getMessageFactory().createResponse(Response.REQUEST_TERMINATED, pstnInvite); try{ pstnInviteTx.getServerTransaction().sendResponse(pstnResponseTerminated); } catch(Exception e){ e.printStackTrace(); } assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TERMINATED, augustCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(1000); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } @Test @Category(UnstableTests.class) public void testWebRTCClientIncomingCancel() throws InterruptedException, ParseException { logger.info("testWebRTCClientIncomingCancel"); registerAugust(); SipCall augustCall = augustPhone.createSipCall(); SipCall pstnCall = pstnPhone.createSipCall(); initiatePstn(pstnCall, augustCall); assertTrue(augustCall.waitForIncomingCall(30 * 1000)); assertTrue(augustCall.sendIncomingCallResponse(Response.RINGING, "Ringing-August", 3600)); SipTransaction augustInviteTx = augustCall.getLastTransaction(); Request augustInvite = augustInviteTx.getServerTransaction().getRequest(); augustCall.listenForCancel(); SipTransaction pstnCancelTransaction = pstnCall.sendCancel(); assertTrue(pstnCancelTransaction != null); SipTransaction augustCancelTransaction = augustCall.waitForCancel(5 * 1000); assertTrue(augustCancelTransaction != null); augustCall.respondToCancel(augustCancelTransaction, 200, "OK-pstn", 3600); Response augustResponseTerminated = imsSipStack.getMessageFactory().createResponse(Response.REQUEST_TERMINATED, augustInvite); try{ augustInviteTx.getServerTransaction().sendResponse(augustResponseTerminated); } catch(Exception e){ e.printStackTrace(); } assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TERMINATED, pstnCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(1000); Map<String, String> filters = new HashMap<String, String>(); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(0, filteredCallsByStatusObject.get("calls").getAsJsonArray().size()); unregisterAugust(); } private void unregisterAugust() throws InterruptedException{ ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.unregister(augustContact, 3600)); isAugustRegistered = false; Thread.sleep(1000); } private void unregisterJulius() throws InterruptedException{ ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsJuliusPhone.listenRequestMessage(); RequestEvent requestEvent = imsJuliusPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = juliusSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(0); contactHeader.setAddress(juliusSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsJuliusPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(juliusPhone.unregister(juliusContact, 3600)); isJuliusRegistered = false; Thread.sleep(1000); } private void registerAugust() throws ParseException, InterruptedException{ SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.execute(new Runnable() { @Override public void run() { imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(10000); assertNotNull(requestEvent); try { Response response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(14400); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); } catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } }); assertTrue(augustPhone.register(uri, "august", "1234", augustContact, 14400, 3600)); isAugustRegistered = true; Thread.sleep(1000); Credential c = new Credential("127.0.0.1", "august", "1234"); augustPhone.addUpdateCredential(c); } private void initiateAugust(SipCall toCall, String toUri, SipCall augustCall) throws ParseException, InterruptedException { toCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = augustSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // August initiates a call to pstn URI uri1 = augustSipStack.getAddressFactory().createURI("sip:127.0.0.1:5080"); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = augustSipStack.getAddressFactory().createAddress(uri1); RouteHeader routeHeader = augustSipStack.getHeaderFactory().createRouteHeader(address); replaceHeaders.add(routeHeader.toString()); Header user = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-User", "myUser"); Header pass = augustSipStack.getHeaderFactory().createHeader("X-RestComm-Ims-Password", "myPass"); replaceHeaders.add(user.toString()); replaceHeaders.add(pass.toString()); augustCall.initiateOutgoingCall(augustContact, toUri, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(augustCall); assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); int responseAugust = augustCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseAugust == Response.TRYING || responseAugust == Response.RINGING); Dialog augustDialog = null; if (responseAugust == Response.TRYING) { assertTrue(augustCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, augustCall.getLastReceivedResponse().getStatusCode()); augustDialog = augustCall.getDialog(); assertNotNull(augustDialog); } assertTrue(toCall.waitForIncomingCall(5 * 1000)); DigestServerAuthenticationMethod dsam = new DigestServerAuthenticationMethod(); dsam.initialize(); // it should read values from file, now all static ProxyAuthenticateHeader proxyAuthenticate = augustSipStack.getHeaderFactory().createProxyAuthenticateHeader( dsam.getScheme()); proxyAuthenticate.setParameter("realm", dsam.getRealm(null)); proxyAuthenticate.setParameter("nonce", dsam.generateNonce()); // proxyAuthenticateImpl.setParameter("domain",authenticationMethod.getDomain()); proxyAuthenticate.setParameter("opaque", ""); proxyAuthenticate.setParameter("algorithm", dsam.getAlgorithm()); ArrayList<Header> headers = new ArrayList<Header>(); headers.add(proxyAuthenticate); assertTrue(toCall.sendIncomingCallResponse(Response.PROXY_AUTHENTICATION_REQUIRED, "Non authorized", 3600, headers, null, null)); } private void initiatePstn(SipCall pstnCall, SipCall augustCall) throws ParseException, InterruptedException { // Prepare august phone to receive call augustCall.listenForIncomingCall(); // Create outgoing call with pstn phone ArrayList<String> replaceHeaders = new ArrayList<String>(); URI uri1 = augustSipStack.getAddressFactory().createURI("sip:[email protected]:5080"); SipURI sipURI = (SipURI) uri1; sipURI.setLrParam(); Address address = augustSipStack.getAddressFactory().createAddress(uri1); ToHeader toHeader = augustSipStack.getHeaderFactory().createToHeader(address, null); replaceHeaders.add(toHeader.toString()); pstnCall.initiateOutgoingCall(pstnContact, "sip:127.0.0.1:5080", null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(pstnCall); assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); int responsePstn = pstnCall.getLastReceivedResponse().getStatusCode(); assertTrue(responsePstn == Response.TRYING || responsePstn == Response.RINGING); if (responsePstn == Response.TRYING) { assertTrue(pstnCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, pstnCall.getLastReceivedResponse().getStatusCode()); } } @Deployment(name = "ImsClientsDialTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip-ims.xml", "/sip.xml"); archive.addAsWebInfResource("restcomm-ims-delay.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_imsDialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-conference-entry.xml"); archive.addAsWebResource("dial-fork-entry.xml"); archive.addAsWebResource("dial-uri-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("dial-number-entry.xml"); return archive; } }
21,369
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallRegexSingleTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/CallRegexSingleTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; /** * Test for Regex for IncomingPhoneNumbers * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class CallRegexSingleTest { private final static Logger logger = Logger.getLogger(CallRegexSingleTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStackOrg1; private SipPhone bobPhoneOrg1; private static String bobPort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContactOrg1 = "sip:[email protected]"; // George is a simple SIP Client. Will not register with Restcomm private SipStack aliceSipStackOrg1; private SipPhone alicePhoneOrg1; private static String alicePort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContactOrg1 = "sip:[email protected]"; // subaccountclient is a simple SIP Client. Will register with Restcomm private SipStack subAccountClientSipStack; private SipPhone subAccountClientPhone; private static String subaccountPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String subAccountClientContact = "sip:[email protected]:" + subaccountPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String subAccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; private String subAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); tool5 = new SipStackTool("DialActionTest5"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); bobSipStackOrg1 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort2, restcommContact); bobPhoneOrg1 = bobSipStackOrg1.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContactOrg1); aliceSipStackOrg1 = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort2, restcommContact); alicePhoneOrg1 = aliceSipStackOrg1.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContactOrg1); subAccountClientSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", subaccountPort, restcommContact); subAccountClientPhone = subAccountClientSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, subAccountClientContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (bobSipStackOrg1 != null) { bobSipStackOrg1.dispose(); } if (bobPhoneOrg1 != null) { bobPhoneOrg1.dispose(); } if (alicePhoneOrg1 != null) { alicePhoneOrg1.dispose(); } if (aliceSipStackOrg1 != null) { aliceSipStackOrg1.dispose(); } if (subAccountClientPhone != null) { subAccountClientPhone.dispose(); } if (subAccountClientSipStack != null) { subAccountClientSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; /** * @throws ParseException * @throws InterruptedException * @throws MalformedURLException */ @Test @Category(UnstableTests.class) public void testDial7777RegexOfDifferentOrganization() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "7777|8888" but belongs to domain 127.0.0.1 // hence anyone from org1.restcomm.com should not be allowed to reach this regex // https://github.com/RestComm/Restcomm-Connect/issues/2293 stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); // Create outgoing call with first phone final SipCall bobCallOrg1 = bobPhoneOrg1.createSipCall(); bobCallOrg1.initiateOutgoingCall(bobContactOrg1, "sip:7777@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg1); assertTrue(bobCallOrg1.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg1.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCallOrg1.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.NOT_FOUND, bobCallOrg1.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCallOrg1.getLastReceivedResponse().getStatusCode()); } } @Test public void testDialClientAlice7777() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "7777|8888" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:7777@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice8888() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "7777|8888" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:8888@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(alicePort2)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(bobPort2)); replacements.put("5093", String.valueOf(subaccountPort)); List<String> resources = new ArrayList(Arrays.asList("dial-client-entry_wActionUrl.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm_callRegex.xml", "restcomm.script_callRegexTest2",resources, replacements); } }
23,839
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialPureSipNumbersFromPstnTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialPureSipNumbersFromPstnTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommConferenceTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class DialPureSipNumbersFromPstnTest { private final static Logger logger = Logger.getLogger(DialPureSipNumbersFromPstnTest.class.getName()); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; // Bob acts a call from PSTN private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialRestcomm = "sip:[email protected]"; private final String confRoom2 = "confRoom2"; private String dialConfernceRcml = "<Response><Dial><Conference>"+confRoom2+"</Conference></Dial></Response>"; private String superAdminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialToPureSipNumbers1"); tool2 = new SipStackTool("DialTest2Tool2"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialRestcomm = "sip:[email protected]"; } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); /* these will only work in Java8, but seems unccesary wireMockRule.resetMappings(); wireMockRule.resetScenarios();*/ Thread.sleep(2000); } @Deployment(name = "DialPureSipNumbersFromPstn", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5090", String.valueOf(bobPort)); List<String> resources = new ArrayList(Arrays.asList("hello-play.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm_dial_puresip_from_pstn.xml", "restcomm.script_dial_pure_sip_from_pstn",resources, replacements); } @Test public synchronized void testDialNumberRegisteredAsPureSip() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(1, liveCalls); assertEquals(1, liveCallsArraySize); assertEquals(1, RestcommConferenceTool.getInstance().getConferencesSize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken)); int numOfParticipants = RestcommConferenceTool.getInstance().getParticipantsSize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken, confRoom2); logger.info("Number of participants: "+numOfParticipants); assertEquals(1, numOfParticipants); } }
8,236
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TestDialVerbPartThree.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestDialVerbPartThree.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import gov.nist.javax.sip.message.MessageExt; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.testsuite.telephony.security.DigestServerAuthenticationMethod; import javax.sip.address.SipURI; import javax.sip.header.Header; import javax.sip.header.ProxyAuthenticateHeader; import javax.sip.header.ProxyAuthorizationHeader; import javax.sip.message.Request; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import java.util.HashMap; import java.util.Map; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Test for Dial verb. Will test Dial Conference, Dial URI, Dial Client, Dial Number and Dial Fork * * @author <a href="mailto:[email protected]">gvagenas</a> * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(ParallelClassTests.class) public class TestDialVerbPartThree { private final static Logger logger = Logger.getLogger(TestDialVerbPartThree.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); // No-args constructor defaults to port 8080 private final String recordWithActionRcml = "<Response><Record action=\"http://127.0.0.1:" + mockPort + "/recordAction\" method=\"GET\" finishOnKey=\"#\" maxLength=\"10\" playBeep=\"true\"/></Response>"; private final String recordWithActionRcmNullFinishOnKey = "<Response><Record action=\"http://127.0.0.1:" + mockPort + "/recordAction\" method=\"GET\" finishOnKey=\"-1\" maxLength=\"10\" playBeep=\"true\"/></Response>"; private final String dialSipTagScreeningRcml = "<Response>\n" + "\t<Dial timeLimit=\"10\" timeout=\"10\" action=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/sip-dial-url-screening-test.jsp\" method=\"GET\">\n" + "\t <Sip url=\"http://127.0.0.1:" + mockPort + "/screening\" method=\"GET\">sip:[email protected]:" + alicePort + "?mycustomheader=foo&myotherheader=bar</Sip>\n" + "\t</Dial>\n" + "</Response>"; private final String dialSipDialScreeningRcml = "<Response>\n" + "\t<Dial timeLimit=\"10\" timeout=\"10\" action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\">\n" + "\t <Sip url=\"http://127.0.0.1:" + mockPort + "/screening\" method=\"GET\">sip:[email protected]:" + alicePort + "?mycustomheader=foo&myotherheader=bar</Sip>\n" + "\t</Dial>\n" + "</Response>"; private static SipStackTool tool1; private static SipStackTool tool2; // private static SipStackTool tool3; // private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; private final String actionUrlRcml = "<Dial timeout=\"50\"><Uri>sip:[email protected]:" + alicePort + "</Uri></Dial>"; private final String dialSipRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Sip>sip:[email protected]:" + alicePort + "?mycustomheader=foo&myotherheader=bar</Sip></Dial></Response>"; private final String dialSipAuthRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Sip username=\"alice\" password=\"1234\">sip:[email protected]:" + alicePort + "?mycustomheader=foo&myotherheader=bar</Sip></Dial></Response>"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialRestcomm = "sip:1111@" + restcommContact; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialTest3Tool1"); tool2 = new SipStackTool("DialTest3Tool2"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialRestcomm = "sip:1111@" + restcommContact; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } //Non regression test for https://github.com/Mobicents/RestComm/issues/612 @Test @Category({UnstableTests.class, FeatureAltTests.class}) public synchronized void testRecord_ExecuteRCML_ReturnedFromActionURL() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordWithActionRcml))); stubFor(get(urlPathEqualTo("/recordAction")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(actionUrlRcml))); //Prepare Fotini phone to receive a call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //At this point bob leaves a voicemail //Now Fotini should receive a call assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Fotini", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Fotini", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Fotini", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); aliceCall.listenForDisconnect(); Thread.sleep(2000); // hangup. assertTrue(bobCall.disconnect()); assertTrue(aliceCall.waitForDisconnect(50 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } //Non regression test for https://github.com/Mobicents/RestComm/issues/612 @Test @Category({UnstableTests.class, FeatureAltTests.class}) public synchronized void testRecord_ExecuteRCML_ReturnedFromActionURLWithNullFinishOnKey() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(recordWithActionRcmNullFinishOnKey))); stubFor(get(urlPathEqualTo("/recordAction")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(actionUrlRcml))); //Prepare Fotini phone to receive a call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //At this point bob leaves a voicemail //Now Fotini should receive a call assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Fotini", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Fotini", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Fotini", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); aliceCall.listenForDisconnect(); Thread.sleep(2000); // hangup. assertTrue(bobCall.disconnect()); assertTrue(aliceCall.waitForDisconnect(50 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } private String playRcml = "<Play>/restcomm/audio/demo-prompt.wav</Play>"; //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test @Category(FeatureAltTests.class) public synchronized void testDialWithCustomHeaders() throws InterruptedException, ParseException { //Received request: GET /rcml?CallSid=CA154c8c93d7eb439989a6ea42915b6c1b&AccountSid=ACae6e420f425248d6a26948c17a9e2acf&From=bob&To=%2B17778& //CallStatus=ringing&ApiVersion=2012-04-24&Direction=inbound&CallerName&ForwardedFrom&SipHeader_X-MyCustom-Header1=Value1&SipHeader_X-MyCustom-Header2=Value2 HTTP/1.1 stubFor(get(urlPathEqualTo("/1111")) .withQueryParam("SipHeader_X-MyCustom-Header1", containing("Value1")) .withQueryParam("SipHeader_X-MyCustom-Header2", containing("Value2")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(playRcml))); ArrayList<String> additionalHeaders = new ArrayList<String>(); additionalHeaders.add(bobPhone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header1", "Value1").toString()); additionalHeaders.add(bobPhone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header2", "Value2").toString()); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); Thread.sleep(1000); assertTrue(bobCall.waitForDisconnect(5 * 1000)); assertTrue(bobCall.respondToDisconnect()); } @Test @Category(UnstableTests.class) // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out public synchronized void testDialSip() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); } // @Ignore @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // in auth manner public synchronized void testDialSipAuth() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipAuthRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); DigestServerAuthenticationMethod dsam = new DigestServerAuthenticationMethod(); dsam.initialize(); // it should read values from file, now all static ProxyAuthenticateHeader proxyAuthenticate = aliceSipStack.getHeaderFactory().createProxyAuthenticateHeader( dsam.getScheme()); proxyAuthenticate.setParameter("realm", dsam.getRealm(null)); proxyAuthenticate.setParameter("nonce", dsam.generateNonce()); // proxyAuthenticateImpl.setParameter("domain",authenticationMethod.getDomain()); proxyAuthenticate.setParameter("opaque", ""); proxyAuthenticate.setParameter("algorithm", dsam.getAlgorithm()); ArrayList<Header> headers = new ArrayList<Header>(); headers.add(proxyAuthenticate); assertTrue(aliceCall.sendIncomingCallResponse(Response.PROXY_AUTHENTICATION_REQUIRED, "Non authorized", 3600, headers, null, null)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite.getHeader(ProxyAuthorizationHeader.NAME)); ProxyAuthorizationHeader proxyAuthorization = (ProxyAuthorizationHeader) invite .getHeader(ProxyAuthorizationHeader.NAME); boolean res = dsam.doAuthenticate("alice", "1234", proxyAuthorization, (Request) invite); assertTrue(res); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); aliceCall.listenForDisconnect(); Thread.sleep(3000); // hangup. bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); } private String screeningRcml = "<Response><Hangup/></Response>"; @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // with URL screening @Category(FeatureAltTests.class) public synchronized void testDialSipTagScreening() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipTagScreeningRcml))); stubFor(get(urlPathEqualTo("/screening")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(screeningRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); ArrayList<String> headers = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-mycustomheader", "customValue"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-myothereader", "customOtherValue"); headers.add(customHeader.toString()); headers.add(otherHeader.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", headers, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); } private String sipDialUrlActionRcml = "<Response><Hangup/></Response>"; @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // with Dial Action screening @Category(FeatureAltTests.class) public synchronized void testDialSipDialTagScreening() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipDialScreeningRcml))); stubFor(get(urlPathEqualTo("/screening")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(screeningRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sipDialUrlActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); ArrayList<String> headers = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-mycustomheader", "customValue"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-myothereader", "customOtherValue"); headers.add(customHeader.toString()); headers.add(otherHeader.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.NOT_FOUND, "Not-Found", 3600, receivedBody, "application", "sdp", headers, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); } @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // with Dial Action screening @Category(FeatureAltTests.class) public synchronized void testDialSipDialTagScreening180Decline() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipDialScreeningRcml))); stubFor(get(urlPathEqualTo("/screening")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(screeningRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sipDialUrlActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing", 3600, receivedBody, "application", "sdp", null, null)); ArrayList<String> headers = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-mycustomheader", "customValue"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-myothereader", "customOtherValue"); headers.add(customHeader.toString()); headers.add(otherHeader.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.DECLINE, "Declined", 3600, receivedBody, "application", "sdp", headers, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; @Test //For github issue #600, At the DB the IncomingPhoneNumber is '1111' and we dial '+1111', Restcomm should find this number even with the '+' @Category(FeatureAltTests.class) public synchronized void testDialClientAliceWithPlusSign() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:+1111@" + restcommContact + "", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } @Test //For github issue #600, At the DB the IncomingPhoneNumber is '+2222' and we dial '2222', Restcomm should find this number even without the '+' @Category({FeatureAltTests.class, UnstableTests.class}) public synchronized void testDialClientAliceWithoutPlusSign() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:2222@" + restcommContact + "", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } @Deployment(name = "TestDialVerbPartThree", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm.xml", "restcomm.script_dialTest_new", replacements); } }
41,272
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TestDialVerbPartThreeAnswerDelay.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestDialVerbPartThreeAnswerDelay.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import gov.nist.javax.sip.message.MessageExt; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.telephony.security.DigestServerAuthenticationMethod; import javax.sip.address.SipURI; import javax.sip.header.Header; import javax.sip.header.ProxyAuthenticateHeader; import javax.sip.header.ProxyAuthorizationHeader; import javax.sip.message.Request; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import java.util.HashMap; import java.util.Map; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Test for Dial verb. Will test Dial Conference, Dial URI, Dial Client, Dial Number and Dial Fork * * @author <a href="mailto:[email protected]">gvagenas</a> * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, ParallelClassTests.class}) public class TestDialVerbPartThreeAnswerDelay { private final static Logger logger = Logger.getLogger(TestDialVerbPartThreeAnswerDelay.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private String dialSipDialScreeningRcml = "<Response>\n" + "\t<Dial timeLimit=\"10\" timeout=\"10\" action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\">\n" + "\t <Sip url=\"http://127.0.0.1:" + mockPort + "/screening\" method=\"GET\">sip:[email protected]:" + alicePort + "?mycustomheader=foo&myotherheader=bar</Sip>\n" + "\t</Dial>\n" + "</Response>"; private static SipStackTool tool1; private static SipStackTool tool2; // private static SipStackTool tool3; // private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; private final String actionUrlRcml = "<Dial timeout=\"50\"><Uri>sip:[email protected]:" + alicePort + "</Uri></Dial>"; private final String dialSipRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Sip>sip:[email protected]:" + alicePort + "?mycustomheader=foo&myotherheader=bar</Sip></Dial></Response>"; private final String dialSipAuthRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Sip username=\"alice\" password=\"1234\">sip:[email protected]:" + alicePort + "?mycustomheader=foo&myotherheader=bar</Sip></Dial></Response>"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialRestcomm = "sip:1111@" + restcommContact; private String dialRestcomm_httpError = "sip:6666@" + restcommContact; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialTest3Tool1"); tool2 = new SipStackTool("DialTest3Tool2"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialRestcomm = "sip:1111@" + restcommContact; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out @Category(UnstableTests.class) public synchronized void testDialSip() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); } // @Ignore @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // in auth manner public synchronized void testDialSipAuth() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipAuthRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); DigestServerAuthenticationMethod dsam = new DigestServerAuthenticationMethod(); dsam.initialize(); // it should read values from file, now all static ProxyAuthenticateHeader proxyAuthenticate = aliceSipStack.getHeaderFactory().createProxyAuthenticateHeader( dsam.getScheme()); proxyAuthenticate.setParameter("realm", dsam.getRealm(null)); proxyAuthenticate.setParameter("nonce", dsam.generateNonce()); // proxyAuthenticateImpl.setParameter("domain",authenticationMethod.getDomain()); proxyAuthenticate.setParameter("opaque", ""); proxyAuthenticate.setParameter("algorithm", dsam.getAlgorithm()); ArrayList<Header> headers = new ArrayList<Header>(); headers.add(proxyAuthenticate); assertTrue(aliceCall.sendIncomingCallResponse(Response.PROXY_AUTHENTICATION_REQUIRED, "Non authorized", 3600, headers, null, null)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite.getHeader(ProxyAuthorizationHeader.NAME)); ProxyAuthorizationHeader proxyAuthorization = (ProxyAuthorizationHeader) invite .getHeader(ProxyAuthorizationHeader.NAME); boolean res = dsam.doAuthenticate("alice", "1234", proxyAuthorization, (Request) invite); assertTrue(res); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); aliceCall.listenForDisconnect(); Thread.sleep(3000); // hangup. bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); } private String sipDialUrlActionRcml = "<Response><Hangup/></Response>"; private String screeningRcml = "<Response><Hangup/></Response>"; @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // with Dial Action screening public synchronized void testDialSipDialTagScreening() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipDialScreeningRcml))); stubFor(get(urlPathEqualTo("/screening")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(screeningRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sipDialUrlActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); ArrayList<String> headers = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-mycustomheader", "customValue"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-myothereader", "customOtherValue"); headers.add(customHeader.toString()); headers.add(otherHeader.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.NOT_FOUND, "Not-Found", 3600, receivedBody, "application", "sdp", headers, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.NOT_FOUND, bobCall.getLastReceivedResponse().getStatusCode()); } @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // with Dial Action screening public synchronized void testDialSipDialTagScreening180Decline() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipDialScreeningRcml))); stubFor(get(urlPathEqualTo("/screening")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(screeningRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sipDialUrlActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing", 3600, receivedBody, "application", "sdp", null, null)); ArrayList<String> headers = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-mycustomheader", "customValue"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-myothereader", "customOtherValue"); headers.add(customHeader.toString()); headers.add(otherHeader.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.DECLINE, "Declined", 3600, receivedBody, "application", "sdp", headers, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.DECLINE, bobCall.getLastReceivedResponse().getStatusCode()); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; @Test //For github issue #600, At the DB the IncomingPhoneNumber is '1111' and we dial '+1111', Restcomm should find this number even with the '+' public synchronized void testDialClientAliceWithPlusSign() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:+1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } @Test //For github issue #600, At the DB the IncomingPhoneNumber is '+2222' and we dial '2222', Restcomm should find this number even without the '+' public synchronized void testDialClientAliceWithoutPlusSign() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:2222@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } private String playRcml = "<Play>/restcomm/audio/demo-prompt.wav</Play>"; //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test public synchronized void testDialWithCustomHeaders() throws InterruptedException, ParseException { //Received request: GET /rcml?CallSid=CA154c8c93d7eb439989a6ea42915b6c1b&AccountSid=ACae6e420f425248d6a26948c17a9e2acf&From=bob&To=%2B17778& //CallStatus=ringing&ApiVersion=2012-04-24&Direction=inbound&CallerName&ForwardedFrom&SipHeader_X-MyCustom-Header1=Value1&SipHeader_X-MyCustom-Header2=Value2 HTTP/1.1 stubFor(get(urlPathEqualTo("/1111")) .withQueryParam("SipHeader_X-MyCustom-Header1", containing("Value1")) .withQueryParam("SipHeader_X-MyCustom-Header2", containing("Value2")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(playRcml))); ArrayList<String> additionalHeaders = new ArrayList<String>(); additionalHeaders.add(bobPhone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header1", "Value1").toString()); additionalHeaders.add(bobPhone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header2", "Value2").toString()); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); Thread.sleep(1000); assertTrue(bobCall.waitForDisconnect(5 * 1000)); assertTrue(bobCall.respondToDisconnect()); } //issue-1759 regression test @Test public synchronized void testDialWithCustomHeadersHttpError() throws InterruptedException, ParseException { //Received request: GET /rcml?CallSid=CA154c8c93d7eb439989a6ea42915b6c1b&AccountSid=ACae6e420f425248d6a26948c17a9e2acf&From=bob&To=%2B17778& //CallStatus=ringing&ApiVersion=2012-04-24&Direction=inbound&CallerName&ForwardedFrom&SipHeader_X-MyCustom-Header1=Value1&SipHeader_X-MyCustom-Header2=Value2 HTTP/1.1 /*stubFor(get(urlPathEqualTo("/1111")) .withQueryParam("SipHeader_X-MyCustom-Header1", containing("Value1")) .withQueryParam("SipHeader_X-MyCustom-Header2", containing("Value2")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(playRcml)));*/ ArrayList<String> additionalHeaders = new ArrayList<String>(); additionalHeaders.add(bobPhone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header1", "Value1").toString()); additionalHeaders.add(bobPhone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header2", "Value2").toString()); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm_httpError, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVER_INTERNAL_ERROR, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(1000); } @Deployment(name = "TestDialVerbPartThreeAnswerDelay", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm-delay.xml", "restcomm.script_dialTest_new", replacements); } }
32,755
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallLifecycleAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/CallLifecycleAnswerDelayTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; /** * Test for Dial Action attribute. Reference: https://www.twilio.com/docs/api/twiml/dial#attributes-action The 'action' * attribute takes a URL as an argument. When the dialed call ends, Restcomm will make a GET or POST request to this URL * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class CallLifecycleAnswerDelayTest { private final static Logger logger = Logger.getLogger(CallLifecycleAnswerDelayTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("CallLifecycleDelayAnswerTest1"); tool2 = new SipStackTool("CallLifecycleDelayAnswerTest2"); tool3 = new SipStackTool("CallLifecycleDelayAnswerTest3"); tool4 = new SipStackTool("CallLifecycleDelayAnswerTest"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @Test @Category({FeatureExpTests.class, UnstableTests.class}) public void testDialCancelBeforeDialingClientAliceAfterRinging() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING); SipTransaction cancelTransaction = bobCall.sendCancel(); assertNotNull(cancelTransaction); assertTrue(bobCall.waitForCancelResponse(cancelTransaction,5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.OK); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.REQUEST_TERMINATED); // Thread.sleep(15000); // // int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); // logger.info("LiveCalls: "+liveCalls); // int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); // logger.info("LiveCallsArraySize: "+liveCallsArraySize); // assertTrue(liveCalls==0); // assertTrue(liveCallsArraySize==0); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); String status = jsonObj.get("status").getAsString(); logger.info("Status: "+status); assertTrue(status.equalsIgnoreCase("canceled")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialClientAlice() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); } private String dialNumberRcml = "<Response><Dial><Number>+131313</Number></Dial></Response>"; @Test @Category(FeatureAltTests.class) public void testDialNumberPstn() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Test @Category({FeatureExpTests.class, UnstableTests.class}) public void testDialNumberPstnRegisteredClientTimesOutCallDisconnects() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "alice", "1234"); alicePhone.addUpdateCredential(c); // Create outgoing call with first phone final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(aliceCall); assertTrue(aliceCall.waitForAuthorisation(5000)); assertTrue(aliceCall.waitOutgoingCallResponse(5 * 1000)); final int response = aliceCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(aliceCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, aliceCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, aliceCall.getLastReceivedResponse().getStatusCode()); assertTrue(aliceCall.sendInviteOkAck()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); aliceCall.disposeNoBye(); georgeCall.listenForDisconnect(); Thread.sleep(50000); assertTrue(georgeCall.waitForDisconnect(500000)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstnForbidden() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.sendIncomingCallResponse(Response.FORBIDDEN, "George-Forbidden", 3600)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstnBobDisconnects() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstn_404NotHere() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect(Response.NOT_FOUND, "Not Here")); georgeCall.disposeNoBye(); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); bobPhone.dispose(); bobPhone = null; georgePhone.dispose(); georgePhone = null; assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } private String dialNumberRcmlWithTimeout = "<Response><Dial timeout=\"10\"><Number>+131313</Number></Dial></Response>"; @Test @Category(FeatureExpTests.class) public void testDialNumberPstnNoAnswer() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcmlWithTimeout))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); assertTrue(georgeCall.listenForCancel()); SipTransaction cancelTransaction = georgeCall.waitForCancel(100 * 1000); assertNotNull(cancelTransaction); assertTrue(georgeCall.respondToCancel(cancelTransaction, Response.OK, "George-OK-2-Cancel", 3600)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TIMEOUT, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(1000); assertTrue(bobCall.disconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); String status = jsonObj.get("status").getAsString(); logger.info("Status: "+status); assertTrue(status.equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstn_500ServerInternalError() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } Thread.sleep(200); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.SERVER_INTERNAL_ERROR, "George-Server Internal Error", 3600)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVER_INTERNAL_ERROR, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Test @Category(FeatureExpTests.class) public void testDialNumberPstn_BusyHere() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } Thread.sleep(200); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==2); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.BUSY_HERE, "George-Busy Here", 3600)); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.BUSY_HERE, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } private String dialAliceRcmlInvalidRCML = "%%<Response><Dial><Client>alice</Client></Dial></Response>"; @Test @Category(FeatureExpTests.class) public void testDialClientAlice_InvalidRCML() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcmlInvalidRCML))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVER_INTERNAL_ERROR, bobCall.getLastReceivedResponse().getStatusCode()); String reason = bobCall.getLastReceivedResponse().getMessage().getHeader("Reason").toString(); assertTrue(bobCall.getLastReceivedResponse().getMessage().getHeader("Reason").toString().contains("Problem_to_parse_downloaded_RCML")); Thread.sleep(5000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); Thread.sleep(5000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); } @Deployment(name = "CallLifecycleDelayAnswerTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); List<String> resources = new ArrayList(Arrays.asList("dial-client-entry_wActionUrl.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm_calllifecycle-delay.xml", "restcomm.script_callLifecycleTest",resources, replacements); } }
56,487
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialActionOrganizationSBCTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialActionOrganizationSBCTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.net.MalformedURLException; import java.net.URL; import java.net.UnknownHostException; import java.text.ParseException; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; import javax.sip.Dialog; import javax.sip.ListeningPoint; import javax.sip.address.Hop; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mobicents.api.annotations.GetDeployableContainer; import org.jboss.arquillian.container.mss.extension.ContainerManagerTool; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.spi.client.container.DeploymentException; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.mobicents.ext.javax.sip.dns.DNSLookupPerformer; import org.mobicents.ext.javax.sip.dns.DefaultDNSLookupPerformer; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.http.RestcommConferenceParticipantsTool; import org.restcomm.connect.testsuite.http.RestcommConferenceTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import org.xbill.DNS.DClass; import org.xbill.DNS.NAPTRRecord; import org.xbill.DNS.Name; import org.xbill.DNS.Record; import org.xbill.DNS.SRVRecord; import org.xbill.DNS.TextParseException; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import gov.nist.javax.sip.stack.HopImpl; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; /** * Test for Dial Action attribute for organization * * @author maria * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={WithInMinsTests.class, SequentialClassTests.class}) public class DialActionOrganizationSBCTest { private final static Logger logger = Logger.getLogger(DialActionOrganizationSBCTest.class.getName()); private static final String TRANSPORT = "udp"; private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @GetDeployableContainer private ContainerManagerTool containerManager; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; private static SipStackTool tool6; private static SipStackTool tool7; private static SipStackTool tool8; private SipStack bobSipStackOrg2; private SipPhone bobPhoneOrg2; private String bobContactOrg2 = "sip:[email protected]"; private SipStack bobSipStackOrg3; private SipPhone bobPhoneOrg3; private String bobContactOrg3 = "sip:[email protected]"; private SipStack bobSipStackDefaultOrg; private SipPhone bobPhoneDefaultOrg; private String bobContactDefaultOrg = "sip:[email protected]:5096"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. Alice belong to organization org2.restcomm.com private SipStack aliceSipStackOrg2; private SipPhone alicePhoneOrg2; private String aliceContactOrg2 = "sip:[email protected]"; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStackOrg2; private SipPhone mariaPhoneOrg2; private String mariaContactOrg2 = "sip:[email protected]"; // Shoaibs is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack shoaibSipStackOrg2; private SipPhone shoaibPhoneOrg2; private String shoaibContactOrg2 = "sip:[email protected]"; // pstn is a simple SIP Client. Will not register with Restcomm private SipStack pstnSipStack; private SipPhone pstnPhone; private String pstnContact = "sip:[email protected]:5070"; private String clientPassword = "qwerty1234RT"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. Alice belong to organization: org3.restcomm.com private SipStack aliceSipStackOrg3; private SipPhone alicePhoneOrg3; private String aliceContactOrg3 = "sip:[email protected]"; private String providerNumberOrg2 = "sip:[email protected]"; // Application: dial-number-entry_wActionUrl.xml private String pureSipNumberOrg3 = "sip:[email protected]"; // Application: dial-client-entry_wActionUrl.xml private String numberWithDefaultDomain = "sip:[email protected]:5080"; // Application: dial-client-entry_wActionUrl.xml private String dialClientWithActionUrlOrg2 = "sip:[email protected]"; // Application: dial-client-entry_wActionUrl.xml private String dialClientWithActionUrlOrg3 = "sip:[email protected]"; // Application: dial-client-entry_wActionUrl.xml of organization: org3.restcomm.com private String dialRestcommOrg2 = "sip:[email protected]"; private String dialRestcommOrg3 = "sip:[email protected]"; private final String confRoom2 = "confRoom2"; private String dialConfernceRcml = "<Response><Dial><Conference>"+confRoom2+"</Conference></Dial></Response>"; private String dialNumberRcml = "<Response><Dial><Number>+131313</Number></Dial></Response>"; private String dialSipRcmlOrg2 = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Sip>sip:[email protected]</Sip></Dial></Response>"; private String superAdminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAccountSidOrg2 = "ACae6e420f425248d6a26948c17a9e2acg"; private String adminAccountSidOrg3 = "ACae6e420f425248d6a26948c17a9e2ach"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static final String HOST_ORG2 = "org2.restcomm.com"; private static final String HOST_ORG3 = "org3.restcomm.com"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); tool5 = new SipStackTool("DialActionTest5"); tool6 = new SipStackTool("DialActionTest6"); tool7 = new SipStackTool("DialActionTest7"); tool8 = new SipStackTool("DialActionTest8"); } @Before public void before() throws Exception { bobSipStackOrg2 = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhoneOrg2 = bobSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContactOrg2); aliceSipStackOrg2 = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhoneOrg2 = aliceSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContactOrg2); bobSipStackOrg3 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); bobPhoneOrg3 = bobSipStackOrg3.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContactOrg3); mariaSipStackOrg2 = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5093", "127.0.0.1:5080"); mariaPhoneOrg2 = mariaSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContactOrg2); shoaibSipStackOrg2 = tool6.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5094", "127.0.0.1:5080"); shoaibPhoneOrg2 = shoaibSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, shoaibContactOrg2); aliceSipStackOrg3 = tool7.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5095", "127.0.0.1:5080"); alicePhoneOrg3 = aliceSipStackOrg3.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContactOrg3); bobSipStackDefaultOrg = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5096", "127.0.0.1:5080"); bobPhoneDefaultOrg = bobSipStackDefaultOrg.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContactDefaultOrg); pstnSipStack = tool8.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); pstnPhone = pstnSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, pstnContact); } private void mockDNSLookup(String host, String transport) throws TextParseException { DNSLookupPerformer dnsLookupPerformer = mock(DefaultDNSLookupPerformer.class); //mocking the DNS Lookups to match our test cases containerManager.getSipStandardService().getSipApplicationDispatcher().getDNSServerLocator().setDnsLookupPerformer(dnsLookupPerformer); Set<String> supportedTransports = new HashSet<String>(); supportedTransports.add(TRANSPORT.toUpperCase()); supportedTransports.add(ListeningPoint.TCP.toUpperCase()); supportedTransports.add(ListeningPoint.TLS.toUpperCase()); Queue<Hop> hops = new ConcurrentLinkedQueue(); hops = new ConcurrentLinkedQueue(); //dont use "localhost" or DNS will not work (wouldnt be external) hops.add(new HopImpl("127.0.0.1", 5080, transport)); when(dnsLookupPerformer.locateHopsForNonNumericAddressWithPort("localhost", 5080, transport)).thenReturn(hops); when(dnsLookupPerformer.locateHopsForNonNumericAddressWithPort("localhost", 5082, transport)).thenReturn(null); when(dnsLookupPerformer.locateHopsForNonNumericAddressWithPort("localhost", 5081, transport)).thenReturn(null); List<NAPTRRecord> mockedNAPTRRecords = new LinkedList<NAPTRRecord>(); // mocking the name because localhost is not absolute and localhost. cannot be resolved Name name = mock(Name.class); when(name.isAbsolute()).thenReturn(true); when(name.toString()).thenReturn("localhost"); mockedNAPTRRecords.add(new NAPTRRecord(new Name(host + "."), DClass.IN, 1000, 0, 0, "s", "SIP+D2U", "", new Name("_sip._" + TRANSPORT.toLowerCase() + "." + host + "."))); when(dnsLookupPerformer.performNAPTRLookup(host, false, supportedTransports)).thenReturn(mockedNAPTRRecords); List<Record> mockedSRVRecords = new LinkedList<Record>(); mockedSRVRecords.add(new SRVRecord(new Name("_sip._" + TRANSPORT.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5080, name)); mockedSRVRecords.add(new SRVRecord(new Name("_sip._" + TRANSPORT.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 0, 0, 5081, name)); when(dnsLookupPerformer.performSRVLookup("_sip._" + TRANSPORT.toLowerCase() + "." + host)).thenReturn(mockedSRVRecords); List<Record> mockedSRVTCPRecords = new LinkedList<Record>(); mockedSRVTCPRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5080, name)); mockedSRVTCPRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 0, 0, 5081, name)); // mockedSRVTLSRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TLS.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5081, name)); when(dnsLookupPerformer.performSRVLookup("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host)).thenReturn(mockedSRVTCPRecords); List<Record> mockedSRVTLSRecords = new LinkedList<Record>(); mockedSRVTLSRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5080, name)); mockedSRVTLSRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TCP.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 0, 0, 5081, name)); // mockedSRVTLSRecords.add(new SRVRecord(new Name("_sips._" + ListeningPoint.TLS.toLowerCase() + "." + host + "."), DClass.IN, 1000L, 1, 0, 5081, name)); when(dnsLookupPerformer.performSRVLookup("_sips._" + ListeningPoint.TLS.toLowerCase() + "." + host)).thenReturn(mockedSRVTLSRecords); } @Ignore @Test public void testDialSipNumberSameAndDifferentOrganization() throws ParseException, InterruptedException, DeploymentException, TextParseException{ stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSipRcmlOrg2))); /* * test case: * bob@org3 will dial a sip number X@org2 * X is mapped on an RCML that dials sip like <Dial><Sip>sip:[email protected]</Sip></Dial> * */ //Reload Context //containerManagercontainerManager.reloadContext(); mockDNSLookup(HOST_ORG2, TRANSPORT); //bob@org3 will dial a sip number X@org3 SipURI uri = bobSipStackOrg3.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg3.register(uri, "bob", clientPassword, "sip:[email protected]:5092", 3600, 3600)); Credential c = new Credential("org3.restcomm.com", "bob", clientPassword); bobPhoneOrg3.addUpdateCredential(c); final SipCall bobCallOrg3 = bobPhoneOrg3.createSipCall(); bobCallOrg3.initiateOutgoingCall(bobContactOrg3, dialRestcommOrg3, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg3); assertTrue(bobCallOrg3.waitForAuthorisation(3000)); assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); int responseBobOrg3 = bobCallOrg3.getLastReceivedResponse().getStatusCode(); logger.info("responseBobOrg3: "+responseBobOrg3); assertTrue(responseBobOrg3 == Response.TRYING || responseBobOrg3 == Response.RINGING); if (responseBobOrg3 == Response.TRYING) { assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg3.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg3.getLastReceivedResponse().getStatusCode()); bobCallOrg3.sendInviteOkAck(); assertTrue(!(bobCallOrg3.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); Thread.sleep(3000); bobCallOrg3.disconnect(); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test public void testOutboundPstn() throws ParseException, InterruptedException, UnknownHostException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); //prepare pstn phone to receive call SipCall pstnCall = pstnPhone.createSipCall(); pstnCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, dialRestcommOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg2.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg2.getLastReceivedResponse().getStatusCode()); assertTrue(bobCallOrg2.sendInviteOkAck()); assertTrue(pstnCall.waitForIncomingCall(5000)); assertTrue(pstnCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(pstnCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); String receivedBody = new String(pstnCall.getLastReceivedRequest().getRawContent()); assertTrue(pstnCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(pstnCall.waitForAck(5000)); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)==2); assertTrue(MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)==1); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)==2); Thread.sleep(3000); bobCallOrg2.listenForDisconnect(); assertTrue(pstnCall.disconnect()); Thread.sleep(500); assertTrue(bobCallOrg2.waitForDisconnect(5000)); assertTrue(bobCallOrg2.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertEquals(1, requests.size()); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSidOrg2, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertEquals(0, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)); assertEquals(0, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSidOrg2, adminAuthToken)); } /** * testDialNumberExistingInMultipleOrganization: * * given we have 5 clients: * 1. alice @ org2. * 2. alice @ org3. * 3. bob @ org2. * 4. bob @ org3. * 5. alice @ defaultOrg. * * we have 2 number: * [email protected] is provider number and mapped on dial action to call alice@org2. * [email protected] is pure sip number and mapped on dial action to call alice@org3. * * test case 1: bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org3 (bcz [email protected] is pure sip) - instead call should FAIL * test case 2: bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org2 (bcz number does not exist in default.restcomm.com) - so call should FAIL * test case 3: bob@org3 created INVITE - sip:[email protected](a conference in org2) -> able to join conference (bcz [email protected] is provider number) * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialNumberExistingInMultipleOrganizationCase1() throws ParseException, InterruptedException, UnknownHostException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); /* * test case 1 - bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org3 (bcz [email protected] is pure sip) - instead call should FAIL */ SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); //register as [email protected] uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600)); SipCall aliceCallOrg2 = alicePhoneOrg2.createSipCall(); aliceCallOrg2.listenForIncomingCall(); // [email protected] - dials a pure sip number in org3. final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, pureSipNumberOrg3, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode(); logger.info("bobCallOrg2 response: "+response); assertEquals(Response.NOT_FOUND, response); } /** * testDialNumberExistingInMultipleOrganization: * * given we have 5 clients: * 1. alice @ org2. * 2. alice @ org3. * 3. bob @ org2. * 4. bob @ org3. * 5. alice @ defaultOrg. * * we have 2 number: * [email protected] is provider number and mapped on dial action to call alice@org2. * [email protected] is pure sip number and mapped on dial action to call alice@org3. * * test case 1: bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org3 (bcz [email protected] is pure sip) - instead call should FAIL * test case 2: bob@org2 created INVITE - sip:[email protected] -> call should FAIL (bcz defaulOrg does not have that number) * test case 3: bob@org3 created INVITE - sip:[email protected](a conference in org2) -> able to join conference (bcz [email protected] is provider number) * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialNumberExistingInMultipleOrganizationCase2() throws ParseException, InterruptedException, UnknownHostException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); /* * test case 2: bob@org2 created INVITE - sip:[email protected] -> call should FAIL (bcz defaulOrg does not have that number) */ SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); //register as [email protected] uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600)); SipCall aliceCallOrg2 = alicePhoneOrg2.createSipCall(); aliceCallOrg2.listenForIncomingCall(); // [email protected] - dials a pure sip number in org3. final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, numberWithDefaultDomain, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode(); logger.info("bobCallOrg2 response: "+response); assertEquals(Response.NOT_FOUND, response); } /** * testDialNumberExistingInMultipleOrganization: * * given we have 5 clients: * 1. alice @ org2. * 2. alice @ org3. * 3. bob @ org2. * 4. bob @ org3. * 5. alice @ defaultOrg. * * we have 2 number: * [email protected] is provider number and mapped on dial action to call alice@org2. * [email protected] is pure sip number and mapped on dial action to call alice@org3. * * test case 1: bob@org2 created INVITE - sip:[email protected] -> call should NOT go to alice@org3 (bcz [email protected] is pure sip) - instead call should FAIL * test case 2: bob@org2 created INVITE - sip:[email protected] -> call should FAIL (bcz defaulOrg does not have that number) * test case 3: bob@org3 created INVITE - sip:[email protected](a conference in org2) -> able to join conference (bcz [email protected] is provider number) * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialNumberExistingInMultipleOrganizationJoinConferenceOfDifferentOrgCase3() throws ParseException, InterruptedException, UnknownHostException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); /* * test case 3: bob@org3 created INVITE - sip:[email protected](a conference in org2) -> able to join conference (bcz [email protected] is provider number) */ //bob@org3 joins conference via sip:[email protected] SipURI uri = bobSipStackOrg3.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg3.register(uri, "bob", clientPassword, "sip:[email protected]:5092", 3600, 3600)); Credential c = new Credential("org3.restcomm.com", "bob", clientPassword); bobPhoneOrg3.addUpdateCredential(c); final SipCall bobCallOrg3 = bobPhoneOrg3.createSipCall(); bobCallOrg3.initiateOutgoingCall(bobContactOrg3, dialRestcommOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg3); assertTrue(bobCallOrg3.waitForAuthorisation(3000)); assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); int responseBobOrg3 = bobCallOrg3.getLastReceivedResponse().getStatusCode(); logger.info("responseBobOrg3: "+responseBobOrg3); assertTrue(responseBobOrg3 == Response.TRYING || responseBobOrg3 == Response.RINGING); if (responseBobOrg3 == Response.TRYING) { assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg3.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg3.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg3.getLastReceivedResponse().getStatusCode()); bobCallOrg3.sendInviteOkAck(); assertTrue(!(bobCallOrg3.getLastReceivedResponse().getStatusCode() >= 400)); //bob@org2 joins conference via sip:[email protected] uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, dialRestcommOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); int responseBobOrg2 = bobCallOrg2.getLastReceivedResponse().getStatusCode(); assertTrue(responseBobOrg2 == Response.TRYING || responseBobOrg2 == Response.RINGING); if (responseBobOrg2 == Response.TRYING) { assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg2.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg2.getLastReceivedResponse().getStatusCode()); bobCallOrg2.sendInviteOkAck(); assertTrue(!(bobCallOrg2.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); assertTrue(getConferencesSize(adminAccountSidOrg2)>=1); int numOfParticipants = getParticipantsSize(confRoom2, adminAccountSidOrg2); logger.info("Number of participants: "+numOfParticipants); assertTrue(numOfParticipants==2); Thread.sleep(3000); bobCallOrg3.disconnect(); bobCallOrg2.disconnect(); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); assertTrue(getConferencesSize(adminAccountSidOrg2)>=1); int confRoom2Participants = getParticipantsSize(confRoom2, adminAccountSidOrg2); logger.info("&&&&& ConfRoom2Participants: "+confRoom2Participants); assertEquals(0, confRoom2Participants); } private int getConferencesSize(String accountSid) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),accountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); return conferenceArray.size(); } private int getParticipantsSize(final String name, String accountSid) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),accountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); String confSid = null; for(int i = 0; i < conferenceArray.size(); i++) { JsonObject confObj = conferenceArray.get(i).getAsJsonObject(); String confName = confObj.get("friendly_name").getAsString(); if (confName.equalsIgnoreCase(name)) { confSid = confObj.get("sid").getAsString(); break; } } JsonObject participants = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), accountSid, adminAuthToken, confSid); JsonArray participantsArray = participants.getAsJsonArray("calls"); return participantsArray.size(); } /** * testClientsCallEachOtherSameOrganization * given clients: * * maria belongs to org: org2.restcomm.com * shoaib belong to org: org2.restcomm.com * * test case: maria calls shoaib. * * result: call goes through * * @throws ParseException * @throws InterruptedException */ @Test public void testClientsCallEachOtherSameOrganization() throws ParseException, InterruptedException { SipURI uri = mariaSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(mariaPhoneOrg2.register(uri, "maria", clientPassword, "sip:[email protected]:5093", 3600, 3600)); assertTrue(shoaibPhoneOrg2.register(uri, "shoaib", clientPassword, "sip:[email protected]:5094", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "maria", clientPassword); mariaPhoneOrg2.addUpdateCredential(c); final SipCall shoaibCall = shoaibPhoneOrg2.createSipCall(); shoaibCall.listenForIncomingCall(); Thread.sleep(1000); // Maria initiates a call to Shoaib final SipCall mariaCall = mariaPhoneOrg2.createSipCall(); mariaCall.initiateOutgoingCall(mariaContactOrg2, shoaibContactOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(shoaibCall.waitForIncomingCall(5000)); assertTrue(shoaibCall.sendIncomingCallResponse(100, "Trying-Shoaib", 1800)); assertTrue(shoaibCall.sendIncomingCallResponse(180, "Ringing-Shoaib", 1800)); String receivedBody = new String(shoaibCall.getLastReceivedRequest().getRawContent()); assertTrue(shoaibCall.sendIncomingCallResponse(Response.OK, "OK-Shoaib", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 4000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.getDialog().equals(mariaDialog)); mariaCall.sendInviteOkAck(); assertTrue(mariaCall.getDialog().equals(mariaDialog)); assertTrue(!(mariaCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(shoaibCall.waitForAck(3000)); //Talk time ~ 3sec Thread.sleep(3000); shoaibCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); assertTrue(shoaibCall.waitForDisconnect(5 * 1000)); assertTrue(shoaibCall.respondToDisconnect()); Thread.sleep(5000); //Check live calls int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), superAdminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0,liveCallsArraySize); } /** * testClientsCallEachOtherDifferentOrganization * given clients: * * maria belongs to org: org2.restcomm.com * alice belong to org: org3.restcomm.com * * test case: maria calls alice. * * result: call do not go through * * @throws ParseException * @throws InterruptedException */ @Test @Category({FeatureExpTests.class}) public void testClientsCallEachOtherDifferentOrganization() throws ParseException, InterruptedException { SipURI uri = mariaSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(mariaPhoneOrg2.register(uri, "maria", clientPassword, "sip:[email protected]:5093", 3600, 3600)); assertTrue(alicePhoneOrg3.register(uri, "alice", "1234", "sip:[email protected]:5095", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "maria", clientPassword); mariaPhoneOrg2.addUpdateCredential(c); final SipCall aliceCallOrg3 = alicePhoneOrg3.createSipCall(); aliceCallOrg3.listenForIncomingCall(); Thread.sleep(1000); // Maria initiates a call to Alice long startTime = System.currentTimeMillis(); final SipCall mariaCall = mariaPhoneOrg2.createSipCall(); mariaCall.initiateOutgoingCall(mariaContactOrg2, aliceContactOrg3, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); //alice should not get the call assertTrue(!aliceCallOrg3.waitForIncomingCall(5000)); } /** * testDialActionAliceAnswers: * given: * clients: * bob@org2, alice@org2. * * given numbers: * 12223334455@org2 * 12223334455@org3 * * test case: bob@org2 INVITE 12223334455@org2 * result: call goes to alice@org2. * * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test public void testDialActionDialClient() throws ParseException, InterruptedException, UnknownHostException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); //register as alice@org2 uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600)); // Prepare alice's phone to receive call SipCall aliceCall = alicePhoneOrg2.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with bob@org final SipCall bobCall = bobPhoneOrg2.createSipCall(); bobCall.initiateOutgoingCall(bobContactOrg2, dialClientWithActionUrlOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(3000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } Thread.sleep(3000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=3")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSidOrg2, adminAuthToken, dialCallSid); assertNotNull(cdr); } /** * testDialActionHangupWithLCM: * given: * clients: * bob@org2, alice@org2. * * given numbers: * 12223334455@org2 * 12223334455@org3 * * test case1: bob@org2 INVITE 12223334455@org2 * result: call goes to alice@org2. * * test case2: hangup using LCM * result: call completes * * @throws ParseException * @throws InterruptedException * @throws UnknownHostException */ @Test @Category({FeatureAltTests.class}) public void testDialActionHangupWithLCM() throws Exception { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); SipURI uri = bobSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(bobPhoneOrg2.register(uri, "bob", clientPassword, "sip:[email protected]:5090", 3600, 3600)); Credential c = new Credential("org2.restcomm.com", "bob", clientPassword); bobPhoneOrg2.addUpdateCredential(c); // Phone2 register as alice uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600)); // Prepare second phone to receive call SipCall aliceCallOrg2 = alicePhoneOrg2.createSipCall(); aliceCallOrg2.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall(); bobCallOrg2.initiateOutgoingCall(bobContactOrg2, dialClientWithActionUrlOrg2, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCallOrg2); assertTrue(bobCallOrg2.waitForAuthorisation(3000)); assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCallOrg2.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCallOrg2.getLastReceivedResponse().getStatusCode()); String callSid = bobCallOrg2.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCallOrg2.sendInviteOkAck(); assertTrue(!(bobCallOrg2.getLastReceivedResponse().getStatusCode() >= 400)); bobCallOrg2.listenForDisconnect(); assertTrue(aliceCallOrg2.waitForIncomingCall(30 * 1000)); aliceCallOrg2.listenForCancel(); logger.info("About to execute LCM to hangup the call"); RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(),adminAccountSidOrg2,adminAuthToken,callSid,"completed", null); assertTrue(bobCallOrg2.waitForDisconnect(50 * 1000)); assertTrue(bobCallOrg2.respondToDisconnect()); Thread.sleep(10 * 1000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); logger.info("DialAction requestBody: "+requestBody); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); assertTrue(requestBody.contains("CallStatus=completed")); Iterator iter = Arrays.asList(params).iterator(); } @After public void after() throws Exception { if (bobPhoneOrg2 != null) { bobPhoneOrg2.dispose(); } if (bobSipStackOrg2 != null) { bobSipStackOrg2.dispose(); } if (bobPhoneOrg3 != null) { bobPhoneOrg3.dispose(); } if (bobSipStackOrg3 != null) { bobSipStackOrg3.dispose(); } if (bobPhoneDefaultOrg != null) { bobPhoneDefaultOrg.dispose(); } if (bobSipStackDefaultOrg != null) { bobSipStackDefaultOrg.dispose(); } if (mariaPhoneOrg2 != null) { mariaPhoneOrg2.dispose(); } if (mariaSipStackOrg2 != null) { mariaSipStackOrg2.dispose(); } if (aliceSipStackOrg2 != null) { aliceSipStackOrg2.dispose(); } if (alicePhoneOrg2 != null) { alicePhoneOrg2.dispose(); } if (aliceSipStackOrg3 != null) { aliceSipStackOrg3.dispose(); } if (alicePhoneOrg3 != null) { alicePhoneOrg3.dispose(); } if (shoaibSipStackOrg2 != null) { shoaibSipStackOrg2.dispose(); } if (shoaibPhoneOrg2 != null) { shoaibPhoneOrg2.dispose(); } if (pstnSipStack != null) { pstnSipStack.dispose(); } if (pstnPhone != null) { pstnPhone.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_sbc.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialActionTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-client-entry_wActionUrl.xml"); logger.info("Packaged Test App"); return archive; } }
53,807
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ReferTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ReferTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.ReferSubscriber; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.SipException; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.Arrays; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.cafesip.sipunit.SipAssert.assertNoSubscriptionErrors; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; /** * Test for SIP Refer support according to the RFC5589 spec in order to provide call transfer capabilities to deskphone * sip clients that use SIP Refer to implement call transfer. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={WithInMinsTests.class, SequentialClassTests.class}) public class ReferTest { private final static Logger logger = Logger.getLogger(ReferTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private String dialGeorgeRcml = "<Response><Dial><Number>+131313</Number></Dial></Response>"; private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test public void testTransfer() throws ParseException, InterruptedException, MalformedURLException, SipException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialGeorgeRcml))); stubFor(get(urlPathEqualTo("/2222")) .withQueryParam("ReferTarget", equalTo("alice")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int callResponse = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING); logger.info("Last response: "+callResponse); if (callResponse == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080"); ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000); assertNotNull(subscription); assertTrue(subscription.isSubscriptionPending()); assertTrue(subscription.processResponse(1000)); assertTrue(subscription.isSubscriptionPending()); assertNoSubscriptionErrors(subscription); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } requests = findAll(getRequestedFor(urlPathMatching("/2222"))); assertTrue(requests.size() == 1); requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery(); params = Arrays.asList(requestBody.split("&")); assertTrue(params.contains("Transferor=%2B131313")); assertTrue(params.contains("Transferee=bob")); assertTrue(params.contains("ReferTarget=alice")); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); } @Test public void testTransferToAnyNumber() throws ParseException, InterruptedException, MalformedURLException, SipException { stubFor(get(urlPathEqualTo("/gottacatchemall")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialGeorgeRcml))); stubFor(get(urlPathEqualTo("/2222")) .withQueryParam("ReferTarget", equalTo("alice")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int callResponse = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING); logger.info("Last response: "+callResponse); if (callResponse == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080"); ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000); assertNotNull(subscription); assertTrue(subscription.isSubscriptionPending()); assertTrue(subscription.processResponse(1000)); assertTrue(subscription.isSubscriptionPending()); assertNoSubscriptionErrors(subscription); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/gottacatchemall"))); assertTrue(requests.size() == 1); String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); } @Test public void testTransferToNumberWithPlusSign() throws ParseException, InterruptedException, MalformedURLException, SipException { stubFor(get(urlPathEqualTo("/1112")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialGeorgeRcml))); stubFor(get(urlPathEqualTo("/2222")) .withQueryParam("ReferTarget", equalTo("alice")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int callResponse = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING); logger.info("Last response: "+callResponse); if (callResponse == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080"); ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000); assertNotNull(subscription); assertTrue(subscription.isSubscriptionPending()); assertTrue(subscription.processResponse(1000)); assertTrue(subscription.isSubscriptionPending()); assertNoSubscriptionErrors(subscription); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1112"))); assertTrue(requests.size() == 1); String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); } @Test @Category(FeatureAltTests.class) public void testTransferHangupByBob() throws ParseException, InterruptedException, MalformedURLException, SipException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialGeorgeRcml))); stubFor(get(urlPathEqualTo("/2222")) .withQueryParam("ReferTarget", equalTo("alice")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int callResponse = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING); logger.info("Last response: "+callResponse); if (callResponse == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080"); ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000); assertNotNull(subscription); assertTrue(subscription.isSubscriptionPending()); assertTrue(subscription.processResponse(1000)); assertTrue(subscription.isSubscriptionPending()); assertNoSubscriptionErrors(subscription); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveIncomingCalls==1); assertTrue(liveOutgoingCalls==1); assertTrue(liveCallsArraySize==2); aliceCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); } @Test public void testTransferByBob() throws ParseException, InterruptedException, MalformedURLException, SipException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialGeorgeRcml))); stubFor(get(urlPathEqualTo("/2222")) .withQueryParam("ReferTarget", equalTo("alice")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int callResponse = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING); logger.info("Last response: "+callResponse); if (callResponse == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(6000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); SipURI referTo = bobSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080"); ReferSubscriber subscription = bobPhone.refer(bobCall.getDialog(), referTo, null, 5000); assertNotNull(subscription); assertTrue(subscription.isSubscriptionPending()); assertTrue(subscription.processResponse(1000)); assertTrue(subscription.isSubscriptionPending()); assertNoSubscriptionErrors(subscription); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(10000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==2); assertTrue(liveOutgoingCalls==2); assertTrue(liveCallsArraySize==2); georgeCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); //This will fail because CDR is not updated because Observers are cleared // assertEquals("complete", jsonObj.get("status").getAsString()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls==0); assertTrue(liveCallsArraySize==0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls==2); assertTrue(maxConcurrentIncomingCalls==1); assertTrue(maxConcurrentOutgoingCalls==1); } @Test @Category(FeatureExpTests.class) public void testTransferWithAbsentReferUrlAndApplication() throws ParseException, InterruptedException, MalformedURLException, SipException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialGeorgeRcml))); stubFor(get(urlPathEqualTo("/2222")) .withQueryParam("ReferTarget", equalTo("alice")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int callResponse = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING); logger.info("Last response: "+callResponse); if (callResponse == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080"); ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000); assertNull(subscription); assertEquals("Received response status: 404, reason: Not found", georgePhone.getErrorMessage()); } @Test @Category(FeatureExpTests.class) public void testTransferWithOutOfDialogRefer() throws ParseException, InterruptedException, MalformedURLException, SipException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialGeorgeRcml))); stubFor(get(urlPathEqualTo("/2222")) .withQueryParam("ReferTarget", equalTo("alice")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int callResponse = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING); logger.info("Last response: "+callResponse); if (callResponse == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080"); ReferSubscriber subscription = georgePhone.refer(bobContact, referTo, null, 5000, null); assertNotNull(subscription); assertFalse(subscription.processResponse(1000)); assertEquals("Received response status: 404, reason: Not found", subscription.getErrorMessage()); } private String dialJoeRcml = "<Response><Dial><Client>joe</Client></Dial></Response>"; @Test @Category(FeatureExpTests.class) public void testTransferIncorrectReferTarget() throws ParseException, InterruptedException, MalformedURLException, SipException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialGeorgeRcml))); stubFor(get(urlPathEqualTo("/2222")) .withQueryParam("ReferTarget", equalTo("joe")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialJoeRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); georgeCall.listenForDisconnect(); bobCall.listenForDisconnect(); SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("joe", "127.0.0.1:5080"); georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.delete("/WEB-INF/classes/application.conf"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_calllifecycle.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_ReferMessageTest", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); logger.info("Packaged Test App"); return archive; } }
52,441
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialRecordingS3UploadNoneSecurityTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialRecordingS3UploadNoneSecurityTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.text.ParseException; import java.util.List; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; /** * Created by gvagenas on 08/01/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class DialRecordingS3UploadNoneSecurityTest { private final static Logger logger = Logger.getLogger(DialRecordingS3UploadNoneSecurityTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private String henriqueContact = "sip:[email protected]:5092"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; private String dialRestcomm = "sip:[email protected]:5080"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice_BobDisconnects() throws InterruptedException, ParseException, IOException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") .withHeader("Server", "AmazonS3") )); stubFor(get(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("X-Amz-Algorithm", "AWS4-HMAC-SHA256") )); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3500); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(1000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0 , duration, 0.5); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); assertTrue(recording.get(0).getAsJsonObject().get("s3_uri").getAsString().startsWith("http://127.0.0.1:8090/s3")); URL url = new URL(recording.get(0).getAsJsonObject().get("file_uri").getAsString()); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); Thread.sleep(1000); assertEquals(200, connection.getResponseCode()); Thread.sleep(6000); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); } @Test public synchronized void testDialClientAlice_AliceDisconnects() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); stubFor(put(urlPathEqualTo("/s3")) .willReturn(aResponse() .withStatus(200) .withHeader("x-amz-id-2","LriYPLdmOdAiIfgSm/F1YsViT1LW94/xUQxMsF7xiEb1a0wiIOIxl+zbwZ163pt7") .withHeader("x-amz-request-id","0A49CE4060975EAC") .withHeader("Date", DateTime.now().toString()) .withHeader("x-amz-expiration", "expiry-date="+DateTime.now().plusDays(3).toString()+"\", rule-id=\"1\"") // .withHeader("ETag", "1b2cf535f27731c974343645a3985328") .withHeader("Server", "AmazonS3") )); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.listenForDisconnect(); aliceCall.disconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(7000); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0,duration,0.5); assertTrue(recording.get(0).getAsJsonObject().get("file_uri").getAsString().contains("/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/")); assertTrue(recording.get(0).getAsJsonObject().get("s3_uri").getAsString().startsWith("http://127.0.0.1:8090/s3")); //Verify S3 Upload List<LoggedRequest> requests = findAll(putRequestedFor(urlMatching("/s3/.*"))); assertEquals(1, requests.size()); verify(1, putRequestedFor(urlMatching("/s3/.*"))); } @Test @Ignore //The code we used to support old DB schema was removed - George 26/06/2018 public void testGetRecordingWithOldS3Url() { String callSid = "CA2d3f6354e75e46b3ac76f534129ff511"; DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"); DateTime lastDateUpdate = formatter.parseDateTime("2017-04-05 12:57:35.583000"); JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertTrue(duration==3.0); assertTrue(!recording.get(0).getAsJsonObject().get("file_uri").getAsString().startsWith("https://s3.amazonaws.com")); //Wed, 5 Apr 2017 13:33:03 +0300 formatter = DateTimeFormat.forPattern("EEE, d MMM yyyy HH:mm:ss Z"); DateTime dateUpdated = formatter.parseDateTime(recording.get(0).getAsJsonObject().get("date_updated").getAsString()); assertTrue(dateUpdated.isAfter(lastDateUpdate)); String expectedS3Uri = "http://127.0.0.1:8090/s3/restcomm-as-a-service/logs/RE7a2345a37a2a4f18a2a715e8f352c4ed.wav"; assertEquals(expectedS3Uri, recording.get(0).getAsJsonObject().get("s3_uri").getAsString()); //Second time we access the recording THERE MUST BE NO update since we fixed S3_URI and FILE_URI in the previous call recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); DateTime dateUpdated2 = formatter.parseDateTime(recording.get(0).getAsJsonObject().get("date_updated").getAsString()); assertTrue(!dateUpdated2.isAfter(dateUpdated)); assertEquals(expectedS3Uri, recording.get(0).getAsJsonObject().get("s3_uri").getAsString()); } @Deployment(name = "DialRecordingS3UploadSecureTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.delete("/WEB-INF/classes/application.conf"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_recording_s3_upload_none_security.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_DialRecording", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); logger.info("Packaged Test App"); return archive; } }
17,598
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialConferenceConnectionFailureTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialConferenceConnectionFailureTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.URL; import java.util.Map; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.testsuite.http.RestcommConferenceTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; /** * @author mariafarooq * https://telestax.atlassian.net/browse/RESTCOMM-1343 */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={SequentialClassTests.class}) public class DialConferenceConnectionFailureTest { private final static Logger logger = Logger.getLogger(DialConferenceConnectionFailureTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; private String dialRestcomm = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialConferenceTool1"); tool2 = new SipStackTool("DialConferenceTool3"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(4000); } private final String confRoom2 = "confRoom2"; private String dialConfernceRcml = "<Response><Dial><Conference>"+confRoom2+"</Conference></Dial></Response>"; @Test public synchronized void testDialConferenceConnectionFailureCallCleanupTest() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(80 * 1000)); Thread.sleep(3000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); assertEquals(1, RestcommConferenceTool.getInstance().getConferencesSize(deploymentUrl.toString(), adminAccountSid, adminAuthToken)); int numOfParticipants = RestcommConferenceTool.getInstance().getParticipantsSize(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confRoom2); assertEquals(0, numOfParticipants); logger.info("going to check mgcpResources"); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); assertEquals(0, (int)mgcpResources.get("MgcpEndpoints")); assertEquals(0, (int)mgcpResources.get("MgcpConnections")); } @Deployment(name = "DialConferenceTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-with-failing-mockmedia.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest_new", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
8,703
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PlayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/PlayTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mobicents.arquillian.mediaserver.api.EmbeddedMediaserver; import org.mobicents.arquillian.mediaserver.api.MgcpEventListener; import org.mobicents.arquillian.mediaserver.api.annotations.Mediaserver; import org.mobicents.commtesting.MgcpUnit; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInSecsTests; /** * @author Amit Bhayani * */ @Ignore //The mss-arquillian mms extension needs update @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class PlayTest { private final static Logger logger = Logger.getLogger(PlayTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; private static SipStackTool tool1; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; @Mediaserver(IVR = 10, CONF = 10, RELAY = 10)//, BRIDGE = 10) private EmbeddedMediaserver mediaserver; private MgcpUnit mgcpUnit; private MgcpEventListener mgcpEventListener; private String dialPlay = "sip:[email protected]:5080"; /** * */ public PlayTest() { // TODO Auto-generated constructor stub } @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("CallTestDial1"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); mgcpUnit = new MgcpUnit(); mgcpEventListener = mgcpUnit.getMgcpEventListener(); mediaserver.registerListener(mgcpEventListener); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } mgcpEventListener = null; mgcpUnit = null; } /** * Makes use of hello-play.xml which simply plays demo-prompt.wav * @throws InterruptedException */ @Test public synchronized void testPlay() throws InterruptedException { deployer.deploy("PlayTest"); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialPlay, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // Start a new thread for bob to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(bobCall.waitForDisconnect(30 * 1000)); } }).start(); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Deployment(name = "PlayTest", managed = false, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive);; archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-embeddedMMS.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_playTest", "data/hsql/restcomm.script"); archive.addAsWebResource("hello-play.xml"); logger.info("Packaged Test App"); return archive; } }
7,692
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NoAuthRegisterClientTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/NoAuthRegisterClientTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.net.URL; import java.text.ParseException; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.http.CreateClientsTool; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.commons.annotations.UnstableTests; /** * Client registration Test. * Maria client is using two sip clients to register * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class NoAuthRegisterClientTest { private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStack; private SipPhone mariaPhone; private String mariaContact = "sip:[email protected]:5092"; private String mariaRestcommClientSid; // Dimitris is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStack2; private SipPhone mariaPhone2; private String mariaContact2 = "sip:[email protected]:5093"; private String mariaRestcommContact = "sip:[email protected]:5080"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5091"; private String georgeRestcommClientSid; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String strongPassword = "Qwert12345"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("RegisterClientTest1"); tool2 = new SipStackTool("RegisterClientTest2"); tool3 = new SipStackTool("RegisterClientTest3"); } @Before public void before() throws Exception { georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); mariaSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); mariaPhone = mariaSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContact); mariaSipStack2 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.1.1", "5093", "127.0.0.1:5080"); mariaPhone2 = mariaSipStack2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContact2); mariaRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "maria", strongPassword, null); georgeRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "george", strongPassword, null); } @After public void after() throws Exception { if (mariaPhone != null) { mariaPhone.dispose(); } if (mariaSipStack != null) { mariaSipStack.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (mariaSipStack2 != null) { mariaSipStack2.dispose(); } if (mariaPhone2 != null) { mariaPhone2.dispose(); } } @Test @Category(UnstableTests.class) public void testGeorgeCallMaria() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(georgeRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(georgePhone.register(uri, "", "", georgeContact, 3600, 3600)); Thread.sleep(3000); assertTrue(mariaPhone.register(uri, "", "", mariaContact, 3600, 3600)); Thread.sleep(3000); assertTrue(mariaPhone2.register(uri, "", "", mariaContact2, 3600, 3600)); Thread.sleep(3000); // Credential c = new Credential("127.0.0.1", "george", strongPassword); // georgePhone.addUpdateCredential(c); // // Credential c2 = new Credential("127.0.0.1", "maria", strongPassword); // mariaPhone.addUpdateCredential(c2); // // Credential c3 = new Credential("127.0.0.1", "maria", strongPassword); // mariaPhone2.addUpdateCredential(c3); Thread.sleep(1000); final SipCall mariaCall_1 = mariaPhone.createSipCall(); mariaCall_1.listenForIncomingCall(); final SipCall mariaCall_2 = mariaPhone2.createSipCall(); mariaCall_2.listenForIncomingCall(); // Alice initiates a call to Maria final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, mariaRestcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertFalse(georgeCall.waitForAuthorisation(1000)); //According to issue 106: https://telestax.atlassian.net/browse/RESTCOMM-106 //Restcomm will only use the last REGISTER address //Last REGISTRATION was from Maria-2 assertTrue(mariaCall_2.waitForIncomingCall(3000)); assertTrue(mariaCall_2.sendIncomingCallResponse(100, "Trying-Maria-2", 1800)); assertTrue(mariaCall_2.sendIncomingCallResponse(180, "Ringing-Maria-2", 1800)); String receivedBody = new String(mariaCall_2.getLastReceivedRequest().getRawContent()); assertTrue(mariaCall_2.sendIncomingCallResponse(Response.OK, "OK-Maria-2", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(!mariaCall_1.waitForIncomingCall(3000)); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int georgeResponse = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(georgeResponse == Response.TRYING || georgeResponse == Response.RINGING); // Dialog georgeDialog = null; if (georgeResponse == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); // georgeDialog = georgeCall.getDialog(); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); assertTrue(georgeCall.sendInviteOkAck()); // assertTrue(georgeCall.getDialog().equals(georgeDialog)); // assertTrue(georgeCall.getDialog().equals(georgeDialog)); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); // Thread.sleep(3000); // assertTrue(georgeCall.disconnect()); // // assertTrue(mariaCall_2.waitForDisconnect(5 * 1000)); // assertTrue(mariaCall_2.respondToDisconnect()); //Check CDR JsonObject cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); assertTrue(cdrsArray.size() == 1); } @Test public void testRegisterClients() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(georgeRestcommClientSid); SipURI uri = georgeSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(georgePhone.register(uri, "", "", georgeContact, 3600, 3600)); assertTrue(mariaPhone.register(uri, "", "", mariaContact, 3600, 3600)); assertTrue(mariaPhone2.register(uri, "", "", mariaContact2, 3600, 3600)); Thread.sleep(1000); assertTrue(georgePhone.unregister(georgeContact, 0)); assertTrue(mariaPhone.unregister(mariaContact, 0)); assertTrue(mariaPhone2.unregister(mariaContact2, 0)); } @Deployment(name = "RegisterClientTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("org/restcomm/connect/telephony/restcomm_no_auth.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-conference-entry.xml"); archive.addAsWebResource("dial-fork-entry.xml"); archive.addAsWebResource("dial-uri-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("dial-number-entry.xml"); return archive; } }
12,752
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialActionTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialActionTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.header.Header; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; /** * Test for Dial Action attribute. Reference: https://www.twilio.com/docs/api/twiml/dial#attributes-action The 'action' * attribute takes a URL as an argument. When the dialed call ends, Restcomm will make a GET or POST request to this URL * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class DialActionTest { private final static Logger logger = Logger.getLogger(DialActionTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialClientWithActionUrl = "sip:+12223334455@" + restcommContact; // Application: dial-client-entry_wActionUrl.xml @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialClientWithActionUrl = "sip:+12223334455@" + restcommContact; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @Test @Category(UnstableTests.class) public void testDialActionInvalidCall() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(40 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=failed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertTrue(dialCallSid.equals("null")); //Since ALICE is not registered, CallManager will ask to hangup the call, thus we never have outbound call // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); // assertNotNull(cdr); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test //No regression test for https://github.com/Mobicents/RestComm/issues/505 @Category(UnstableTests.class) public void testDialActionInvalidCallCheckCallStatusCompleted() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(40 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); //DialCallStatus should be null since there was no call made - since Alice is not registered assertTrue(requestBody.contains("DialCallStatus=failed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); //When the Dial finish and since the Dialbranch = 0, the Dial Action is executed while Call is in progress assertTrue(requestBody.contains("CallStatus=in-progress")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertTrue(dialCallSid.equals("null")); //Since ALICE is not registered, CallManager will ask to hangup the call, thus we never have outbound call // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); // assertNotNull(cdr); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(WithInMinsTests.class) public void testDialActionAliceAnswers() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } Thread.sleep(3000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=3")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialActionAliceAnswersAliceHangup() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=3")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialActionAliceAnswersBobDisconnects() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=3")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialActionAliceNOAnswer() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.listenForCancel()); SipTransaction cancelTransaction = aliceCall.waitForCancel(30 * 1000); assertNotNull(cancelTransaction); assertTrue(aliceCall.respondToCancel(cancelTransaction, Response.OK, "Alice-OK-2-Cancel", 3600)); Thread.sleep(3700); assertTrue(bobCall.disconnect()); Thread.sleep(10000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); if (!requestBody.contains("DialCallStatus=no-answer")) { String msgToPrint = requestBody.replaceAll("&", "\n"); logger.info("requestBody: \n"+"\n ---------------------- \n"+msgToPrint+"\n---------------------- "); } assertTrue(requestBody.contains("DialCallStatus=canceled")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialRingDuration=3")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialActionAliceBusy() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); if (!requestBody.contains("DialCallStatus=busy")) { logger.info("requestBody: \n"+requestBody); } assertTrue(requestBody.contains("DialCallStatus=busy")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testDialActionHangupWithLCM() throws Exception { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); aliceCall.listenForCancel(); logger.info("About to execute LCM to hangup the call"); RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid,"completed", null); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); // logger.info("&&&&&&&&&&&&&&&&&&&&&& Alice about to listen for CANCEL"); // SipTransaction sipTransaction = aliceCall.waitForCancel(50 * 1000); // assertNotNull(sipTransaction); // aliceCall.respondToCancel(sipTransaction,200,"Alice-OK-To-Cancel",3600); // aliceCall.respondToCancel(sipTransaction,487,"Alice-Request-Terminated",3600); Thread.sleep(10 * 1000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); assertTrue(requestBody.contains("CallStatus=completed")); Iterator iter = Arrays.asList(params).iterator(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } /** * This test verifies: if Diversion header is present in INVITE, we update ForwardedFrom in cdr. * * @throws ParseException * @throws InterruptedException */ @Test @Category(WithInMinsTests.class) public void testSipInviteDiversionHeader() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); ArrayList<String> additionalHeaders = new ArrayList<String>(); Header diversionHeader = aliceSipStack.getHeaderFactory().createHeader("Diversion", "<sip:[email protected]>;counter=1;reason=UNKNOWN"); additionalHeaders.add(diversionHeader.toString()); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); // Add custom headers to the SIP INVITE String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); logger.info("requestBody = "+requestBody); System.out.println("requestBody = "+requestBody); assertTrue(requestBody.contains("SipHeader_Diversion=%3Csip%3A11223344%40xyz.com%3E%3Bcounter%3D1%3Breason%3DUNKNOWN")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("CallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); logger.info("cdr = "+cdr); assertNotNull(cdr); String forwardedFrom = cdr.get("forwarded_from").getAsString(); assertNotNull(forwardedFrom); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(WithInMinsTests.class) public void testSipInviteCustomHeaders() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); ArrayList<String> additionalHeaders = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-My-Custom-Header", "My Custom Value"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-OtherHeader", "Other Value"); Header anotherHeader = aliceSipStack.getHeaderFactory().createHeader("X-another-header", "another value"); additionalHeaders.add(customHeader.toString()); additionalHeaders.add(otherHeader.toString()); additionalHeaders.add(anotherHeader.toString()); // bobCall.initiateOutgoingCall(fromUri, toUri, viaNonProxyRoute, body, contentType, contentSubType, additionalHeaders, replaceHeaders) // bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, additionalHeaders, null, body); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); // Add custom headers to the SIP INVITE String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); // public boolean sendIncomingCallResponse(int statusCode, // String reasonPhrase, int expires, String body, String contentType, // String contentSubType, ArrayList<String> additionalHeaders, // ArrayList<String> replaceHeaders) assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); // assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, null, null, receivedBody)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("SipHeader_X-My-Custom-Header=My+Custom+Value")); assertTrue(requestBody.contains("SipHeader_X-OtherHeader=Other+Value")); assertTrue(requestBody.contains("SipHeader_X-another-header=another+value")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test //TODO: PASSES when run individually. to check @Category(WithInMinsTests.class) public void testDialCallDurationAliceAnswers() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); Thread.sleep(2000); //Ringing time String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); //Talk time // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("DialCallDuration=3")); assertTrue(requestBody.contains("DialRingDuration=2")); Iterator iter = Arrays.asList(params).iterator(); String callSid = null; String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("CallSid")) { callSid = param.split("=")[1]; } else if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; } } assertNotNull(callSid); assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject dialCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); assertNotNull(dialCdr); //INBOUND call has no ring_duration since Restcomm will answer imediatelly an incoming call assertTrue(cdr.get("duration").getAsString().equalsIgnoreCase("5")); //Only talk time assertTrue(cdr.get("direction").getAsString().equalsIgnoreCase("inbound")); assertTrue(dialCdr.get("duration").getAsString().equalsIgnoreCase("3")); //Only talk time assertTrue(dialCdr.get("ring_duration").getAsString().equalsIgnoreCase("2")); //Only Ringing time assertTrue(dialCdr.get("direction").getAsString().equalsIgnoreCase("outbound-api")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test //TODO: PASSES when run individually. to check public void testDialCallDurationAliceBusy() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); Thread.sleep(2000); //Ringing Time assertTrue(aliceCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertEquals(1, requests.size()); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=busy")); assertTrue(requestBody.contains("DialCallDuration=0")); assertTrue(requestBody.contains("DialRingDuration=2")); Iterator iter = Arrays.asList(params).iterator(); String callSid = null; String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("CallSid")) { callSid = param.split("=")[1]; } else if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; } } assertNotNull(callSid); assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject dialCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); assertNotNull(dialCdr); //Since the outbound call to Alice never got established the duration of the inbound call is not defined //assertTrue(cdr.get("duration").getAsString().equalsIgnoreCase("0")); //Only talk time //assertTrue(cdr.get("ring_duration").getAsString().equalsIgnoreCase("0")); assertTrue(cdr.get("direction").getAsString().equalsIgnoreCase("inbound")); assertTrue(dialCdr.get("duration").getAsString().equalsIgnoreCase("0")); //Only talk time assertTrue(dialCdr.get("ring_duration").getAsString().equalsIgnoreCase("2")); //Only Ringing time assertTrue(dialCdr.get("direction").getAsString().equalsIgnoreCase("outbound-api")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); List<String> resources = new ArrayList(Arrays.asList("dial-client-entry_wActionUrl.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm.xml", "restcomm.script_dialActionTest",resources, replacements); } }
60,741
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialActionAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialActionAnswerDelayTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.header.Header; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; /** * Test for Dial Action attribute. Reference: https://www.twilio.com/docs/api/twiml/dial#attributes-action The 'action' * attribute takes a URL as an argument. When the dialed call ends, Restcomm will make a GET or POST request to this URL * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, ParallelClassTests.class}) public class DialActionAnswerDelayTest { private final static Logger logger = Logger.getLogger(DialActionAnswerDelayTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialClientWithActionUrl = "sip:+12223334455@" + restcommContact; // Application: dial-client-entry_wActionUrl.xml private String dialActionRcml = "<Response><Dial><Number>+131313</Number></Dial></Response>"; private String playPlusDialActionRcml; private String dialActionRcmlPlay; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionAnswerDelayTest1"); tool2 = new SipStackTool("DialActionAnswerDelayTest2"); tool3 = new SipStackTool("DialActionAnswerDelayTest3"); tool4 = new SipStackTool("DialActionAnswerDelayTest4"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialClientWithActionUrl = "sip:+12223334455@" + restcommContact; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); dialActionRcmlPlay = "<Response><Play>"+deploymentUrl.toString()+"audio/demo-prompt.wav</Play></Response>"; playPlusDialActionRcml = "<Response><Play>"+deploymentUrl.toString()+"audio/demo-prompt.wav</Play><Dial><Number>+131313</Number></Dial></Response>"; } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @Test @Category(UnstableTests.class) public void testDialActionInvalidCall() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVER_INTERNAL_ERROR, bobCall.getLastReceivedResponse().getStatusCode()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=failed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertTrue(dialCallSid.equals("null")); //Since ALICE is not registered, CallManager will ask to hangup the call, thus we never have outbound call // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); // assertNotNull(cdr); } @Test //No regression test for https://github.com/Mobicents/RestComm/issues/505 @Category(UnstableTests.class) public void testDialActionInvalidCallCheckCallStatusCompleted() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVER_INTERNAL_ERROR, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(10 * 1000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); //DialCallStatus should be null since there was no call made - since Alice is not registered assertTrue(requestBody.contains("DialCallStatus=failed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); assertTrue(requestBody.contains("CallStatus=wait-for-answer")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertTrue(dialCallSid.equals("null")); //Since ALICE is not registered, CallManager will ask to hangup the call, thus we never have outbound call // JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); // assertNotNull(cdr); } @Test @Category(WithInMinsTests.class) public void testDialActionAliceAnswers() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } Thread.sleep(3000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=3")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Test public void testDialActionAliceAnswersAliceHangup() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=3")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Test public void testDialActionAliceAnswersBobDisconnects() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=3")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Test public void testDialActionAliceNOAnswer() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.listenForCancel()); SipTransaction cancelTransaction = aliceCall.waitForCancel(30 * 1000); assertNotNull(cancelTransaction); assertTrue(aliceCall.respondToCancel(cancelTransaction, Response.OK, "Alice-OK-2-Cancel", 3600)); assertTrue(bobCall.waitOutgoingCallResponse(120 * 1000)); assertEquals(Response.REQUEST_TIMEOUT, bobCall.getLastReceivedResponse().getStatusCode()); Thread.sleep(3700); Thread.sleep(10000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); if (!requestBody.contains("DialCallStatus=no-answer")) { String msgToPrint = requestBody.replaceAll("&", "\n"); logger.info("requestBody: \n"+"\n ---------------------- \n"+msgToPrint+"\n---------------------- "); } assertTrue(requestBody.contains("DialCallStatus=canceled")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialRingDuration=3")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Test public void testDialActionAliceBusy() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.BUSY_HERE, bobCall.getLastReceivedResponse().getStatusCode()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); if (!requestBody.contains("DialCallStatus=busy")) { logger.info("requestBody: \n"+requestBody); } assertTrue(requestBody.contains("DialCallStatus=busy")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Test @Category(WithInMinsTests.class) public void testSipInviteCustomHeaders() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); ArrayList<String> additionalHeaders = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-My-Custom-Header", "My Custom Value"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-OtherHeader", "Other Value"); Header anotherHeader = aliceSipStack.getHeaderFactory().createHeader("X-another-header", "another value"); additionalHeaders.add(customHeader.toString()); additionalHeaders.add(otherHeader.toString()); additionalHeaders.add(anotherHeader.toString()); // bobCall.initiateOutgoingCall(fromUri, toUri, viaNonProxyRoute, body, contentType, contentSubType, additionalHeaders, replaceHeaders) // bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, additionalHeaders, null, body); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); // Add custom headers to the SIP INVITE String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); // public boolean sendIncomingCallResponse(int statusCode, // String reasonPhrase, int expires, String body, String contentType, // String contentSubType, ArrayList<String> additionalHeaders, // ArrayList<String> replaceHeaders) assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); // assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, null, null, receivedBody)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("SipHeader_X-My-Custom-Header=My+Custom+Value")); assertTrue(requestBody.contains("SipHeader_X-OtherHeader=Other+Value")); assertTrue(requestBody.contains("SipHeader_X-another-header=another+value")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Test //TODO: PASSES when run individually. to check @Category(WithInMinsTests.class) public void testDialCallDurationAliceAnswers() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); Thread.sleep(2000); //Ringing time String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); //Talk time // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(50 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=completed")); assertTrue(requestBody.contains("DialCallDuration=3")); assertTrue(requestBody.contains("DialRingDuration=2")); Iterator iter = Arrays.asList(params).iterator(); String callSid = null; String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("CallSid")) { callSid = param.split("=")[1]; } else if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; } } assertNotNull(callSid); assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject dialCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); assertNotNull(dialCdr); //INBOUND call has no ring_duration since Restcomm will answer imediatelly an incoming call assertTrue(cdr.get("duration").getAsString().equalsIgnoreCase("5")); //Only talk time assertTrue(cdr.get("direction").getAsString().equalsIgnoreCase("inbound")); assertTrue(dialCdr.get("duration").getAsString().equalsIgnoreCase("3")); //Only talk time assertTrue(dialCdr.get("ring_duration").getAsString().equalsIgnoreCase("2")); //Only Ringing time assertTrue(dialCdr.get("direction").getAsString().equalsIgnoreCase("outbound-api")); } @Test //TODO: PASSES when run individually. to check public void testDialCallDurationAliceBusy() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); Thread.sleep(2000); //Ringing Time assertTrue(aliceCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.BUSY_HERE, bobCall.getLastReceivedResponse().getStatusCode()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); assertTrue(requestBody.contains("DialCallStatus=busy")); assertTrue(requestBody.contains("DialCallDuration=0")); assertTrue(requestBody.contains("DialRingDuration=2")); Iterator iter = Arrays.asList(params).iterator(); String callSid = null; String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("CallSid")) { callSid = param.split("=")[1]; } else if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; } } assertNotNull(callSid); assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject dialCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); assertNotNull(dialCdr); //Since the outbound call to Alice never got established the duration of the inbound call is not defined //assertTrue(cdr.get("duration").getAsString().equalsIgnoreCase("0")); //Only talk time //assertTrue(cdr.get("ring_duration").getAsString().equalsIgnoreCase("0")); assertTrue(cdr.get("direction").getAsString().equalsIgnoreCase("inbound")); assertTrue(dialCdr.get("duration").getAsString().equalsIgnoreCase("0")); //Only talk time assertTrue(dialCdr.get("ring_duration").getAsString().equalsIgnoreCase("2")); //Only Ringing time assertTrue(dialCdr.get("direction").getAsString().equalsIgnoreCase("outbound-api")); } @Test public void testDialActionAliceNOAnswerRcmlOnDialAction() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.listenForCancel()); SipTransaction cancelTransaction = aliceCall.waitForCancel(30 * 1000); assertNotNull(cancelTransaction); assertTrue(aliceCall.respondToCancel(cancelTransaction, Response.OK, "Alice-OK-2-Cancel", 3600)); assertTrue(georgeCall.waitForIncomingCall(5000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. georgeCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(5000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); if (!requestBody.contains("DialCallStatus=no-answer")) { String msgToPrint = requestBody.replaceAll("&", "\n"); logger.info("requestBody: \n"+"\n ---------------------- \n"+msgToPrint+"\n---------------------- "); } assertTrue(requestBody.contains("DialCallStatus=canceled")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialRingDuration=3")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Test public void testDialActionAliceNOAnswerRcmlPlayOnDialAction() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialActionRcmlPlay))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.listenForCancel()); SipTransaction cancelTransaction = aliceCall.waitForCancel(30 * 1000); assertNotNull(cancelTransaction); assertTrue(aliceCall.respondToCancel(cancelTransaction, Response.OK, "Alice-OK-2-Cancel", 3600)); assertTrue(bobCall.waitOutgoingCallResponse(50 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); logger.info("bob listenForDisconnect"); assertTrue(bobCall.waitForDisconnect(120 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(5000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); if (!requestBody.contains("DialCallStatus=no-answer")) { String msgToPrint = requestBody.replaceAll("&", "\n"); logger.info("requestBody: \n"+"\n ---------------------- \n"+msgToPrint+"\n---------------------- "); } assertTrue(requestBody.contains("DialCallStatus=canceled")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialRingDuration=3")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Test public void testDialActionAliceNOAnswerPlayPlusDialRcmlOnDialAction() throws ParseException, InterruptedException { stubFor(post(urlPathMatching("/DialAction.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(playPlusDialActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithActionUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.listenForCancel()); SipTransaction cancelTransaction = aliceCall.waitForCancel(30 * 1000); assertNotNull(cancelTransaction); assertTrue(aliceCall.respondToCancel(cancelTransaction, Response.OK, "Alice-OK-2-Cancel", 3600)); Thread.sleep(6000); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); logger.info("George is going to waitForIncomingCall"); assertTrue(georgeCall.waitForIncomingCall(12000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. georgeCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(5000); logger.info("About to check the DialAction Requests"); List<LoggedRequest> requests = findAll(postRequestedFor(urlPathMatching("/DialAction.*"))); assertTrue(requests.size() == 1); String requestBody = requests.get(0).getBodyAsString(); String[] params = requestBody.split("&"); if (!requestBody.contains("DialCallStatus=no-answer")) { String msgToPrint = requestBody.replaceAll("&", "\n"); logger.info("requestBody: \n"+"\n ---------------------- \n"+msgToPrint+"\n---------------------- "); } assertTrue(requestBody.contains("DialCallStatus=canceled")); assertTrue(requestBody.contains("To=%2B12223334455")); assertTrue(requestBody.contains("From=bob")); assertTrue(requestBody.contains("DialRingDuration=3")); assertTrue(requestBody.contains("DialCallDuration=0")); Iterator iter = Arrays.asList(params).iterator(); String dialCallSid = null; while (iter.hasNext()) { String param = (String) iter.next(); if (param.startsWith("DialCallSid")) { dialCallSid = param.split("=")[1]; break; } } assertNotNull(dialCallSid); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, dialCallSid); assertNotNull(cdr); } @Deployment(name = "DialActionAnswerDelay", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); List<String> resources = new ArrayList(Arrays.asList("dial-client-entry_wActionUrl.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm-delay.xml", "restcomm.script_dialActionTest",resources, replacements); } }
59,815
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TestGatherVerb.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestGatherVerb.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import gov.nist.javax.sip.header.ContentType; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import javax.sip.Dialog; import javax.sip.SipException; import javax.sip.message.Request; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; /** * Test for Dial verb. Will test Dial Conference, Dial URI, Dial Client, Dial Number and Dial Fork * * @author <a href="mailto:[email protected]">Hoan HL</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(SequentialClassTests.class) public class TestGatherVerb { private final static Logger logger = Logger.getLogger(TestDialVerbPartTwo.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; private String dialRestcomm = "sip:[email protected]:5080"; private String dialRestcommWithStatusCallback = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialTest2Tool1"); tool2 = new SipStackTool("DialTest2Tool2"); tool3 = new SipStackTool("DialTest2Tool3"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } private String dtmfWithSipInfo = "<Response><Gather action=\"http://127.0.0.1:8090/dtmfAction\" method=\"GET\" numDigits=\"3\"></Gather></Response>"; private String hangupActionRcml = "<Response><Hangup /></Response>"; @Test //Test case for github issue 2415 public synchronized void testDtmfWithSipInfo() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dtmfWithSipInfo))); stubFor(get(urlPathEqualTo("/dtmfAction")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupActionRcml))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); Dialog dialog = bobCall.getDialog(); String infoBody = "Signal=3\r\n" + "Duration=28\r\n"; Request info = null; try { info = dialog.createRequest(Request.INFO); } catch (SipException e) { e.printStackTrace(); } ContentType contentType = new ContentType(); contentType.setContentType("application"); contentType.setContentSubType("dtmf-relay"); info.setContent(infoBody.getBytes(), contentType); SipTransaction infoTransaction = bobPhone.sendRequestWithTransaction(info, false, dialog); assertNotNull(infoTransaction); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(15000)); assertTrue(bobCall.respondToDisconnect()); List<LoggedRequest> recordActionRequests = findAll(getRequestedFor(urlPathMatching("/dtmfAction.*"))); assertTrue(recordActionRequests.size()==1); logger.info(recordActionRequests.get(0).toString().contains("Digits=3")); } @Test //Test case for github issue 2415 @Category(FeatureAltTests.class) public synchronized void testDtmfWithSipInfoWith3Number() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dtmfWithSipInfo))); stubFor(get(urlPathEqualTo("/dtmfAction")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupActionRcml))); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(1000); Dialog dialog = bobCall.getDialog(); String infoBody = "Signal=1\r\n" + "Duration=28\r\n"; String infoBody2 = "Signal=2\r\n" + "Duration=28\r\n"; String infoBody3 = "Signal=3\r\n" + "Duration=28\r\n"; Request info = null; Request info2 = null; Request info3 = null; try { info = dialog.createRequest(Request.INFO); info2 = dialog.createRequest(Request.INFO); info3 = dialog.createRequest(Request.INFO); } catch (SipException e) { e.printStackTrace(); } ContentType contentType = new ContentType(); contentType.setContentType("application"); contentType.setContentSubType("dtmf-relay"); info.setContent(infoBody.getBytes(), contentType); info2.setContent(infoBody2.getBytes(), contentType); info3.setContent(infoBody3.getBytes(), contentType); SipTransaction infoTransaction = bobPhone.sendRequestWithTransaction(info, false, dialog); assertNotNull(infoTransaction); Thread.sleep(1000); SipTransaction infoTransaction2 = bobPhone.sendRequestWithTransaction(info2, false, dialog); assertNotNull(infoTransaction2); Thread.sleep(1000); SipTransaction infoTransaction3 = bobPhone.sendRequestWithTransaction(info3, false, dialog); assertNotNull(infoTransaction3); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(15000)); assertTrue(bobCall.respondToDisconnect()); List<LoggedRequest> recordActionRequests = findAll(getRequestedFor(urlPathMatching("/dtmfAction.*"))); assertTrue(recordActionRequests.size()==1); logger.info(recordActionRequests.get(0).toString().contains("Digits=123")); } @Deployment(name = "TestDialVerbPartTwo", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_gather_test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest_new", "data/hsql/restcomm.script"); archive.addAsWebResource("hello-play.xml"); logger.info("Packaged Test App"); return archive; } }
13,918
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialForkAnswerDelayCancelTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialForkAnswerDelayCancelTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.*; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.Arrays; import java.util.List; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.testsuite.http.RestcommCallsTool; /** * Tests for the Dial forking * Created by gvagenas on 12/19/15. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class DialForkAnswerDelayCancelTest { private final static Logger logger = Logger.getLogger(CallLifecycleTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; //Dial Action URL: http://ACae6e420f425248d6a26948c17a9e2acf:[email protected]:8080/restcomm/2012-04-24/DialAction Method: POST @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private String henriqueContact = "sip:[email protected]:5092"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialForkAnswerDelay1"); tool2 = new SipStackTool("DialForkAnswerDelay2"); tool3 = new SipStackTool("DialForkAnswerDelay3"); tool4 = new SipStackTool("DialForkAnswerDelay4"); tool5 = new SipStackTool("DialForkAnswerDelay5"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private String dialFork = "<Response><Dial><Client>alice</Client><Sip>sip:[email protected]:5092</Sip><Number>+131313</Number></Dial></Response>"; @Test public synchronized void testDialForkBobSendsCancel() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); georgeCall.listenForCancel(); aliceCall.listenForCancel(); henriqueCall.listenForCancel(); Thread.sleep(1000); SipTransaction bobCancelTransaction = bobCall.sendCancel(); assertTrue(bobCancelTransaction != null); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(30000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK-2-Cancel-Henrique", 3600); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TERMINATED, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("canceled")); } @Deployment(name = "DialForkAnswerDelayTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-delay.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialForkTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
12,570
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallRegexNullSrcOrgTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/CallRegexNullSrcOrgTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2018, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.DialogState; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Test for Regex for IncomingPhoneNumbers * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class, FeatureExpTests.class}) public class CallRegexNullSrcOrgTest { private final static Logger logger = Logger.getLogger(CallRegexNullSrcOrgTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; // subaccountclient is a simple SIP Client. Will register with Restcomm private SipStack subAccountClientSipStack; private SipPhone subAccountClientPhone; private static String subAccountPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String subAccountClientContact = "sip:[email protected]:" + subAccountPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String subAccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; private String subAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); tool3 = new SipStackTool("DialActionTest3"); tool4 = new SipStackTool("DialActionTest4"); tool5 = new SipStackTool("DialActionTest5"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); subAccountClientSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", subAccountPort, restcommContact); subAccountClientPhone = subAccountClientSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, subAccountClientContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (subAccountClientPhone != null) { subAccountClientPhone.dispose(); } if (subAccountClientSipStack != null) { subAccountClientSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test public void testDialClientAlice7777() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "7777|8888" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:7777@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice8888() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "7777|8888" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:8888@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice7711133() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^*77...33#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*7711133#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice7722233() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^*77...33#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*7722233#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice12233() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^[12]2233#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:12233#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice22233() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^[12]2233#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:22233#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice222_888_999_500() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^\\*222\\*...\\*...\\*500#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*222*888*999*500#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice222_333_444_500() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "^\\*222\\*...\\*...\\*500#$" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*222*333*444*500#@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice42342() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "[45]234[23]" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:42342@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice52343() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "[45]234[23]" stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:52343@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice999111() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "999..." stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:999111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAlice999222() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "999..." stubFor(get(urlPathEqualTo("/regex")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:999222@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regex"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAliceNoRegex() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "999..." stubFor(get(urlPathEqualTo("/1313")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1313@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1313"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } @Test public void testDialClientAliceStar() throws ParseException, InterruptedException, MalformedURLException { //matches regex expression "*" stubFor(get(urlPathEqualTo("/regexAll")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:987654321@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertTrue(liveIncomingCalls == 1); assertTrue(liveOutgoingCalls == 1); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/regexAll"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(metrics); liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: " + liveCalls); liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: " + liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); assertTrue(maxConcurrentCalls == 2); assertTrue(maxConcurrentIncomingCalls == 1); assertTrue(maxConcurrentOutgoingCalls == 1); } static String ussdClientRequestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<ussd-data>\n" + "\t<language value=\"en\"/>\n" + "\t<ussd-string value=\"5544\"/>\n" + "</ussd-data>"; static String ussdRestcommResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ussd-data>\n" + "<language value=\"en\"></language>\n" + "<ussd-string value=\"The information you requested is 1234567890\"></ussd-string>\n" + "<anyExt>\n" + "<message-type>processUnstructuredSSRequest_Response</message-type>\n" + "</anyExt>\n" + "</ussd-data>\n"; private String ussdRcml = "<Response><UssdMessage>The information you requested is 1234567890</UssdMessage></Response>"; @Test public void testUssdPull() { stubFor(get(urlPathEqualTo("/ussd")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(ussdRcml))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:*777#@" + restcommContact, null, ussdClientRequestBody, "application", "vnd.3gpp.ussd+xml", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING); } else { assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(bobCall.getDialog().getState().getValue()== DialogState._CONFIRMED); assertTrue(bobCall.listenForDisconnect()); assertTrue(bobCall.waitForDisconnect(30 * 1000)); bobCall.respondToDisconnect(); SipRequest bye = bobCall.getLastReceivedRequest(); String receivedUssdPayload = new String(bye.getRawContent()); assertTrue(receivedUssdPayload.equalsIgnoreCase(ussdRestcommResponse.trim())); bobCall.dispose(); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); replacements.put("5093", String.valueOf(subAccountPort)); List<String> resources = new ArrayList(Arrays.asList("dial-client-entry_wActionUrl.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm_callRegex.xml", "restcomm.script_callRegexTest",resources, replacements); } }
88,882
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialConferenceTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialConferenceTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.util.Map; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.http.RestcommConferenceParticipantsTool; import org.restcomm.connect.testsuite.http.RestcommConferenceTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * Created by gvagenas on 5/19/16. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={SequentialClassTests.class}) public class DialConferenceTest { private final static Logger logger = Logger.getLogger(DialConferenceTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // Fotini is a simple SIP Client. Will not register with Restcomm private SipStack fotiniSipStack; private SipPhone fotiniPhone; private String fotiniContact = "sip:[email protected]"; private String dialRestcomm = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialConferenceTool1"); tool2 = new SipStackTool("DialConferenceTool2"); tool3 = new SipStackTool("DialConferenceTool3"); tool4 = new SipStackTool("DialConferenceTool4"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); fotiniSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5060", "127.0.0.1:5080"); fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, fotiniContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (fotiniPhone != null) { fotiniPhone.dispose(); } if (fotiniSipStack != null) { fotiniSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(4000); } private int getConferencesSize() { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),adminAccountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); return conferenceArray.size(); } private int getParticipantsSize(final String name) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),adminAccountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); String confSid = null; for(int i = 0; i < conferenceArray.size(); i++) { JsonObject confObj = conferenceArray.get(i).getAsJsonObject(); String confName = confObj.get("friendly_name").getAsString(); if (confName.equalsIgnoreCase(name)) { confSid = confObj.get("sid").getAsString(); break; } } // confSid = conferenceArray.get(conferenceArray.size()-1).getAsJsonObject().get("sid").getAsString(); JsonObject participants = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confSid); JsonArray participantsArray = participants.getAsJsonArray("calls"); return participantsArray.size(); } private final String confRoom1 = "confRoom1"; private String dialConfernceRcmlWithTimeLimit = "<Response><Dial timeLimit=\"50\"><Conference>"+confRoom1+"</Conference></Dial></Response>"; @Test //This is expected to fail because of https://github.com/RestComm/Restcomm-Connect/issues/1081 @Category({FeatureAltTests.class, UnstableTests.class}) public synchronized void testDialConferenceClientsWaitForDisconnect() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcmlWithTimeLimit))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(1000); assertEquals(1, getConferencesSize()); assertEquals(2, getParticipantsSize(confRoom1)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertTrue(mgcpEndpoints>0); assertTrue(mgcpConnections>0); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(georgeCall.waitForDisconnect(50 * 1000)); Thread.sleep(1000); assertEquals(1, getConferencesSize()); assertEquals(0, getParticipantsSize(confRoom1)); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private final String confRoom2 = "confRoom2"; private String dialConfernceRcml = "<Response><Dial><Conference>"+confRoom2+"</Conference></Dial></Response>"; @Test public synchronized void testDialConferenceClientsDisconnect() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); assertTrue(getConferencesSize()>=1); int numOfParticipants = getParticipantsSize(confRoom2); logger.info("Number of participants: "+numOfParticipants); assertTrue(numOfParticipants==2); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertTrue(mgcpEndpoints>0); assertTrue(mgcpConnections>0); Thread.sleep(3000); georgeCall.disconnect(); bobCall.disconnect(); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); assertTrue(getConferencesSize()>=1); int confRoom2Participants = getParticipantsSize(confRoom2); logger.info("&&&&& ConfRoom2Participants: "+confRoom2Participants); assertTrue(confRoom2Participants==0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private final String confRoom3 = "confRoom3"; private String dialConfernceRcml3 = "<Response><Dial><Conference>"+confRoom3+"</Conference></Dial></Response>"; @Test public synchronized void testDialConferenceSingleClient() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml3))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 1); assertTrue(liveCallsArraySize == 1); assertTrue(getConferencesSize()>=1); int numOfParticipants = getParticipantsSize(confRoom3); logger.info("Number of participants: "+numOfParticipants); assertTrue(numOfParticipants==1); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertTrue(mgcpEndpoints>0); assertTrue(mgcpConnections>0); Thread.sleep(3000); bobCall.disconnect(); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); assertTrue(getConferencesSize()>=1); int confRoom2Participants = getParticipantsSize(confRoom3); logger.info("&&&&& ConfRoom2Participants: "+confRoom2Participants); assertTrue(confRoom2Participants==0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private final String confRoom4 = "confRoom4"; private String dialConfernceRcmlWithWaitUrl = "<Response><Dial><Conference startConferenceOnEnter=\"false\" waitUrl=\"http://127.0.0.1:8090/waitUrl\" waitMethod=\"GET\">"+confRoom3+"</Conference></Dial></Response>"; private String waitUrlRcml = "<Response><Say>Wait while somebody joins the conference</Say><Play>/restcomm/audio/demo-prompt.wav</Play></Response>"; @Test @Ignore //TTS is not working on the testsuite @Category(FeatureAltTests.class) public synchronized void testDialConferenceClientsDisconnectWithWaitUrl() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcmlWithWaitUrl))); stubFor(get(urlPathEqualTo("/waitUrl")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(waitUrlRcml))); stubFor(get(urlPathEqualTo("/restcomm/audio/demo-prompt.wav")) .willReturn(aResponse() .withStatus(200) .withBodyFile("demo-prompt.wav"))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); Thread.sleep(4000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(1, liveCalls); assertEquals(1, liveCallsArraySize); assertTrue(getConferencesSize()>=1); int numOfParticipants = getParticipantsSize(confRoom4); logger.info("Number of participants: "+numOfParticipants); assertTrue(numOfParticipants==1); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertTrue(mgcpEndpoints>0); assertTrue(mgcpConnections>0); // final SipCall georgeCall = georgePhone.createSipCall(); // georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); // assertLastOperationSuccess(georgeCall); // assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); // int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); // assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); // // if (responseGeorge == Response.TRYING) { // assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); // assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); // } // // assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); // assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); // georgeCall.sendInviteOkAck(); // assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); // georgeCall.disconnect(); bobCall.disconnect(); Thread.sleep(1000); assertTrue(getConferencesSize()>=1); assertTrue(getParticipantsSize(confRoom4)==0); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private final String confRoom5 = "confRoom5"; private String dialConfernceRcmlWithTimeLimit10Sec = "<Response><Dial timeLimit=\"10\"><Conference>"+confRoom5+"</Conference></Dial></Response>"; @Test public synchronized void testDialConferenceClientsDestroy() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcmlWithTimeLimit10Sec))); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 2); assertTrue(liveCallsArraySize == 2); int confSize = getConferencesSize(); int partSize = getParticipantsSize(confRoom5); logger.info("Conference rooms: "+confSize+", participants: "+partSize); assertTrue(confSize>=1); assertTrue(partSize==2); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertTrue(mgcpEndpoints>0); assertTrue(mgcpConnections>0); Thread.sleep(3000); georgeCall.disposeNoBye(); bobCall.disposeNoBye(); Thread.sleep(10000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); confSize = getConferencesSize(); partSize = getParticipantsSize(confRoom5); logger.info("Conference rooms: "+confSize+", participants: "+partSize); assertTrue(confSize>=1); assertTrue(partSize==0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } String waitUrl = "/restcomm/music/electronica/teru_-_110_Downtempo_Electronic_4.wav"; private final String confRoom6 = "confRoom6"; private String dialConfernceRcmlWithMoh = "<Response><Dial><Conference startConferenceOnEnter=\"false\" waitUrl=\""+waitUrl+"\" >"+confRoom6+"</Conference></Dial></Response>"; @Test public synchronized void testDialConferenceSingleClientWithMoh() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcmlWithMoh))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(3000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 1); assertTrue(liveCallsArraySize == 1); assertTrue(getConferencesSize()>=1); int numOfParticipants = getParticipantsSize(confRoom6); logger.info("Number of participants: "+numOfParticipants); assertTrue(numOfParticipants==1); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertTrue(mgcpEndpoints>0); assertTrue(mgcpConnections>0); Thread.sleep(3000); bobCall.disconnect(); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); assertTrue(getConferencesSize()>=1); int confRoom2Participants = getParticipantsSize(confRoom6); logger.info("&&&&& ConfRoom2Participants: "+confRoom2Participants); assertTrue(confRoom2Participants==0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Deployment(name = "DialConferenceTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest_new", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
38,016
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallMaxDurationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/CallMaxDurationTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import javax.sip.Dialog; import org.cafesip.sipunit.Credential; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Test for Dial Action attribute. Reference: https://www.twilio.com/docs/api/twiml/dial#attributes-action The 'action' * attribute takes a URL as an argument. When the dialed call ends, Restcomm will make a GET or POST request to this URL * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class CallMaxDurationTest { private final static Logger logger = Logger.getLogger(CallMaxDurationTest.class.getName()); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("CallMaxDurationTest1"); tool2 = new SipStackTool("CallMaxDurationTest2"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } @Test @Category(FeatureAltTests.class) public void testClientsCallEachOther() throws ParseException, InterruptedException { SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); SipURI bobUri = bobSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); assertTrue(bobPhone.register(bobUri, "bob", "1234", bobContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "alice", "1234"); alicePhone.addUpdateCredential(c); final SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); Thread.sleep(1000); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.initiateOutgoingCall(aliceContact, bobContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(aliceCall); assertTrue(aliceCall.waitForAuthorisation(3000)); assertTrue(bobCall.waitForIncomingCall(5000)); assertTrue(bobCall.sendIncomingCallResponse(100, "Trying-bob", 1800)); Thread.sleep(1000); assertTrue(bobCall.sendIncomingCallResponse(180, "Ringing-bob", 1800)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); Thread.sleep(5000); assertTrue(bobCall.sendIncomingCallResponse(Response.OK, "OK-bob", 3600, receivedBody, "application", "sdp", null, null)); int responseMaria = -1; do { assertTrue(aliceCall.waitOutgoingCallResponse(5 * 1000)); responseMaria = aliceCall.getLastReceivedResponse().getStatusCode(); } while (responseMaria != Response.OK ); aliceCall.sendInviteOkAck(); assertTrue(bobCall.waitForAck(5000)); bobCall.listenForDisconnect(); aliceCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(80000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(aliceCall.waitForDisconnect(5 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } @Deployment(name = "CallMaxDuration", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); List<String> resources = new ArrayList(); return WebArchiveUtil.createWebArchiveNoGw("org/restcomm/connect/telephony/restcomm_callmaxduration.xml", "org/restcomm/connect/telephony/restcomm_callmaxduration.script",resources, replacements); } }
10,152
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TestDialVerbPartTwoAnswerDelay.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestDialVerbPartTwoAnswerDelay.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import javax.sip.address.SipURI; import javax.sip.header.FromHeader; import javax.sip.message.Request; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import java.util.ArrayList; import java.util.Arrays; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Test for Dial verb. Will test Dial Conference, Dial URI, Dial Client, Dial Number and Dial Fork * * @author <a href="mailto:[email protected]">gvagenas</a> * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, ParallelClassTests.class}) public class TestDialVerbPartTwoAnswerDelay { private final static Logger logger = Logger.getLogger(TestDialVerbPartTwoAnswerDelay.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private String dialClientWithRecordingRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\" action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\"><Client>alice</Client></Dial></Response>"; private String dialConferenceWithDialActionRcml = "<Response><Dial action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\"><Conference>test</Conference></Dial></Response>"; private String dialClientWithRecordingRcml2 = "<Response><Dial timeLimit=\"10\" timeout=\"10\" record=\"true\" action=\"http://127.0.0.1:" + mockPort + "/action&sticky_numToDial=00306986971731\" method=\"GET\"><Client>alice</Client></Dial></Response>"; private String dialRecordWithActionRcml = "<Response><Record action=\"http://127.0.0.1:" + mockPort + "/recordAction\" method=\"GET\" finishOnKey=\"*\" maxLength=\"10\" playBeep=\"true\"/></Response>"; private String dialClientWithActionRcml = "<Response><Dial action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\"><Client>alice</Client></Dial></Response>"; private String dialTimeOutClientWithActionRcml = "<Response><Dial timeout=\"3\" action=\"http://127.0.0.1:" + mockPort + "/action\" method=\"GET\"><Client>alice</Client></Dial></Response>"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + georgePort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialRestcomm = "sip:1111@" + restcommContact; private static String dialRestcommWithStatusCallback = "sip:7777@" + restcommContact; private static String dialNumberNoCallerId = "<Response><Dial><Number url=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; private static String dialNumberRcml = "<Response><Dial callerId=\"+13055872294\"><Number url=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialTest2Tool1"); tool2 = new SipStackTool("DialTest2Tool2"); tool3 = new SipStackTool("DialTest2Tool3"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialRestcomm = "sip:1111@" + restcommContact; dialRestcommWithStatusCallback = "sip:7777@" + restcommContact; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); dialNumberNoCallerId = "<Response><Dial><Number url=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; dialNumberRcml = "<Response><Dial callerId=\"+13055872294\"><Number url=\"http://127.0.0.1:" + restcommHTTPPort + "/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; //Test for issue RESTCOMM-617 @Test @Category(UnstableTests.class) public synchronized void testDialClientAliceToBigDID() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } private String sendSmsActionRcml = "<Response>\n" + "\t\t\t<Sms to=\"bob\" from=\"+12223334499\">Hello World!</Sms>\n" + "</Response>"; @Test @Category(UnstableTests.class) public synchronized void testDialClientAliceWithRecord() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithRecordingRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(0)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); } @Test @Category(UnstableTests.class) public synchronized void testDialClientAliceWithRecord2() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithRecordingRcml2))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(10000); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(0)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); } @Test //Test case for issue 320 @Category(UnstableTests.class) public synchronized void testDialClientAliceWithRecordAndStatusCallbackForApp() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithRecordingRcml))); stubFor(get(urlPathEqualTo("/action")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sendSmsActionRcml))); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcommWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(0)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); logger.info("About to check the Status Callback Requests"); Map<String, String> statusCallbacks = new HashMap<String,String>(); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); assertTrue(requests.size()==3); // for (LoggedRequest loggedRequest : requests) { // String queryParam = loggedRequest.getUrl().replaceFirst("/StatusCallBack?", ""); // String[] params = queryParam.split("&"); // String callSid = params[0].split("=")[1]; // String callStatus = params[4].split("=")[1]; // if (statusCallbacks.containsKey(callSid)) { // statusCallbacks.remove(callSid); // } // statusCallbacks.put(callSid, callStatus); // } // assertTrue(statusCallbacks.size()==1); // Iterator<String> iter = statusCallbacks.keySet().iterator(); // while (iter.hasNext()) { // String key = iter.next(); // assertTrue(statusCallbacks.get(key).equalsIgnoreCase("completed")); // } } @Test @Category(UnstableTests.class) public synchronized void testDialNumberGeorge() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); final SipRequest lastRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // the number dialed uses a callerId of "+13055872294", which is what George should receive String contactHeader = georgeCall.getLastReceivedRequest().getMessage().getHeader("Contact").toString().replaceAll("\r\n",""); assertTrue(contactHeader.equalsIgnoreCase("Contact: \"+13055872294\" <sip:+13055872294@" + restcommContact + ">")); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(!bobCall.callTimeoutOrError()); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); assertTrue(georgeCall.respondToDisconnect()); } //Non-regression test for https://github.com/Mobicents/RestComm/issues/505 @Test @Category(UnstableTests.class) public synchronized void testDialNumberGeorge_403Forbidden() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); // SipURI uri = bobSipStack.getAddressFactory().createSipURI(null, restcommContact); // assertTrue(bobPhone.register(uri, "bob", "1234", bobContact, 3600, 3600)); // // Credential c = new Credential("127.0.0.1", "bob", "1234"); // bobPhone.addUpdateCredential(c); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.FORBIDDEN, "FORBIDDEN-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode()); } //Non-regression test for https://github.com/Mobicents/RestComm/issues/505 @Test @Category(UnstableTests.class) public synchronized void testDialNumberGeorge_404_OnBye() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberRcml))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); bobCall.disconnect(); georgeCall.listenForDisconnect(); georgeCall.waitForDisconnect(5000); georgeCall.respondToDisconnect(404, "Not Here"); georgeCall.disposeNoBye(); } //Test for Issue 210: https://telestax.atlassian.net/browse/RESTCOMM-210 //Bob callerId should pass to the call created by Dial Number @Test @Category(UnstableTests.class) public synchronized void testDialNumberGeorgePassInitialCallerId() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberNoCallerId))); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); SipRequest georgeInvite = georgeCall.getLastReceivedRequest(); assertTrue(((FromHeader)georgeInvite.getMessage().getHeader("From")).getAddress().getDisplayName().contains("bob")); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); assertTrue(georgeCall.respondToDisconnect()); } private String dialClientRcml_SendSMSToBob = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial>" + "<Sms to=\"bob\" from=\"+12223334499\">Hello World!</Sms></Response>"; //Test for issue RESTCOMM-617 @Test public synchronized void testDialClientAliceSendSmsToBob() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml_SendSMSToBob))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); bobCall.listenForMessage(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); } @Deployment(name = "TestDialVerbPartTwo", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); List<String> resources = new ArrayList(Arrays.asList("hello-play.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm-delay.xml", "restcomm.script_dialTest_new",resources, replacements); } }
37,992
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialForkPlayDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialForkPlayDelayTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; /** * Tests for the Dial Forking timeout, this test class is being tested with 2 seconds audio file, that can make RC in * PLAYING state for 2 seconds. * Created by xhoaluu on 03/29/18. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(SequentialClassTests.class) public class DialForkPlayDelayTest { private final static Logger logger = Logger.getLogger(CallLifecycleTest.class.getName()); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; // Fotini is a simple SIP Client. Will not register with Restcomm private SipStack fotiniSipStack; private SipPhone fotiniPhone; private static String fotiniPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String fotiniContact = "sip:[email protected]:" + fotiniPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private String dialTimeoutRcmlWithPlay; private String rcmlPlayAndDialReturn; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialFork1"); tool2 = new SipStackTool("DialFork2"); tool3 = new SipStackTool("DialFork3"); tool4 = new SipStackTool("DialFork4"); tool5 = new SipStackTool("DialFork5"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { dialTimeoutRcmlWithPlay = "<Response><Dial timeout=\"1\" action=\"http://127.0.0.1:" + mockPort+ "/test\"><Client>alice</Client></Dial></Response>"; rcmlPlayAndDialReturn = "<Response><Play>" + deploymentUrl.toString() + "/audio/demo-prompt.wav</Play><Dial><Client>bob</Client></Dial></Response>"; bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); fotiniSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", fotiniPort, restcommContact); fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, fotiniContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (fotiniPhone != null) { fotiniPhone.dispose(); } if (fotiniSipStack != null) { fotiniSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(5000); } @Test @Category(FeatureAltTests.class) public void testDialTimeoutWithPlay() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialTimeoutRcmlWithPlay))); stubFor(post(urlEqualTo("/test")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlPlayAndDialReturn))); SipURI Alice_uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(Alice_uri, "alice", "1234", aliceContact, 3600, 3600)); SipURI Bob_uri = bobSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(bobPhone.register(Bob_uri, "bob", "1234", bobContact, 3600, 3600)); // Prepare Alice's phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.initiateOutgoingCall(henriqueContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(henriqueCall); assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); final int response = henriqueCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, henriqueCall.getLastReceivedResponse().getStatusCode()); } assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, henriqueCall.getLastReceivedResponse().getStatusCode()); assertTrue(henriqueCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.TEMPORARILY_UNAVAILABLE, "Alice-TemporaryUnavailable", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); // Prepare Bob's phone to receive call SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); assertTrue(bobCall.waitForIncomingCall(5000)); assertTrue(bobCall.sendIncomingCallResponse(Response.TRYING, "Bob-Trying", 3600)); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Bob-Ringing", 3600)); assertTrue(bobCall.sendIncomingCallResponse(Response.OK, "Bob-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitForAck(5000)); Thread.sleep(2000); henriqueCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(henriqueCall.waitForDisconnect(5000)); assertTrue(henriqueCall.respondToDisconnect()); assertTrue(alicePhone.unregister(aliceContact, 3600)); assertTrue(bobPhone.unregister(aliceContact, 3600)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureAltTests.class) public void testDialBusyTimeoutWithPlay() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialTimeoutRcmlWithPlay))); stubFor(post(urlEqualTo("/test")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlPlayAndDialReturn))); SipURI Alice_uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(Alice_uri, "alice", "1234", aliceContact, 3600, 3600)); SipURI Bob_uri = bobSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(bobPhone.register(Bob_uri, "bob", "1234", bobContact, 3600, 3600)); // Prepare Alice's phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.initiateOutgoingCall(henriqueContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(henriqueCall); assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); final int response = henriqueCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, henriqueCall.getLastReceivedResponse().getStatusCode()); } assertTrue(henriqueCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, henriqueCall.getLastReceivedResponse().getStatusCode()); assertTrue(henriqueCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.BUSY_HERE, "Alice-BUSY-HERE", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); // Prepare Bob's phone to receive call SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); assertTrue(bobCall.waitForIncomingCall(5000)); assertTrue(bobCall.sendIncomingCallResponse(Response.TRYING, "Bob-Trying", 3600)); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Bob-Ringing", 3600)); assertTrue(bobCall.sendIncomingCallResponse(Response.OK, "Bob-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitForAck(5000)); Thread.sleep(2000); henriqueCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); Thread.sleep(500); assertTrue(henriqueCall.waitForDisconnect(5000)); assertTrue(henriqueCall.respondToDisconnect()); assertTrue(alicePhone.unregister(aliceContact, 3600)); assertTrue(bobPhone.unregister(aliceContact, 3600)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Deployment(name = "DialForkTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); replacements.put("5093", String.valueOf(fotiniPort)); List<String> resources = new ArrayList(Arrays.asList("hello-play.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm_dialForkPlayDelayTest.xml", "restcomm.script_dialForkPlayDelayTest",resources, replacements); } }
21,254
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TestDialVerbPartOne.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestDialVerbPartOne.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipResponse; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import java.util.HashMap; import java.util.Map; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Test for Dial verb. Will test Dial Conference, Dial URI, Dial Client, Dial Number and Dial Fork * * @author <a href="mailto:[email protected]">gvagenas</a> * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(ParallelClassTests.class) public class TestDialVerbPartOne { private final static Logger logger = Logger.getLogger(TestDialVerbPartOne.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); private static final String sdpForHold = "v=0\n" + "o=bob-jitsi.org 0 2 IN IP4 192.168.1.190\n" + "s=-\n" + "c=IN IP4 192.168.1.190\n" + "t=0 0\n" + "m=audio 5000 RTP/AVP 0 8 3 101\n" + "a=rtpmap:0 PCMU/8000\n" + "a=rtpmap:8 PCMA/8000\n" + "a=rtpmap:3 GSM/8000\n" + "a=rtpmap:101 telephone-event/8000\n" + "a=extmap:1 urn:ietf:params:rtp-hdrext:csrc-audio-level\n" + "a=extmap:2 urn:ietf:params:rtp-hdrext:ssrc-audio-level\n" + "a=rtcp-xr:voip-metrics\n" + "m=video 5004 RTP/AVP 96 99\n" + "a=recvonly\n" + "a=rtpmap:96 H264/90000\n" + "a=fmtp:96 profile-level-id=4DE01f;packetization-mode=1\n" + "a=imageattr:96 send * recv [x=[0-1440],y=[0-900]]\n" + "a=rtpmap:99 H264/90000\n" + "a=fmtp:99 profile-level-id=4DE01f\n" + "a=imageattr:99 send * recv [x=[0-1440],y=[0-900]]\n"; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private String dialClientRcmlWithScreeningRelative = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client url=\"http://127.0.0.1:" + mockPort + "/screening\" method=\"GET\">alice</Client></Dial></Response>"; private String dialClientRcmlWithScreening = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client url=\"http://127.0.0.1:" + mockPort + "/screening\" method=\"GET\">alice</Client></Dial></Response>"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; // Fotini is a simple SIP Client. Will not register with Restcomm private SipStack fotiniSipStack; private SipPhone fotiniPhone; private static String fotiniPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String fotiniContact = "sip:[email protected]:" + fotiniPort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialRestcomm = "sip:1111@" + restcommContact; private static String notFoundDialNumber = "sip:+12223334457@" + restcommContact; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialTest1Tool1"); tool2 = new SipStackTool("DialTest1Tool2"); tool3 = new SipStackTool("DialTest1Tool3"); tool4 = new SipStackTool("DialTest1Tool4"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialRestcomm = "sip:1111@" + restcommContact; notFoundDialNumber = "sip:+12223334457@" + restcommContact; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); fotiniSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", fotiniPort, restcommContact); fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, fotiniContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (fotiniPhone != null) { fotiniPhone.dispose(); } if (fotiniSipStack != null) { fotiniSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } private String dialConfernceRcml = "<Response><Dial timeLimit=\"50\"><Conference>test</Conference></Dial></Response>"; @Test public synchronized void testDialConference() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // George calls to the conference final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); // Start a new thread for george to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForDisconnect(30 * 1000)); } }).start(); // Start a new thread for bob to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(bobCall.waitForDisconnect(30 * 1000)); } }).start(); } private String dialConfernceRcmlWithTimeLimit = "<Response><Dial timeLimit=\"50\"><Conference>test</Conference></Dial></Response>"; @Test public synchronized void testDialConferenceOnlyOneClientWithTimeLimit() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcmlWithTimeLimit))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(60 * 1000)); } private String dialConfernceRcmlWithTimeLimitSmsAfterConf = "<Response><Dial timeLimit=\"50\"><Conference>test</Conference></Dial><Sms>Conference time limit reached</Sms></Response>"; @Test @Category(FeatureAltTests.class) public synchronized void testDialConferenceOnlyOneClientWithTimeLimitSmsAfterConf() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcmlWithTimeLimitSmsAfterConf))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(60 * 1000)); bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60000)); assertTrue(bobCall.sendMessageResponse(Response.ACCEPTED,"BobCall Msg Accepted", 3600)); String messageReceived = new String(bobCall.getLastReceivedMessageRequest().getRawContent()); assertEquals("Conference time limit reached", messageReceived); } private String dialConfernceRcmlWithoutTimeLimit = "<Response><Dial><Conference>test</Conference></Dial></Response>"; @Test @Category(FeatureAltTests.class) public synchronized void testDialConferenceOnlyOneClientWithoutTimeLimit() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcmlWithoutTimeLimit))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(1000); bobCall.disconnect(); Thread.sleep(10000); } @Test public synchronized void testDialConferenceConcurrentCalls() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); final SipCall bobCall = bobPhone.createSipCall(); final SipCall georgeCall = georgePhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); georgeCall.sendInviteOkAck(); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); Thread.sleep(5000); // Start a new thread for george to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForDisconnect(30 * 1000)); } }).start(); // Start a new thread for bob to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(bobCall.waitForDisconnect(30 * 1000)); } }).start(); } private String dialConfernceRcmlWithPlay = "<Response><Play>/restcomm/audio/demo-prompt.wav</Play><Dial timeLimit=\"50\"><Conference>test</Conference></Dial></Response>"; @Test @Category(FeatureAltTests.class) public synchronized void testDialConferenceWithPlay() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // George calls to the conference final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); // Start a new thread for george to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForDisconnect(30 * 1000)); } }).start(); // Start a new thread for bob to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(bobCall.waitForDisconnect(30 * 1000)); } }).start(); } @Test @Category(FeatureAltTests.class) public synchronized void testDialConferenceWithPlayInDialogInviteHold() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // George calls to the conference final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); //sendReinvite(String newContact, String displayName, String body, String contentType, String contentSubType) SipTransaction reInviteTrans = bobCall.sendReinvite(bobContact, "Hold", sdpForHold, "application", "sdp"); assertTrue(bobCall.waitReinviteResponse(reInviteTrans, 5000)); bobCall.sendReinviteOkAck(reInviteTrans); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); // Start a new thread for george to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForDisconnect(30 * 1000)); } }).start(); // Start a new thread for bob to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(bobCall.waitForDisconnect(30 * 1000)); } }).start(); } @Test @Category(FeatureAltTests.class) public synchronized void testDialConferenceWithContactHeaderPortNull() throws InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.initiateOutgoingCall(fotiniContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(fotiniCall); assertTrue(fotiniCall.waitOutgoingCallResponse(5 * 1000)); int responseFotini = fotiniCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseFotini == Response.TRYING || responseFotini == Response.RINGING); if (responseFotini == Response.TRYING) { assertTrue(fotiniCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, fotiniCall.getLastReceivedResponse().getStatusCode()); } assertTrue(fotiniCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, fotiniCall.getLastReceivedResponse().getStatusCode()); fotiniCall.sendInviteOkAck(); assertTrue(!(fotiniCall.getLastReceivedResponse().getStatusCode() >= 400)); // George calls to the conference final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. fotiniCall.listenForDisconnect(); georgeCall.listenForDisconnect(); // Start a new thread for george to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForDisconnect(30 * 1000)); } }).start(); // Start a new thread for bob to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(fotiniCall.waitForDisconnect(30 * 1000)); } }).start(); } @Test // Non regression test for // https://bitbucket.org/telestax/telscale-restcomm/issue/113/when-restcomm-cannot-find-an-app-url-it @Category(FeatureExpTests.class) public synchronized void testDialApplicationInvalidURL() throws InterruptedException, ParseException { // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, notFoundDialNumber, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } // wait for 404 Not Found assertTrue(bobCall.waitOutgoingCallResponse(10000)); SipResponse lastResponse = bobCall.getLastReceivedResponse(); assertEquals(500, lastResponse.getStatusCode()); } private String dialUriRcml = "<Response><Dial timeLimit=\"100000\" timeout=\"1000000\"><Uri>sip:[email protected]:" + alicePort + "</Uri></Dial><Hangup/></Response>"; @Test public synchronized void testDialUriAliceHangup() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialUriRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); String inboundCallSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); String outboundCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); JsonObject inboundCallCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, inboundCallSid); JsonObject outboundCallCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, outboundCallSid); assertNotNull(inboundCallCdr); assertNotNull(outboundCallCdr); int inboundCdrDuration = inboundCallCdr.get("duration").getAsInt(); int outboundCdrDuration = outboundCallCdr.get("duration").getAsInt(); int outboundCdrRinging = outboundCallCdr.get("ring_duration").getAsInt(); assertTrue(inboundCdrDuration==3); assertTrue(outboundCdrDuration==3); assertTrue(outboundCdrRinging==0); } @Test public synchronized void testDialUriBobHangup() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialUriRcml))); int initialCdrSize = 0; //Check CDR JsonObject cdrs = RestcommCallsTool.getInstance().getCalls("http://127.0.0.1:" +restcommHTTPPort + "/restcomm", adminAccountSid, adminAuthToken); if (cdrs != null) { initialCdrSize = cdrs.get("calls").getAsJsonArray().size(); } // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); //Ringing time 5 sec Thread.sleep(5000); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(3000); //Check CDR cdrs = RestcommCallsTool.getInstance().getCalls("http://127.0.0.1:" + restcommHTTPPort + "/restcomm", adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); System.out.println("cdrsArray.size(): " + cdrsArray.size()); assertTrue((cdrsArray.size() - initialCdrSize) == 2); } @Test @Category(FeatureAltTests.class) public synchronized void testDialUriBobHangupCheckCDRs() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialUriRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); // X-RestComm-CallSid: CA5c2a775f2ca24003a04b7f7b90e6fabb String inboundCallSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); //X-RestComm-CallSid: CAedaccc8f598b4093b1fc33431e1c9ac9 String outboundCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); //Ringing time 5 sec Thread.sleep(5000); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); aliceCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(6000); //Check CDR JsonObject inboundCallCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, inboundCallSid); JsonObject outboundCallCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, outboundCallSid); assertNotNull(inboundCallCdr); assertNotNull(outboundCallCdr); int inboundCdrDuration = inboundCallCdr.get("duration").getAsInt(); int outboundCdrDuration = outboundCallCdr.get("duration").getAsInt(); int outboundCdrRinging = outboundCallCdr.get("ring_duration").getAsInt(); assertTrue(inboundCdrDuration==8); assertTrue(outboundCdrDuration==3); assertTrue(outboundCdrRinging==5); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } @Test @Category(FeatureExpTests.class) public synchronized void testDialClientAliceNoSDP() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.BAD_REQUEST); } @Test @Category(FeatureExpTests.class) public synchronized void testDialClientAliceNullSDP() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, null, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.BAD_REQUEST); } final String screeningResponse = "<Response></Response>"; @Test @Category(FeatureAltTests.class) public synchronized void testDialClientAliceWithScreeningAbsoluteURL() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/screening")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(screeningResponse))); stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcmlWithScreening))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } private String screeningRcml = "<Response><Say>Hi bob. Someone wants to talk to you</Say></Response>"; @Test @Category(FeatureAltTests.class) public synchronized void testDialClientAliceWithScreeningRelativeURL() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcmlWithScreeningRelative))); stubFor(get(urlPathEqualTo("/screening")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(screeningRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } @Deployment(name = "TestDialVerbPartOne", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm.xml", "restcomm.script_dialTest_new", replacements); } }
53,726
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SequentialDialingAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/SequentialDialingAnswerDelayTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; /** * Created by gvagenas on 22/02/2017. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, SequentialClassTests.class}) public class SequentialDialingAnswerDelayTest { private final static Logger logger = Logger.getLogger(SequentialDialingAnswerDelayTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; private SipStack carolSipStack; private SipPhone carolPhone; private String carolContact = "sip:[email protected]:5092"; private SipStack daveSipStack; private SipPhone davePhone; private String daveContact = "sip:[email protected]:5093"; private String dialRestcomm = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("SequentialDialingTool1"); tool2 = new SipStackTool("SequentialDialingTool12"); tool3 = new SipStackTool("SequentialDialingTool13"); tool4 = new SipStackTool("SequentialDialingTool14"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); carolSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); carolPhone = carolSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, carolContact); daveSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5093", "127.0.0.1:5080"); davePhone = daveSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, daveContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (carolSipStack != null) { carolSipStack.dispose(); } if (carolPhone != null) { carolPhone.dispose(); } if (daveSipStack != null) { daveSipStack.dispose(); } if (davePhone != null) { davePhone.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } private String sequentialDialingRcml = "<Response><Dial timeout=\"3\"><Uri>"+aliceContact+"</Uri></Dial><Dial timeout=\"3\"><Uri>" + carolContact + "</Uri></Dial><Dial timeout=\"3\"><Uri>" + daveContact + "</Uri></Dial></Response>"; @Test public void testSequentialDialingWithAnswerDelay() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sequentialDialingRcml))); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); final SipCall carolCall = carolPhone.createSipCall(); carolCall.listenForIncomingCall(); final SipCall daveCall = davePhone.createSipCall(); daveCall.listenForIncomingCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } bobCall.listenForCancel(); // assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); // assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); // bobCall.sendInviteOkAck(); // assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); aliceCall.listenForCancel(); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(5000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(carolCall.waitForIncomingCall(5000)); assertTrue(carolCall.sendIncomingCallResponse(100, "Trying-Carol", 600)); assertTrue(carolCall.sendIncomingCallResponse(180, "Ringing-Carol", 600)); carolCall.listenForCancel(); SipTransaction carolCancelTransaction = carolCall.waitForCancel(5000); assertNotNull(carolCancelTransaction); carolCall.respondToCancel(carolCancelTransaction, 200, "OK-2-Cancel-Carol", 3600); assertTrue(daveCall.waitForIncomingCall(5000)); assertTrue(daveCall.sendIncomingCallResponse(100, "Trying-Dave", 600)); assertTrue(daveCall.sendIncomingCallResponse(180, "Ringing-Dave", 600)); daveCall.listenForCancel(); SipTransaction daveCancelTransaction = daveCall.waitForCancel(5000); assertNotNull(daveCancelTransaction); daveCall.respondToCancel(daveCancelTransaction, 200, "OK-2-Cancel-Dave", 3600); } private String sequentialDialingRcml1 = "<Response><Dial action=\"http://127.0.0.1:8090/action1\" timeout=\"3\"><Uri>" + aliceContact + "</Uri></Dial></Response>"; private String action1 = "<Response><Dial action=\"http://127.0.0.1:8090/action2\" timeout=\"3\"><Uri>" + carolContact + "</Uri></Dial></Response>"; private String action2 = "<Response><Dial timeout=\"3\"><Uri>" + daveContact + "</Uri></Dial></Response>"; @Test public void testSequentialDialingWithDialAction() throws ParseException, InterruptedException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sequentialDialingRcml1))); stubFor(post(urlPathEqualTo("/action1")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(action1))); stubFor(post(urlPathEqualTo("/action2")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(action2))); final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); final SipCall carolCall = carolPhone.createSipCall(); carolCall.listenForIncomingCall(); final SipCall daveCall = davePhone.createSipCall(); daveCall.listenForIncomingCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } // assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); // assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); // bobCall.sendInviteOkAck(); // assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); aliceCall.listenForCancel(); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(5000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(carolCall.waitForIncomingCall(5000)); assertTrue(carolCall.sendIncomingCallResponse(100, "Trying-Carol", 600)); assertTrue(carolCall.sendIncomingCallResponse(180, "Ringing-Carol", 600)); carolCall.listenForCancel(); SipTransaction carolCancelTransaction = carolCall.waitForCancel(5000); assertNotNull(carolCancelTransaction); carolCall.respondToCancel(carolCancelTransaction, 200, "OK-2-Cancel-Carol", 3600); assertTrue(daveCall.waitForIncomingCall(5000)); assertTrue(daveCall.sendIncomingCallResponse(100, "Trying-Dave", 600)); assertTrue(daveCall.sendIncomingCallResponse(180, "Ringing-Dave", 600)); daveCall.listenForCancel(); SipTransaction daveCancelTransaction = daveCall.waitForCancel(5000); assertNotNull(daveCancelTransaction); daveCall.respondToCancel(daveCancelTransaction, 200, "OK-2-Cancel-Dave", 3600); } @Deployment(name = "SequentialDialingTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-delay.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest_new", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
13,212
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientsDialTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ClientsDialTest.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import gov.nist.javax.sip.address.SipUri; import gov.nist.javax.sip.header.HeaderExt; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.CreateClientsTool; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.Dialog; import javax.sip.InvalidArgumentException; import javax.sip.SipException; import javax.sip.address.SipURI; import javax.sip.header.UserAgentHeader; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Test for clients with or without VoiceURL (Bitbucket issue 115). Clients without VoiceURL can dial anything. * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={ParallelClassTests.class}) public class ClientsDialTest { private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); private static final String webRtcBody = "v=0\n" + "o=- 655836341935372758 2 IN IP4 24.217.142.20\n" + "s=Restcomm B2BUA\n" + "t=0 0\n" + "a=group:BUNDLE audio video\n" + "a=msid-semantic:WMS ARDAMS\n" + "m=audio 9 UDP/TLS/RTP/SAVPF 111 103 9 102 0 8 106 105 13 126\n" + "c=IN IP4 24.217.142.20\n" + "a=rtcp:9 IN IP4 0.0.0.0\n" + "a=candidate:704553097 1 udp 2122260223 192.168.1.3 60475 typ host generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:2158047068 1 udp 1686052607 24.217.142.20 60475 typ srflx raddr 192.168.1.3 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41885695 50.97.253.79 55954 typ relay raddr 24.217.142.20 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41886207 50.97.253.79 49214 typ relay raddr 24.217.142.20 rport 60475 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108735 50.97.253.79 63824 typ relay raddr 24.217.142.20 rport 54517 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108223 50.97.253.79 50246 typ relay raddr 24.217.142.20 rport 33927 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=ice-ufrag:PFs2\n" + "a=ice-pwd:MZHsJBkJ+vdWaNvb4Z7iCejt\n" + "a=fingerprint:sha-256 56:B1:98:06:06:EA:B1:BB:31:51:28:35:C7:8C:45:11:CD:3A:0D:28:C1:10:5B:D5:99:EA:21:46:8E:ED:08:89\n" + "a=setup:actpass\n" + "a=mid:audio\n" + "a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\n" + "a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n" + "a=sendrecv\n" + "a=rtcp-mux\n" + "a=rtpmap:111 opus/48000/2\n" + "a=rtcp-fb:111 transport-cc\n" + "a=fmtp:111 minptime=10;useinbandfec=1\n" + "a=rtpmap:103 ISAC/16000\n" + "a=rtpmap:9 G722/8000\n" + "a=rtpmap:102 ILBC/8000\n" + "a=rtpmap:0 PCMU/8000\n" + "a=rtpmap:8 PCMA/8000\n" + "a=rtpmap:106 CN/32000\n" + "a=rtpmap:105 CN/16000\n" + "a=rtpmap:13 CN/8000\n" + "a=rtpmap:126 telephone-event/8000\n" + "a=ssrc:743432057 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:743432057 msid:ARDAMS ARDAMSa0\n" + "a=ssrc:743432057 mslabel:ARDAMS\n" + "a=ssrc:743432057 label:ARDAMSa0\n" + "m=video 9 UDP/TLS/RTP/SAVPF 100 101 116 117 121 96 97 98 99\n" + "c=IN IP4 24.217.142.20\n" + "a=rtcp:9 IN IP4 0.0.0.0\n" + "a=candidate:704553097 1 udp 2122260223 192.168.1.3 40839 typ host generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:2158047068 1 udp 1686052607 24.217.142.20 40839 typ srflx raddr 192.168.1.3 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41886207 50.97.253.79 53691 typ relay raddr 24.217.142.20 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:152961445 1 udp 41885695 50.97.253.79 63503 typ relay raddr 24.217.142.20 rport 40839 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108735 50.97.253.79 56359 typ relay raddr 24.217.142.20 rport 33643 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=candidate:1201536341 1 udp 25108223 50.97.253.79 54107 typ relay raddr 24.217.142.20 rport 44827 generation 0 ufrag PFs2 network-id 3 network-cost 10\n" + "a=ice-ufrag:PFs2\n" + "a=ice-pwd:MZHsJBkJ+vdWaNvb4Z7iCejt\n" + "a=fingerprint:sha-256 56:B1:98:06:06:EA:B1:BB:31:51:28:35:C7:8C:45:11:CD:3A:0D:28:C1:10:5B:D5:99:EA:21:46:8E:ED:08:89\n" + "a=setup:actpass\n" + "a=mid:video\n" + "a=extmap:2 urn:ietf:params:rtp-hdrext:toffset\n" + "a=extmap:3 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n" + "a=extmap:4 urn:3gpp:video-orientation\n" + "a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay\n" + "a=sendrecv\n" + "a=rtcp-mux\n" + "a=rtcp-rsize\n" + "a=rtpmap:100 VP8/90000\n" + "a=rtcp-fb:100 ccm fir\n" + "a=rtcp-fb:100 nack\n" + "a=rtcp-fb:100 nack pli\n" + "a=rtcp-fb:100 goog-remb\n" + "a=rtcp-fb:100 transport-cc\n" + "a=rtpmap:101 VP9/90000\n" + "a=rtcp-fb:101 ccm fir\n" + "a=rtcp-fb:101 nack\n" + "a=rtcp-fb:101 nack pli\n" + "a=rtcp-fb:101 goog-remb\n" + "a=rtcp-fb:101 transport-cc\n" + "a=rtpmap:116 red/90000\n" + "a=rtpmap:117 ulpfec/90000\n" + "a=rtpmap:121 H264/90000\n" + "a=rtcp-fb:121 ccm fir\n" + "a=rtcp-fb:121 nack\n" + "a=rtcp-fb:121 nack pli\n" + "a=rtcp-fb:121 goog-remb\n" + "a=rtcp-fb:121 transport-cc\n" + "a=rtpmap:96 rtx/90000\n" + "a=fmtp:96 apt=100\n" + "a=rtpmap:97 rtx/90000\n" + "a=fmtp:97 apt=101\n" + "a=rtpmap:98 rtx/90000\n" + "a=fmtp:98 apt=116\n" + "a=rtpmap:99 rtx/90000\n" + "a=fmtp:99 apt=121\n" + "a=ssrc-group:FID 2457543170 3154322644\n" + "a=ssrc:2457543170 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:2457543170 msid:ARDAMS ARDAMSv0\n" + "a=ssrc:2457543170 mslabel:ARDAMS\n" + "a=ssrc:2457543170 label:ARDAMSv0\n" + "a=ssrc:3154322644 cname:USPxCkO2V7yoEmg/\n" + "a=ssrc:3154322644 msid:ARDAMS ARDAMSv0\n" + "a=ssrc:3154322644 mslabel:ARDAMS\n" + "a=ssrc:3154322644 label:ARDAMSv0"; @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; private static SipStackTool tool6; private static SipStackTool tool7; private static SipStackTool tool8; private static SipStackTool tool9; private static SipStackTool tool10; private static SipStackTool tool11; private static SipStackTool tool12; private String pstnNumber = "+151261006100"; private String clientPassword = "qwerty1234RT"; // Maria is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack mariaSipStack; private SipPhone mariaPhone; private static String mariaPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String mariaContact = "sip:[email protected]:" + mariaPort; private String mariaRestcommClientSid; // Dimitris is a Restcomm Client **without** VoiceURL. This Restcomm Client can dial anything. private SipStack dimitriSipStack; private SipPhone dimitriPhone; private static String dimitriPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String dimitriContact = "sip:[email protected]:" + dimitriPort; private String dimitriRestcommClientSid; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; private SipStack aliceSipStack2; private SipPhone alicePhone2; private static String alicePort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact2 = "sip:[email protected]:" + alicePort2; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:"+pstnNumber+"@127.0.0.1:" + georgePort; private SipStack clientWithAppSipStack; private SipPhone clientWithAppPhone; private static String clientWithAppPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String clientWithAppContact = "sip:[email protected]:" + clientWithAppPort; private String clientWithAppClientSid; private SipStack fotiniSipStackTcp; private SipPhone fotiniPhoneTcp; private static String fotiniPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String fotiniContactTcp = "sip:[email protected]:" + fotiniPort; private String fotiniClientSid; private SipStack bobSipStackTcp; private SipPhone bobPhoneTcp; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContactTcp = "sip:[email protected]:" + bobPort; private SipStack leftySipStack; private SipPhone leftyPhone; private static String leftyPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String leftyContact = "sip:[email protected]:" + leftyPort; private String leftyRestcommClientSid; private SipStack externalSipStack; private SipPhone externalPhone; private static String externalPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String externalContact = "sip:[email protected]:" + externalPort; private SipStack closedSipStack; private SipPhone closedPhone; private static String closedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String closedContact = "sip:[email protected]:" + closedPort; private SipStack suspendedSipStack; private SipPhone suspendedPhone; private static String suspendedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String suspendedContact = "sip:[email protected]:" + suspendedPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("ClientsDialTest1"); tool2 = new SipStackTool("ClientsDialTest2"); tool3 = new SipStackTool("ClientsDialTest3"); tool4 = new SipStackTool("ClientsDialTest4"); tool5 = new SipStackTool("ClientsDialTest5"); tool6 = new SipStackTool("ClientsDialTest6"); tool7 = new SipStackTool("ClientsDialTest7"); tool8 = new SipStackTool("ClientsDialTest8"); tool9 = new SipStackTool("ClientsDialTest9"); tool10 = new SipStackTool("ClientsDialTest10"); tool11 = new SipStackTool("ClientsDialTest11"); tool12 = new SipStackTool("ClientsDialTest12"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { aliceSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); aliceSipStack2 = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort2, restcommContact); alicePhone2 = aliceSipStack2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact2); mariaSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", mariaPort, restcommContact); mariaPhone = mariaSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, mariaContact); dimitriSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", dimitriPort, restcommContact); dimitriPhone = dimitriSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, dimitriContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); clientWithAppSipStack = tool6.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", clientWithAppPort, restcommContact); clientWithAppPhone = clientWithAppSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, clientWithAppContact); mariaRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "maria", clientPassword, null); dimitriRestcommClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "dimitri", clientPassword, null); clientWithAppClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "clientWithApp", clientPassword, "http://127.0.0.1:" + mockPort + "/1111"); fotiniSipStackTcp = tool7.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", fotiniPort, restcommContact); fotiniPhoneTcp = fotiniSipStackTcp.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, fotiniContactTcp); fotiniClientSid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "fotini", clientPassword, null); bobSipStackTcp = tool8.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", bobPort, restcommContact); bobPhoneTcp = bobSipStackTcp.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, bobContactTcp); leftySipStack = tool9.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", leftyPort, restcommContact); leftyPhone = leftySipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, leftyContact); externalSipStack = tool10.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", externalPort, restcommContact); externalPhone = externalSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, externalContact); closedSipStack = tool11.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", closedPort, restcommContact); closedPhone = closedSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, closedContact); suspendedSipStack = tool12.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", suspendedPort, restcommContact); suspendedPhone = suspendedSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, suspendedContact); } @After public void after() throws Exception { if (mariaPhone != null) { mariaPhone.dispose(); } if (mariaSipStack != null) { mariaSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (dimitriPhone != null) { dimitriPhone.dispose(); } if (dimitriSipStack != null) { dimitriSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (clientWithAppPhone != null) { clientWithAppPhone.dispose(); } if (clientWithAppSipStack != null) { clientWithAppSipStack.dispose(); } if (fotiniPhoneTcp != null) { fotiniPhoneTcp.dispose(); } if (fotiniSipStackTcp != null) { fotiniSipStackTcp.dispose(); } if (bobPhoneTcp != null) { bobPhoneTcp.dispose(); } if (bobSipStackTcp != null) { bobSipStackTcp.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(3000); } @Test public void testRegisterClients() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 3600, 3600)); assertTrue(dimitriPhone.register(uri, "dimitri", clientPassword, dimitriContact, 3600, 3600)); Thread.sleep(1000); assertTrue(alicePhone.unregister(aliceContact, 0)); assertTrue(mariaPhone.unregister(mariaContact, 0)); assertTrue(dimitriPhone.unregister(dimitriContact, 0)); } @Test @Category(UnstableTests.class) public void testClientsCallEachOther() throws ParseException, InterruptedException { JsonObject cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); int origCdrs = cdrsArray.size(); assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 3600, 3600)); assertTrue(dimitriPhone.register(uri, "dimitri", clientPassword, dimitriContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall dimitriCall = dimitriPhone.createSipCall(); dimitriCall.listenForIncomingCall(); Thread.sleep(1000); // Maria initiates a call to Dimitri long startTime = System.currentTimeMillis(); final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, dimitriContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(dimitriCall.waitForIncomingCall(5000)); assertTrue(dimitriCall.sendIncomingCallResponse(100, "Trying-Dimitri", 1800)); assertTrue(dimitriCall.sendIncomingCallResponse(180, "Ringing-Dimitri", 1800)); String receivedBody = new String(dimitriCall.getLastReceivedRequest().getRawContent()); assertTrue(dimitriCall.sendIncomingCallResponse(Response.OK, "OK-Dimitri", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.getDialog().equals(mariaDialog)); mariaCall.sendInviteOkAck(); assertTrue(mariaCall.getDialog().equals(mariaDialog)); assertTrue(!(mariaCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(dimitriCall.waitForAck(3000)); //Talk time ~ 3sec Thread.sleep(3000); dimitriCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); assertTrue(dimitriCall.waitForDisconnect(5 * 1000)); assertTrue(dimitriCall.respondToDisconnect()); long endTime = System.currentTimeMillis(); double totalTime = (endTime - startTime)/1000.0; assertTrue(3.0 <= totalTime); assertTrue(totalTime <= 4.0); Thread.sleep(3000); //Check CDR cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(cdrs); cdrsArray = cdrs.get("calls").getAsJsonArray(); assertEquals(1, cdrsArray.size()-origCdrs); } @Test @Category(FeatureAltTests.class) public void testClientsCallEachOtherWithCustomHeaders() throws ParseException, InterruptedException { String customHeaderName1 = "X-custom-header1"; String value1 = "1234"; String customHeaderName2 = "X-custom-header2"; String value2 = "4321"; JsonObject cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); int origCdrs = cdrsArray.size(); assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 3600, 3600)); assertTrue(dimitriPhone.register(uri, "dimitri", clientPassword, dimitriContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall dimitriCall = dimitriPhone.createSipCall(); dimitriCall.listenForIncomingCall(); Thread.sleep(1000); // Maria initiates a call to Dimitri long startTime = System.currentTimeMillis(); final SipCall mariaCall = mariaPhone.createSipCall(); ArrayList<String> additionalHeaders = new ArrayList<>(); additionalHeaders.add(mariaPhone.getParent().getHeaderFactory().createHeader(customHeaderName1, value1).toString()); additionalHeaders.add(mariaPhone.getParent().getHeaderFactory().createHeader(customHeaderName2, value2).toString()); mariaCall.initiateOutgoingCall(mariaContact, dimitriContact, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(dimitriCall.waitForIncomingCall(5000)); SipRequest invite = dimitriCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader(customHeaderName1)).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader(customHeaderName2)).getValue(); assertEquals(value1, customHeader1); assertEquals(value2, customHeader2); assertTrue(dimitriCall.sendIncomingCallResponse(100, "Trying-Dimitri", 1800)); assertTrue(dimitriCall.sendIncomingCallResponse(180, "Ringing-Dimitri", 1800)); String receivedBody = new String(dimitriCall.getLastReceivedRequest().getRawContent()); assertTrue(dimitriCall.sendIncomingCallResponse(Response.OK, "OK-Dimitri", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.getDialog().equals(mariaDialog)); mariaCall.sendInviteOkAck(); assertTrue(mariaCall.getDialog().equals(mariaDialog)); assertTrue(!(mariaCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(dimitriCall.waitForAck(3000)); //Talk time ~ 3sec Thread.sleep(3000); dimitriCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); assertTrue(dimitriCall.waitForDisconnect(5 * 1000)); assertTrue(dimitriCall.respondToDisconnect()); long endTime = System.currentTimeMillis(); double totalTime = (endTime - startTime)/1000.0; assertTrue(3.0 <= totalTime); assertTrue(totalTime <= 4.0); Thread.sleep(3000); //Check CDR cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(cdrs); cdrsArray = cdrs.get("calls").getAsJsonArray(); assertEquals(1, cdrsArray.size()-origCdrs); } @Test @Category(FeatureAltTests.class) public void testClientsCallEachOtherWithFriendlyNameSetKouKouRouKou() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); Thread.sleep(1000); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 3600, 3600)); Thread.sleep(3000); assertTrue(leftyPhone.register(uri, "lefty", "1234", leftyContact, 3600, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); Thread.sleep(1000); // Maria initiates a call to Dimitri long startTime = System.currentTimeMillis(); final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, leftyContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); final SipCall leftyCall = leftyPhone.createSipCall(); leftyCall.listenForIncomingCall(); assertTrue(leftyCall.waitForIncomingCall(3000)); assertTrue(leftyCall.sendIncomingCallResponse(100, "Trying-Lefty", 1800)); assertTrue(leftyCall.sendIncomingCallResponse(180, "Ringing-Lefty", 1800)); String receivedBody = new String(leftyCall.getLastReceivedRequest().getRawContent()); assertTrue(leftyCall.sendIncomingCallResponse(Response.OK, "OK-Lefty", 3600, receivedBody, "application", "sdp", null, null)); // // Start a new thread for Dimitri to wait disconnect // new Thread(new Runnable() { // @Override // public void run() { // assertTrue(leftyCall.waitForIncomingCall(3000)); // assertTrue(leftyCall.sendIncomingCallResponse(100, "Trying-Lefty", 1800)); // assertTrue(leftyCall.sendIncomingCallResponse(180, "Ringing-Lefty", 1800)); // String receivedBody = new String(leftyCall.getLastReceivedRequest().getRawContent()); // assertTrue(leftyCall.sendIncomingCallResponse(Response.OK, "OK-Lefty", 3600, receivedBody, "application", "sdp", null, // null)); // // assertTrue(dimitriCall.sendIncomingCallResponse(200, "OK", 1800)); // // assertTrue(dimitriCall.waitForAck(3000)); // } // }).run(); //.start(); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.getDialog().equals(mariaDialog)); mariaCall.sendInviteOkAck(); assertTrue(mariaCall.getDialog().equals(mariaDialog)); assertTrue(!(mariaCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(leftyCall.waitForAck(3000)); //Talk time ~ 3sec Thread.sleep(3000); leftyCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); assertTrue(leftyCall.waitForDisconnect(5 * 1000)); assertTrue(leftyCall.respondToDisconnect()); long endTime = System.currentTimeMillis(); double totalTime = (endTime - startTime)/1000.0; assertTrue(3.0 <= totalTime); assertTrue(totalTime <= 4.0); } @Test @Category(UnstableTests.class) public void testClientDialOutPstn() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); Thread.sleep(1000); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); georgeCall.waitForIncomingCall(5 * 1000); georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.sendInviteOkAck()); // For a reason the ACK will never reach Restcomm. This is only when working with the sipUnit // assertTrue(georgeCall.waitForAck(5 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Test @Category(FeatureAltTests.class) public void testClientDialOutPstnWithCustomHeaders() throws ParseException, InterruptedException { String customHeaderName1 = "X-custom-header1"; String value1 = "1234"; String customHeaderName2 = "X-custom-header2"; String value2 = "4321"; assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); Thread.sleep(1000); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); ArrayList<String> additionalHeaders = new ArrayList<>(); additionalHeaders.add(mariaPhone.getParent().getHeaderFactory().createHeader(customHeaderName1, value1).toString()); additionalHeaders.add(mariaPhone.getParent().getHeaderFactory().createHeader(customHeaderName2, value2).toString()); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); georgeCall.waitForIncomingCall(5 * 1000); SipRequest invite = georgeCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader(customHeaderName1)).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader(customHeaderName2)).getValue(); assertEquals(value1, customHeader1); assertEquals(value2, customHeader2); georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.sendInviteOkAck()); // For a reason the ACK will never reach Restcomm. This is only when working with the sipUnit // assertTrue(georgeCall.waitForAck(5 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Test @Category(FeatureAltTests.class) public void testWebRTCClientDialOutPstnWithCustomHeadersOnInitialInvite() throws ParseException, InterruptedException { String customHeaderName1 = "X-custom-header1"; String value1 = "1234"; String customHeaderName2 = "X-custom-header2"; String value2 = "4321"; assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); Thread.sleep(1000); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); ArrayList<String> additionalHeaders = new ArrayList<>(); additionalHeaders.add(mariaPhone.getParent().getHeaderFactory().createHeader(customHeaderName1, value1).toString()); additionalHeaders.add(mariaPhone.getParent().getHeaderFactory().createHeader(customHeaderName2, value2).toString()); ArrayList<String> replaceHeaders = new ArrayList<>(); replaceHeaders.add(mariaPhone.getParent().getHeaderFactory().createHeader("User-Agent", "wss-sipunit").toString()); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", additionalHeaders, replaceHeaders); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.sendInviteOkAck()); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); SipRequest invite = georgeCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader(customHeaderName1)).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader(customHeaderName2)).getValue(); assertEquals(value1, customHeader1); assertEquals(value2, customHeader2); georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // For a reason the ACK will never reach Restcomm. This is only when working with the sipUnit // assertTrue(georgeCall.waitForAck(5 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Test //Issue: https://github.com/RestComm/Restcomm-Connect/issues/2086 public void testDialClientFromPstn() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.listenForIncomingCall(); final SipCall externalCall = externalPhone.createSipCall(); externalCall.initiateOutgoingCall(leftyContact, "sip:maria@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(externalCall); assertTrue(externalCall.waitOutgoingCallResponse(5 * 1000)); final int response = externalCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(externalCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, externalCall.getLastReceivedResponse().getStatusCode()); } assertTrue(externalCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, externalCall.getLastReceivedResponse().getStatusCode()); assertTrue(externalCall.sendInviteOkAck()); assertTrue(mariaCall.waitForIncomingCall(5000)); assertTrue(mariaCall.sendIncomingCallResponse(Response.TRYING, "Maria-Trying", 3600)); assertTrue(mariaCall.sendIncomingCallResponse(Response.RINGING, "Maria-Ringing", 3600)); String receivedBody = new String(mariaCall.getLastReceivedRequest().getRawContent()); assertTrue(mariaCall.sendIncomingCallResponse(Response.OK, "Maria-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitForAck(5000)); Thread.sleep(1000); externalCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); assertTrue(externalCall.waitForDisconnect(5000)); assertTrue(externalCall.respondToDisconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Test //Issue: https://github.com/RestComm/Restcomm-Connect/issues/2086 @Category(FeatureAltTests.class) public void testDialWebRTCClientFromPstnWithCustomHeadersOnInitialInvite() throws ParseException, InterruptedException { String customHeaderName1 = "X-custom-header1"; String value1 = "1234"; String customHeaderName2 = "X-custom-header2"; String value2 = "4321"; assertNotNull(mariaRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.listenForIncomingCall(); final SipCall externalCall = externalPhone.createSipCall(); ArrayList<String> additionalHeaders = new ArrayList<>(); additionalHeaders.add(externalPhone.getParent().getHeaderFactory().createHeader(customHeaderName1, value1).toString()); additionalHeaders.add(externalPhone.getParent().getHeaderFactory().createHeader(customHeaderName2, value2).toString()); ArrayList<String> replaceHeaders = new ArrayList<>(); replaceHeaders.add(externalPhone.getParent().getHeaderFactory().createHeader("User-Agent", "wss-sipunit").toString()); externalCall.initiateOutgoingCall(leftyContact, "sip:maria@" + restcommContact, null, body, "application", "sdp", additionalHeaders, replaceHeaders); assertLastOperationSuccess(externalCall); assertTrue(externalCall.waitOutgoingCallResponse(5 * 1000)); final int response = externalCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(externalCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, externalCall.getLastReceivedResponse().getStatusCode()); } assertTrue(externalCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, externalCall.getLastReceivedResponse().getStatusCode()); assertTrue(externalCall.sendInviteOkAck()); assertTrue(mariaCall.waitForIncomingCall(5000)); SipRequest invite = mariaCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader(customHeaderName1)).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader(customHeaderName2)).getValue(); assertEquals(value1, customHeader1); assertEquals(value2, customHeader2); assertTrue(mariaCall.sendIncomingCallResponse(Response.TRYING, "Maria-Trying", 3600)); assertTrue(mariaCall.sendIncomingCallResponse(Response.RINGING, "Maria-Ringing", 3600)); String receivedBody = new String(mariaCall.getLastReceivedRequest().getRawContent()); assertTrue(mariaCall.sendIncomingCallResponse(Response.OK, "Maria-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(mariaCall.waitForAck(5000)); Thread.sleep(1000); externalCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); assertTrue(externalCall.waitForDisconnect(5000)); assertTrue(externalCall.respondToDisconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1042 - Support WebRTC clients to dial out through MediaServer @Category(FeatureExpTests.class) public void testClientDialOutPstnSimulateWebRTCClient() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Thread.sleep(1000); //Change UserAgent header to "sipunit" so CallManager ArrayList<String> replaceHeaders = new ArrayList<String>(); List<String> userAgentList = new ArrayList<String>(); userAgentList.add("wss-sipunit"); UserAgentHeader userAgentHeader = mariaSipStack.getHeaderFactory().createUserAgentHeader(userAgentList); replaceHeaders.add(userAgentHeader.toString()); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", null, replaceHeaders); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); assertNotNull(mariaDialog); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // For a reason the ACK will never reach Restcomm. This is only when working with the sipUnit // assertTrue(georgeCall.waitForAck(5 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Test //Non regression test for issue https://github.com/RestComm/Restcomm-Connect/issues/1379 - Webrtc calls from non WS clients aren't routed to PSTN #1379 @Category(FeatureAltTests.class) public void testClientDialOutPstnWebRTCClientwithSDP() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Thread.sleep(1000); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, webRtcBody, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); assertNotNull(mariaDialog); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); assertTrue(mariaCall.sendInviteOkAck()); assertTrue(georgeCall.waitForIncomingCall(5 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600)); SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastReceivedRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // For a reason the ACK will never reach Restcomm. This is only when working with the sipUnit // assertTrue(georgeCall.waitForAck(5 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); assertTrue(mariaCall.disconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } @Test @Category(FeatureExpTests.class) public void testClientDialToInvalidNumber() throws ParseException, InterruptedException, InvalidArgumentException, SipException { String invalidNumber = "+123456789"; SipPhone outboundProxy = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, "sip:"+invalidNumber+"@127.0.0.1:" + georgePort); assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); Thread.sleep(1000); // Maria initiates a call to invalid number final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+invalidNumber+"@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); final SipCall georgeCall = outboundProxy.createSipCall(); georgeCall.listenForIncomingCall(); georgeCall.waitForIncomingCall(5 * 1000); georgeCall.sendIncomingCallResponse(Response.NOT_FOUND, "Not-Found George", 3600); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.NOT_FOUND); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.NOT_FOUND, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } outboundProxy.dispose(); } @Test @Category({FeatureExpTests.class, UnstableTests.class}) public void testClientDialOutPstnCancelBefore200() throws ParseException, InterruptedException { assertNotNull(mariaRestcommClientSid); assertNotNull(dimitriRestcommClientSid); SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", clientPassword, mariaContact, 14400, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "maria", clientPassword); mariaPhone.addUpdateCredential(c); Thread.sleep(1000); // Maria initiates a call to Dimitri final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, "sip:"+pstnNumber+"@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitForAuthorisation(3000)); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); georgeCall.waitForIncomingCall(5 * 1000); georgeCall.sendIncomingCallResponse(Response.RINGING, "RINGING-George", 3600); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responseMaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseMaria == Response.TRYING || responseMaria == Response.RINGING); Dialog mariaDialog = null; if (responseMaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); mariaDialog = mariaCall.getDialog(); } SipTransaction mariaCancelTransaction = mariaCall.sendCancel(); assertTrue(mariaCancelTransaction != null); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(5 * 1000); assertTrue(georgeCancelTransaction != null); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-George", 3600); // Thread.sleep(3000); // georgeCall.listenForDisconnect(); // assertTrue(mariaCall.disconnect()); // assertTrue(georgeCall.waitForDisconnect(5 * 1000)); // assertTrue(georgeCall.respondToDisconnect()); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. georgeCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } @Test @Category(UnstableTests.class) public synchronized void testDialClientAliceWithExtraParamsAtContactHeader() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); String extraParamName1 = "rc-id"; String extraParamValue1 = "7616"; String extraParamName2 = "my-param"; String extraParamValue2 = "test"; aliceContact = aliceContact+";"+extraParamName1+"="+extraParamValue1+";"+extraParamName2+"="+extraParamValue2; // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); SipUri ruri = (SipUri) aliceCall.getLastReceivedRequest().getRequestEvent().getRequest().getRequestURI(); assertEquals(extraParamValue1, ruri.getParameter(extraParamName1)); assertEquals(extraParamValue2, ruri.getParameter(extraParamName2)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. georgeCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } private String dialWebRTCClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>bob</Client></Dial></Response>"; @Test public synchronized void testDialClientWebRTCAliceFromAnotherInstance() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialWebRTCClientRcml))); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); georgeCall.listenForDisconnect(); //Restcomm checks for Bob registration, finds one but this is WebRTC=true and the registration instanceId is not the current Restcomm instance id assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); } private String dialWebRTCClientForkRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>bob</Client><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientForkWithWebRTCAliceFromAnotherInstance() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialWebRTCClientForkRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. georgeCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } private String dialAliceDimitriRcml= "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client><Sip>"+dimitriContact+"</Sip></Dial></Response>"; @Test public synchronized void testDialForkClient_AliceMultipleRegistrations_George() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceDimitriRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); assertTrue(alicePhone2.register(uri, "alice", "1234", aliceContact2, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); SipCall aliceCall2 = alicePhone2.createSipCall(); aliceCall2.listenForIncomingCall(); SipCall dimitriCall = dimitriPhone.createSipCall(); dimitriCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall2.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall2.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice2", 3600)); aliceCall2.listenForCancel(); assertTrue(dimitriCall.waitForIncomingCall(30 * 1000)); assertTrue(dimitriCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Dimitri", 3600)); dimitriCall.listenForCancel(); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); SipTransaction aliceCall2CancelTransaction = aliceCall2.waitForCancel(5000); SipTransaction dimitriCallCancelTransaction = dimitriCall.waitForCancel(5000); assertNotNull(aliceCall2CancelTransaction); assertNotNull(dimitriCallCancelTransaction); aliceCall2.respondToCancel(aliceCall2CancelTransaction, 200, "OK-2-Cancel-Alice2", 3600); dimitriCall.respondToCancel(dimitriCallCancelTransaction, 200, "OK-2-Cancel-Dimitr", 3600); Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); georgeCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 0); assertTrue(liveCallsArraySize == 0); } @Test public synchronized void testDialForkClientWebRTCBob_And_AliceWithMultipleRegistrations() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialWebRTCClientForkRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); assertTrue(alicePhone2.register(uri, "alice", "1234", aliceContact2, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); SipCall aliceCall2 = alicePhone2.createSipCall(); aliceCall2.listenForIncomingCall(); // Create outgoing call with first phone final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall2.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall2.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice2", 3600)); aliceCall2.listenForCancel(); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); SipTransaction aliceCall2CancelTransaction = aliceCall2.waitForCancel(5000); assertNotNull(aliceCall2CancelTransaction); aliceCall2.respondToCancel(aliceCall2CancelTransaction, 200, "OK-2-Cancel-Alice2", 3600); Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue( liveCalls == 2); assertTrue(liveCallsArraySize == 2); Thread.sleep(3000); // hangup. aliceCall.listenForDisconnect(); georgeCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); } private String clientWithAppHostedAppRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Number>+151261006100</Number></Dial></Response>"; @Test public synchronized void testClientWithHostedApplication() throws InterruptedException, ParseException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(clientWithAppHostedAppRcml))); assertNotNull(clientWithAppClientSid); SipURI uri = clientWithAppSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(clientWithAppPhone.register(uri, "clientWithApp", clientPassword, clientWithAppContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "clientWithApp", clientPassword); clientWithAppPhone.addUpdateCredential(c); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); SipCall clientWithAppCall = clientWithAppPhone.createSipCall(); clientWithAppCall.initiateOutgoingCall(clientWithAppContact, "sip:3090909090@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(clientWithAppCall); assertTrue(clientWithAppCall.waitForAuthorisation(5000)); assertTrue(clientWithAppCall.waitOutgoingCallResponse(5000)); final int response = clientWithAppCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(clientWithAppCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, clientWithAppCall.getLastReceivedResponse().getStatusCode()); } assertTrue(clientWithAppCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, clientWithAppCall.getLastReceivedResponse().getStatusCode()); clientWithAppCall.sendInviteOkAck(); assertTrue(!(clientWithAppCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. clientWithAppCall.disconnect(); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); assertTrue(georgeCall.respondToDisconnect()); } @Test @Ignore //This will fail because SipUnit when working on TCP will pick an ephemeral port different than the one at Contact header public void testClientsCallEachOtherOnTcp() throws ParseException, InterruptedException { SipURI uri = fotiniSipStackTcp.getAddressFactory().createSipURI(null, restcommContact); assertTrue(fotiniPhoneTcp.register(uri, "fotini", clientPassword, fotiniContactTcp, 3600, 3600)); Thread.sleep(3000); assertTrue(bobPhoneTcp.register(uri, "bob", clientPassword, bobContactTcp, 3600, 3600)); Thread.sleep(3000); Credential c = new Credential("127.0.0.1", "fotini", clientPassword); fotiniPhoneTcp.addUpdateCredential(c); final SipCall bobCallTcp = bobPhoneTcp.createSipCall(); bobCallTcp.listenForIncomingCall(); Thread.sleep(1000); // Maria initiates a call to Dimitri long startTime = System.currentTimeMillis(); final SipCall fotiniCallTcp = fotiniPhoneTcp.createSipCall(); fotiniCallTcp.initiateOutgoingCall(fotiniContactTcp, bobContactTcp, null, body, "application", "sdp", null, null); assertLastOperationSuccess(fotiniCallTcp); assertTrue(fotiniCallTcp.waitForAuthorisation(5000)); assertTrue(bobCallTcp.waitForIncomingCall(5000)); assertTrue(bobCallTcp.sendIncomingCallResponse(Response.TRYING, "Trying-Bob-TCP", 1800)); assertTrue(fotiniCallTcp.waitOutgoingCallResponse(5000)); assertTrue(fotiniCallTcp.getLastReceivedResponse().getStatusCode()==Response.TRYING); assertTrue(bobCallTcp.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob-TCP", 1800)); assertTrue(fotiniCallTcp.waitOutgoingCallResponse(5000)); assertTrue(fotiniCallTcp.getLastReceivedResponse().getStatusCode()==Response.RINGING); String receivedBody = new String(bobCallTcp.getLastReceivedRequest().getRawContent()); assertTrue(bobCallTcp.sendIncomingCallResponse(Response.OK, "Ok-Bob-TCP", 1800, receivedBody, "application", "sdp", null, null)); assertTrue(fotiniCallTcp.waitOutgoingCallResponse(5000)); assertTrue(fotiniCallTcp.getLastReceivedResponse().getStatusCode()==Response.OK); assertTrue(fotiniCallTcp.sendInviteOkAck()); assertTrue(bobCallTcp.waitForAck(5000)); Thread.sleep(3000); bobCallTcp.listenForDisconnect(); assertTrue(fotiniCallTcp.disconnect()); assertTrue(bobCallTcp.waitForDisconnect(5000)); assertTrue(bobCallTcp.respondToDisconnect()); long endTime = System.currentTimeMillis(); double totalTime = (endTime - startTime)/1000.0; assertTrue(3.0 <= totalTime); assertTrue(totalTime <= 4.0); Thread.sleep(3000); //Check CDR JsonObject cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); System.out.println("cdrsArray.size(): "+cdrsArray.size()); assertTrue(cdrsArray.size() == 1); } @Test public void testSuspendedClientDialingOut() { Credential c = new Credential("127.0.0.1", "suspended", "1234"); suspendedPhone.addUpdateCredential(c); SipCall suspendedCall = suspendedPhone.createSipCall(); suspendedCall.initiateOutgoingCall(suspendedContact, "sip:+151212344566@"+restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(suspendedCall); assertTrue(suspendedCall.waitOutgoingCallResponse(10000)); final int response = suspendedCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.FORBIDDEN); if (response == Response.TRYING) { assertTrue(suspendedCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, suspendedCall.getLastReceivedResponse().getStatusCode()); } } @Test public void testClosedClientDialingOut() { Credential c = new Credential("127.0.0.1", "closed", "1234"); closedPhone.addUpdateCredential(c); SipCall closedCall = closedPhone.createSipCall(); closedCall.initiateOutgoingCall(closedContact, "sip:+151212344566@"+restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(closedCall); assertTrue(closedCall.waitOutgoingCallResponse(10000)); final int response = closedCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.FORBIDDEN); if (response == Response.TRYING) { assertTrue(closedCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, closedCall.getLastReceivedResponse().getStatusCode()); } } @Deployment(name = "ClientsDialTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(mariaPort)); replacements.put("5093", String.valueOf(dimitriPort)); replacements.put("5094", String.valueOf(alicePort2)); replacements.put("5095", String.valueOf(clientWithAppPort)); replacements.put("5096", String.valueOf(fotiniPort)); replacements.put("5097", String.valueOf(bobPort)); replacements.put("5098", String.valueOf(leftyPort)); replacements.put("5099", String.valueOf(externalPort)); List<String> resources = new ArrayList( Arrays.asList( "dial-conference-entry.xml", "dial-fork-entry.xml", "dial-uri-entry.xml", "dial-client-entry.xml", "dial-number-entry.xml")); return WebArchiveUtil.createWebArchiveNoGw( "restcomm.xml", "restcomm.script_dialTest", resources, replacements); } }
89,228
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialForkTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialForkTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; /** * Tests for the Dial forking * Created by gvagenas on 12/19/15. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(SequentialClassTests.class) public class DialForkTest { private final static Logger logger = Logger.getLogger(CallLifecycleTest.class.getName()); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private String dialForkWithActionUrl = "<Response><Dial timeLimit=\"1000\" timeout=\"2\" action=\"http://127.0.0.1:" + mockPort+ "/test\">" + "<Number>+131313</Number><Uri>sip:[email protected]:" + henriquePort +"</Uri><Client>alice</Client></Dial></Response>"; private String rcmlToReturn = "<Response><Dial timeout=\"50\"><Uri>sip:[email protected]:" + fotiniPort + "</Uri></Dial></Response>"; private String dialForkToNotRegisteredClientDialClientFirst = "<Response><Dial><Client>alice</Client><Sip>sip:[email protected]:" + henriquePort + "</Sip></Dial></Response>"; private String dialFork = "<Response><Dial><Client>alice</Client><Sip>sip:[email protected]:" + henriquePort + "</Sip><Number>+131313</Number></Dial></Response>"; private String dialForkToNotRegisteredClientSipFirst = "<Response><Dial><Sip>sip:[email protected]:" + henriquePort + "</Sip><Client>alice</Client></Dial></Response>"; private String dialForkWithTimeout15 = "<Response><Dial timeout=\"15\"><Client>alice</Client><Sip>sip:[email protected]:" + henriquePort + "</Sip><Number>+131313</Number></Dial></Response>"; private String dialSequential = "<Response><Dial timeout=\"5\"><Sip>sip:[email protected]:5566</Sip></Dial><Dial timeout=\"5\"><Sip>sip:[email protected]:6655</Sip></Dial><Dial><Sip>sip:[email protected]:" + henriquePort + "</Sip></Dial></Response>"; private String dialForkTwoSipUrisRcml = "<Response><Dial><Sip>sip:[email protected]:" + fotiniPort + "</Sip><Sip>sip:[email protected]:" + henriquePort + "</Sip></Dial></Response>"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private static String henriquePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String henriqueContact = "sip:[email protected]:" + henriquePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; // Fotini is a simple SIP Client. Will not register with Restcomm private SipStack fotiniSipStack; private SipPhone fotiniPhone; private static String fotiniPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String fotiniContact = "sip:[email protected]:" + fotiniPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialAliceRcmlWithPlay; private static String dialAliceRcmlWithInvalidPlay; private int timeout = 10; private String dialForkWithTimeout = "<Response><Dial timeout=\""+timeout+"\"><Client>alice</Client><Sip>sip:[email protected]:" + henriquePort + "</Sip><Number>+131313</Number></Dial></Response>"; private int initialTotalCallSinceUptime; private int initialOutgoingCallsSinceUptime; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialFork1"); tool2 = new SipStackTool("DialFork2"); tool3 = new SipStackTool("DialFork3"); tool4 = new SipStackTool("DialFork4"); tool5 = new SipStackTool("DialFork5"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { dialAliceRcmlWithPlay = "<Response><Play>" + deploymentUrl.toString() + "/audio/demo-prompt.wav</Play><Dial><Client>alice</Client></Dial></Response>"; dialAliceRcmlWithInvalidPlay = "<Response><Play>" + deploymentUrl.toString() + "/audio/demo-prompt13.wav</Play><Dial><Client>alice</Client></Dial></Response>"; bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", henriquePort, restcommContact); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); fotiniSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", fotiniPort, restcommContact); fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, fotiniContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (fotiniPhone != null) { fotiniPhone.dispose(); } if (fotiniSipStack != null) { fotiniSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(5000); } @Test public synchronized void testDialForkNoAnswerButHenrique() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); georgeCall.listenForCancel(); aliceCall.listenForCancel(); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); //Wait to cancel the other branches Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialForkFromPstn = "<Response><Dial><Client>alice</Client><Sip>sip:[email protected]:" + henriquePort + "</Sip></Dial></Response>"; @Test public synchronized void testDialForkFromPstnNoAnswerButHenrique() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkFromPstn))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); final int response = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); aliceCall.listenForCancel(); assertTrue(aliceCall.waitForIncomingCall(3000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(3000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(5000)); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); // Wait to cancel the other branches Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); georgeCall.listenForDisconnect(); Thread.sleep(3000); // hangup. henriqueCall.disconnect(); assertTrue(georgeCall.waitForDisconnect(3000)); georgeCall.respondToDisconnect(); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test public synchronized void testDialForkNoAnswerButFromAliceClient() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(henriqueCall.listenForCancel()); assertTrue(georgeCall.listenForCancel()); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(30 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 2); assertEquals(2, liveCallsArraySize); aliceCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(bobCall.waitForAnswer(5000)); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); String status = jsonObj.get("status").getAsString(); System.out.println("%%%%Status : "+status); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } // Non regression test for https://github.com/RestComm/Restcomm-Connect/issues/1972 @Test @Category(FeatureAltTests.class) public synchronized void testDialForkToNotRegisteredClientDialSipFirst() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkToNotRegisteredClientSipFirst))); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); //Wait to cancel the other branches Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertEquals(2, liveCallsArraySize); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } //Non regression test for https://github.com/RestComm/Restcomm-Connect/issues/1972 //When Dial Client is first its working fine @Test @Category(FeatureAltTests.class) public synchronized void testDialForkToNotRegisteredClientDialClientFirst() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkToNotRegisteredClientDialClientFirst))); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); //Wait to cancel the other branches Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertEquals(2, liveCallsArraySize); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public synchronized void testDialForkWithBusy() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(486, "Busy Here-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(486, "Busy Here-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertTrue(liveCalls == 2); assertEquals(2, liveCallsArraySize); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("%%%% CallSID: "+callSid+" Status : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public synchronized void testDialForkWithDecline() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //int DECLINE = 603; assertTrue(georgeCall.sendIncomingCallResponse(Response.DECLINE, "Busy Here-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.DECLINE, "Busy Here-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertTrue(liveCalls == 2); assertEquals(2, liveCallsArraySize); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("%%%% CallSID: "+callSid+" Status : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public synchronized void testDialForkBobSendsBye() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); georgeCall.listenForCancel(); aliceCall.listenForCancel(); henriqueCall.listenForCancel(); Thread.sleep(1000); bobCall.disconnect(); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(30000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK-2-Cancel-Henrique", 3600); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); Thread.sleep(10 * 1000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public synchronized void testDialForkNoAnswer() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeout))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and Bob will receive disconnect assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); assertTrue(bobCall.listenForDisconnect()); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); int callDuration = jsonObj.get("duration").getAsInt(); assertEquals(timeout, callDuration, 1.5); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } String nonValidSDP = "v=0\n" + "o=user1 53655765 2353687637 IN IP4 127.0.0.1\n" + "s=- NonValidSDP\n" + "c=IN IP4 127.0.0.1\n" + "t=0 0\n" + "m=audio 6000 RTP/AVP 0\n" + "a=rtpmap:0 PCMU/8000\n"; @Test @Ignore //Passes only when run individually. Doesn't pass when run with the rest of the tests @Category(FeatureAltTests.class) public synchronized void testDialForkWithReInviteBeforeDialForkStarts_CancelCall() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeout))); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); initialTotalCallSinceUptime = metrics.getAsJsonObject("Metrics").get("TotalCallsSinceUptime").getAsInt(); initialOutgoingCallsSinceUptime = metrics.getAsJsonObject("Metrics").get("OutgoingCallsSinceUptime").getAsInt(); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); //Send re-Invite here using non-valid SDP SipTransaction sipTransaction = bobCall.sendReinvite(bobContact, "Bob", nonValidSDP, "application", "sdp"); assertNotNull(sipTransaction); assertLastOperationSuccess(bobCall); //For a reason, container sends 100 straight after 569 and sipunit never receives 569. // assertTrue(bobCall.waitReinviteResponse(sipTransaction, 50 * 1000)); // assertEquals(569, bobCall.getLastReceivedResponse().getStatusCode()); // bobCall.listenForDisconnect(); // assertTrue(bobCall.waitForDisconnect(50 * 1000)); // assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); // assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); // assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); // assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); // assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); // assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); // assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); // assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); // assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); // // //No one will answer the call and Bob will receive disconnect // assertTrue(georgeCall.listenForCancel()); // assertTrue(aliceCall.listenForCancel()); // assertTrue(henriqueCall.listenForCancel()); // // assertTrue(bobCall.listenForDisconnect()); // // SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); // assertNotNull(henriqueCancelTransaction); // henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); // // SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); // assertNotNull(aliceCancelTransaction); // aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); // // SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); // assertNotNull(georgeCancelTransaction); // georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); // assertTrue(bobCall.waitForDisconnect(50 * 1000)); // assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalCallSinceUptime = metrics.getAsJsonObject("Metrics").get("TotalCallsSinceUptime").getAsInt(); int outgoingCallsSinceUptime = metrics.getAsJsonObject("Metrics").get("OutgoingCallsSinceUptime").getAsInt(); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); assertEquals(initialTotalCallSinceUptime+1, totalCallSinceUptime); assertEquals(initialOutgoingCallsSinceUptime, outgoingCallsSinceUptime); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("failed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialClientAlice = "<Response><Dial timeout=\"2\"><Client>alice</Client></Dial></Response>"; @Test //Passes only when run individually. Doesn't pass when run with the rest of the tests. It not only fails, it messes up the metrics and cause all following tests to fail. so ignoring it unless we fix it @Ignore @Category(FeatureAltTests.class) public synchronized void testDialForkWithReInviteAfterDialStarts_CancelCall() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientAlice))); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); initialTotalCallSinceUptime = metrics.getAsJsonObject("Metrics").get("TotalCallsSinceUptime").getAsInt(); initialOutgoingCallsSinceUptime = metrics.getAsJsonObject("Metrics").get("OutgoingCallsSinceUptime").getAsInt(); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(aliceCall.listenForCancel()); //Send re-Invite here using non-valid SDP SipTransaction sipTransaction = bobCall.sendReinvite(bobContact, "Bob", nonValidSDP, "application", "sdp"); assertNotNull(sipTransaction); assertLastOperationSuccess(bobCall); //For a reason, container sends 100 straight after 569 and sipunit never receives 569. // assertTrue(bobCall.waitReinviteResponse(sipTransaction, 50 * 1000)); // assertEquals(569, bobCall.getLastReceivedResponse().getStatusCode()); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); // bobCall.listenForDisconnect(); // assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); // assertTrue(bobCall.waitForDisconnect(50 * 1000)); // assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalCallSinceUptime = metrics.getAsJsonObject("Metrics").get("TotalCallsSinceUptime").getAsInt(); int outgoingCallsSinceUptime = metrics.getAsJsonObject("Metrics").get("OutgoingCallsSinceUptime").getAsInt(); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); assertEquals(initialTotalCallSinceUptime+2, totalCallSinceUptime); assertEquals(initialOutgoingCallsSinceUptime+1, outgoingCallsSinceUptime); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("failed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureAltTests.class) public synchronized void testDialForkNoAnswerWith183FromAlice() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeout))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(183, "SessionProgress-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and Bob will receive disconnect assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); assertTrue(bobCall.listenForDisconnect()); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(aliceCancelTransaction); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertEquals(0, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken)); assertEquals(0, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken)); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } class AutoAnswer implements Runnable { SipCall call; public AutoAnswer(SipCall call) { this.call = call; } public void run() { try { call.waitForIncomingCall(15000); call.sendIncomingCallResponse(Response.TRYING, "Trying", 3600); call.sendIncomingCallResponse(Response.RINGING, "Ringing", 3600); String receivedBody = new String(call.getLastReceivedRequest().getRawContent()); //simulate answer time Thread.sleep(3000); call.sendIncomingCallResponse(Response.OK, "OK", 3600, receivedBody, "application", "sdp", null, null); call.waitForAck(15000); call.listenForDisconnect(); call.waitForDisconnect(15000); } catch (InterruptedException ex) { java.util.logging.Logger.getLogger(DialForkTest.class.getName()).log(Level.SEVERE, null, ex); } } } private void assertNoMGCPResources() { JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category({FeatureExpTests.class, UnstableTests.class}) public synchronized void testDialForkMultipleAnswer() throws InterruptedException, ParseException, MalformedURLException { List<AutoAnswer> autoAnswers = new ArrayList<AutoAnswer>(); stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitForAnswer(10000)); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); aliceCall.waitForIncomingCall(15000); aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying", 3600); aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing", 3600); henriqueCall.waitForIncomingCall(15000); henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying", 3600); henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing", 3600); georgeCall.waitForIncomingCall(15000); georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying", 3600); georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing", 3600); Thread.sleep(3000); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); aliceCall.sendIncomingCallResponse(Response.OK, "OK", 3600, receivedBody, "application", "sdp", null, null); henriqueCall.sendIncomingCallResponse(Response.OK, "OK", 3600, receivedBody, "application", "sdp", null, null); georgeCall.sendIncomingCallResponse(Response.OK, "OK", 3600, receivedBody, "application", "sdp", null, null); assertTrue(aliceCall.waitForAck(20000)); aliceCall.listenForDisconnect(); assertTrue(henriqueCall.waitForAck(20000)); henriqueCall.listenForDisconnect(); assertTrue(georgeCall.waitForAck(20000)); georgeCall.listenForDisconnect(); assertTrue(henriqueCall.waitForDisconnect(15000)); henriqueCall.respondToDisconnect(); assertTrue(georgeCall.waitForDisconnect(15000)); georgeCall.respondToDisconnect(); //TODO assert just one call get establlished, rest are either cancel/bye Thread.sleep(5000); assertEquals(1, MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken)); JsonObject liveCalls = MonitoringServiceTool.getInstance().getLiveCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& liveCalls: "+liveCalls); JsonArray liveCallDetails = liveCalls.getAsJsonArray("LiveCallDetails"); assertEquals(1, MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken)); assertEquals(2,liveCallDetails.size()); bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(5000)); aliceCall.respondToDisconnect(); Thread.sleep(1000); assertNoMGCPResources(); } @Test @Category(FeatureExpTests.class) public synchronized void testDialForkNoAnswerAndNoResponseFromAlice() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeout))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); aliceCall.disposeNoBye(); //Alice will send no response at all // assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); // assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and Bob will receive disconnect assertTrue(georgeCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); assertTrue(bobCall.listenForDisconnect()); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); Thread.sleep(60000); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Thread.sleep(5000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureExpTests.class) public synchronized void testDialForkNoAnswerWith183() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithTimeout15))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(183, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); //No one will answer the call and Bob will receive disconnect assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); assertTrue(bobCall.listenForDisconnect()); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+callSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test //TODO Fails when the whole test class runs but Passes when run individually // @Category(UnstableTests.class) @Category(FeatureAltTests.class) public synchronized void testDialForkNoAnswerExecuteRCML_ReturnedFromActionURL() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithActionUrl))); stubFor(post(urlEqualTo("/test")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlToReturn))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); //No one will answer the call and RCML will move to the next verb to call Fotini assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); Thread.sleep(1000); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); // int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // //There will be the initial call from Bob and the new call to Fotini // logger.info("&&&& LiveCalls: "+liveCalls); // logger.info("&&&& LiveCallsArraySize: "+liveCallsArraySize); // assertTrue(liveCalls == 2); // assertEquals(2, liveCallsArraySize); assertTrue(alicePhone.unregister(aliceContact, 3600)); //Now Fotini should receive a call assertTrue(fotiniCall.waitForIncomingCall(30 * 1000)); assertTrue(fotiniCall.sendIncomingCallResponse(100, "Trying-Fotini", 600)); assertTrue(fotiniCall.sendIncomingCallResponse(180, "Ringing-Fotini", 600)); String receivedBody = new String(fotiniCall.getLastReceivedRequest().getRawContent()); assertTrue(fotiniCall.sendIncomingCallResponse(Response.OK, "OK-Fotini", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(fotiniCall.waitForAck(5000)); fotiniCall.listenForDisconnect(); assertEquals(2, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) ); assertEquals(2, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) ); Thread.sleep(2000); // hangup. assertTrue(bobCall.disconnect()); assertTrue(fotiniCall.waitForDisconnect(50 * 1000)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public synchronized void testDialForkEveryoneBusyExecuteRCML_ReturnedFromActionURL() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkWithActionUrl))); stubFor(post(urlEqualTo("/test")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlToReturn))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(486, "Busy Here-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(486, "Busy Here-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(486, "Busy Here-Henrique", 3600)); assertTrue(henriqueCall.waitForAck(50 * 1000)); //No one will answer the call and RCML will move to the next verb to call Fotini // assertTrue(georgeCall.listenForCancel()); // assertTrue(aliceCall.listenForCancel()); // assertTrue(henriqueCall.listenForCancel()); // // Thread.sleep(1000); // // SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); // SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); // SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); // assertNotNull(georgeCancelTransaction); // assertNotNull(aliceCancelTransaction); // assertNotNull(henriqueCancelTransaction); // georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); // aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); // henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); // int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); // //Even though no call answered the dial forking the originated call from Bob should be still live // assertTrue(liveCalls == 1); // assertTrue(liveCallsArraySize == 1); //Now Fotini should receive a call assertTrue(fotiniCall.waitForIncomingCall(30 * 1000)); assertTrue(fotiniCall.sendIncomingCallResponse(100, "Trying-Fotini", 600)); assertTrue(fotiniCall.sendIncomingCallResponse(180, "Ringing-Fotini", 600)); String receivedBody = new String(fotiniCall.getLastReceivedRequest().getRawContent()); assertTrue(fotiniCall.sendIncomingCallResponse(Response.OK, "OK-Fotini", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(fotiniCall.waitForAck(5000)); fotiniCall.listenForDisconnect(); Thread.sleep(1000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); //Even though no call answered the dial forking the originated call from Bob should be still live logger.info("&&&& LiveCalls: "+liveCalls); logger.info("&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); // assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); // assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 2); Thread.sleep(2000); // hangup. assertTrue(bobCall.disconnect()); assertTrue(fotiniCall.waitForDisconnect(50 * 1000)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test //TODO Fails when the whole test class runs but Passes when run individually // @Category(UnstableTests.class) public void testDialClientAlice() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); assertEquals(2, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) ); assertEquals(2, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) ); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureAltTests.class) public void testDialClientAliceWithPlay() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcmlWithPlay))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); assertEquals(2, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) ); assertEquals(2, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) ); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test //Test that Restcomm cleans up calls when an error from MMS happens @Category(FeatureExpTests.class) public void testDialClientAliceWithInvalidPlayFile() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcmlWithInvalidPlay))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); assertEquals(0, MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) ); assertEquals(0, MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) ); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10000); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test @Category(FeatureAltTests.class) public synchronized void testDialSequentialFirstCallTimeouts() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialSequential))); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(9000); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); //Wait to cancel the other branches Thread.sleep(2000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(alicePhone.unregister(aliceContact, 3600)); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test // @Category({FeatureExpTests.class, UnstableTests.class}) @Category(FeatureAltTests.class) public synchronized void testDialForkWithServerErrorReponse() throws InterruptedException, ParseException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialForkTwoSipUrisRcml))); //Prepare Fotini to receive call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(fotiniCall.waitForIncomingCall(30 * 1000)); assertTrue(fotiniCall.sendIncomingCallResponse(Response.TRYING, "Trying-Fotini", 600)); assertTrue(fotiniCall.sendIncomingCallResponse(Response.SERVER_INTERNAL_ERROR, "Fotini-Internal-Server-Error", 600)); assertTrue(fotiniCall.waitForAck(5000)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 3600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(2, liveCalls); assertEquals(2, liveCallsArraySize); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); assertTrue(henriqueCall.respondToDisconnect()); Thread.sleep(10 * 1000); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); logger.info("About to check the Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111"))); assertTrue(requests.size() == 1); // requests.get(0).g; String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();// .getQuery();// .getBodyAsString(); List<String> params = Arrays.asList(requestBody.split("&")); String callSid = ""; for (String param : params) { if (param.contains("CallSid")) { callSid = param.split("=")[1]; } } JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("%%%% CallSID: "+callSid+" Status : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); assertTrue(MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); assertTrue(MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken) == 0); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Deployment(name = "DialForkTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); replacements.put("5092", String.valueOf(henriquePort)); replacements.put("5093", String.valueOf(fotiniPort)); List<String> resources = new ArrayList(Arrays.asList("hello-play.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm.xml", "restcomm.script_dialForkTest",resources, replacements); } }
145,969
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TestDialVerbPartOneAnswerDelay.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestDialVerbPartOneAnswerDelay.java
package org.restcomm.connect.testsuite.telephony; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.RestcommCallsTool; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import java.util.HashMap; import java.util.Map; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * Test for Dial verb. Will test Dial Conference, Dial URI, Dial Client, Dial Number and Dial Fork * * @author <a href="mailto:[email protected]">gvagenas</a> * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={FeatureAltTests.class, ParallelClassTests.class}) public class TestDialVerbPartOneAnswerDelay { private final static Logger logger = Logger.getLogger(TestDialVerbPartOneAnswerDelay.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); private static final String sdpForHold = "v=0\n" + "o=bob-jitsi.org 0 2 IN IP4 192.168.1.190\n" + "s=-\n" + "c=IN IP4 192.168.1.190\n" + "t=0 0\n" + "m=audio 5000 RTP/AVP 0 8 3 101\n" + "a=rtpmap:0 PCMU/8000\n" + "a=rtpmap:8 PCMA/8000\n" + "a=rtpmap:3 GSM/8000\n" + "a=rtpmap:101 telephone-event/8000\n" + "a=extmap:1 urn:ietf:params:rtp-hdrext:csrc-audio-level\n" + "a=extmap:2 urn:ietf:params:rtp-hdrext:ssrc-audio-level\n" + "a=rtcp-xr:voip-metrics\n" + "m=video 5004 RTP/AVP 96 99\n" + "a=recvonly\n" + "a=rtpmap:96 H264/90000\n" + "a=fmtp:96 profile-level-id=4DE01f;packetization-mode=1\n" + "a=imageattr:96 send * recv [x=[0-1440],y=[0-900]]\n" + "a=rtpmap:99 H264/90000\n" + "a=fmtp:99 profile-level-id=4DE01f\n" + "a=imageattr:99 send * recv [x=[0-1440],y=[0-900]]\n"; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private String dialClientRcmlWithScreeningRelative = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client url=\"http://127.0.0.1:" + mockPort + "/screening\" method=\"GET\">alice</Client></Dial></Response>"; private String dialClientRcmlWithScreening = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client url=\"http://127.0.0.1:" + mockPort + "/screening\" method=\"GET\">alice</Client></Dial></Response>"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String georgeContact = "sip:[email protected]:" + georgePort; // Fotini is a simple SIP Client. Will not register with Restcomm private SipStack fotiniSipStack; private SipPhone fotiniPhone; private static String fotiniPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String fotiniContact = "sip:[email protected]:" + fotiniPort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static String dialRestcomm = "sip:1111@" + restcommContact; private static String notFoundDialNumber = "sip:+12223334457@" + restcommContact; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialTest1Tool1"); tool2 = new SipStackTool("DialTest1Tool2"); tool3 = new SipStackTool("DialTest1Tool3"); tool4 = new SipStackTool("DialTest1Tool4"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; dialRestcomm = "sip:1111@" + restcommContact; notFoundDialNumber = "sip:+12223334457@" + restcommContact; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact); fotiniSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", fotiniPort, restcommContact); fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, fotiniContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (fotiniPhone != null) { fotiniPhone.dispose(); } if (fotiniSipStack != null) { fotiniSipStack.dispose(); } Thread.sleep(3000); wireMockRule.resetRequests(); Thread.sleep(2000); } private String dialUriRcml = "<Response><Dial timeLimit=\"100000\" timeout=\"1000000\"><Uri>sip:[email protected]:" + alicePort + "</Uri></Dial><Hangup/></Response>"; @Test public synchronized void testDialUriAliceHangup() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialUriRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); String outboundCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); String inboundCallSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(50 * 1000)); assertTrue(bobCall.respondToDisconnect()); JsonObject inboundCallCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, inboundCallSid); JsonObject outboundCallCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, outboundCallSid); assertNotNull(inboundCallCdr); assertNotNull(outboundCallCdr); int inboundCdrDuration = inboundCallCdr.get("duration").getAsInt(); int outboundCdrDuration = outboundCallCdr.get("duration").getAsInt(); int outboundCdrRinging = outboundCallCdr.get("ring_duration").getAsInt(); assertTrue(inboundCdrDuration==3); assertTrue(outboundCdrDuration==3); assertTrue(outboundCdrRinging==0); } @Test public synchronized void testDialUriBobHangup() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialUriRcml))); int initialCdrSize = 0; //Check CDR JsonObject cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); if (cdrs != null) { initialCdrSize = cdrs.get("calls").getAsJsonArray().size(); } // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); //Ringing time 5 sec Thread.sleep(5000); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(3000); //Check CDR cdrs = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); System.out.println("cdrsArray.size(): " + cdrsArray.size()); assertTrue((cdrsArray.size() - initialCdrSize) == 2); } @Test public synchronized void testDialUriBobHangupCheckCDRs() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialUriRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); //X-RestComm-CallSid: CAedaccc8f598b4093b1fc33431e1c9ac9 String outboundCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); //Ringing time 5 sec Thread.sleep(5000); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); // X-RestComm-CallSid: CA5c2a775f2ca24003a04b7f7b90e6fabb String inboundCallSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); aliceCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(6000); //Check CDR JsonObject inboundCallCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, inboundCallSid); JsonObject outboundCallCdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, outboundCallSid); assertNotNull(inboundCallCdr); assertNotNull(outboundCallCdr); int inboundCdrDuration = inboundCallCdr.get("duration").getAsInt(); int outboundCdrDuration = outboundCallCdr.get("duration").getAsInt(); int outboundCdrRinging = outboundCallCdr.get("ring_duration").getAsInt(); assertTrue(inboundCdrDuration==8); assertTrue(outboundCdrDuration==3); assertTrue(outboundCdrRinging==5); } private String dialClientRcml = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; @Test public synchronized void testDialClientAlice() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientRcml))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); } @Deployment(name = "TestDialVerbPartOneAnswerDelay", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(georgePort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm-delay.xml", "restcomm.script_dialTest_new", replacements); } }
23,307
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DialTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/DialTest.java
package org.restcomm.connect.testsuite.telephony; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.header.FromHeader; import javax.sip.header.Header; import javax.sip.header.ProxyAuthenticateHeader; import javax.sip.header.ProxyAuthorizationHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipResponse; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.SequentialClassTests; import org.restcomm.connect.testsuite.http.RestcommCallsTool; //import org.restcomm.connect.telephony.Version; import org.restcomm.connect.testsuite.telephony.security.DigestServerAuthenticationMethod; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import gov.nist.javax.sip.message.MessageExt; /** * Test for Dial verb. Will test Dial Conference, Dial URI, Dial Client, Dial Number and Dial Fork * * @author <a href="mailto:[email protected]">gvagenas</a> * @author [email protected] */ @Ignore //Moved all tests to DialTest1, DialTest2, DialTest2 @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={SequentialClassTests.class}) public class DialTest { private final static Logger logger = Logger.getLogger(DialTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private static SipStackTool tool5; private static SipStackTool tool6; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; private SipStack aliceTcpSipStack; private SipPhone aliceTcpPhone; private String aliceTcpContact = "sip:[email protected]:5093;transport=tcp"; // Henrique is a simple SIP Client. Will not register with Restcomm private SipStack henriqueSipStack; private SipPhone henriquePhone; private String henriqueContact = "sip:[email protected]:5092"; // George is a simple SIP Client. Will not register with Restcomm private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // Fotini is a simple SIP Client. Will not register with Restcomm private SipStack fotiniSipStack; private SipPhone fotiniPhone; private String fotiniContact = "sip:[email protected]"; private String dialConf = "sip:[email protected]:5080"; private String dialFork = "sip:[email protected]:5080"; private String dialForkWithStatusCallback = "sip:[email protected]:5080"; private String dialFork_with_RCML = "sip:[email protected]:5080"; private String dialURI = "sip:[email protected]:5080"; private String dialClient = "sip:[email protected]:5080"; private String dialClientWithScreeningUrl = "sip:[email protected]:5080"; private String dialClientWithScreeningRelativeUrl = "sip:[email protected]:5080"; private String dialClientWithRecord = "sip:[email protected]:5080"; private String dialNumber = "sip:[email protected]:5080"; private String notFoundDialNumber = "sip:[email protected]:5080"; private String dialSip = "sip:[email protected]:5080"; private String dialSipSecurity = "sip:[email protected]:5080"; private String dialSipTagScreening = "sip:[email protected]:5080"; private String dialSipDialTagScreening = "sip:[email protected]:5080"; private String dialDIDGreaterThan15Digits = "sip:[email protected]:5080"; private String dialClientWithRecordWithStatusCallback = "sip:[email protected]:5080"; private String dialForCustomHeaders = "sip:[email protected]:5080"; private String recordWithRCMLFromRecordAction = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("CallTestDial1"); tool2 = new SipStackTool("CallTestDial2"); tool3 = new SipStackTool("CallTestDial3"); tool4 = new SipStackTool("CallTestDial4"); tool5 = new SipStackTool("CallTestDial5"); tool6 = new SipStackTool("CallTestDial6"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); aliceTcpSipStack = tool6.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", "5093", "127.0.0.1:5080"); aliceTcpPhone = aliceTcpSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, 5080, aliceTcpContact); henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, henriqueContact); georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); fotiniSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5060", "127.0.0.1:5080"); fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, fotiniContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (henriqueSipStack != null) { henriqueSipStack.dispose(); } if (henriquePhone != null) { henriquePhone.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (fotiniPhone != null) { fotiniPhone.dispose(); } if (fotiniSipStack != null) { fotiniSipStack.dispose(); } deployer.undeploy("DialTest"); Thread.sleep(1000); } @Test @Ignore public synchronized void testDialConference() throws InterruptedException { deployer.deploy("DialTest"); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialConf, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int responseBob = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING); if (responseBob == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // George calls to the conference final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialConf, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); // Start a new thread for george to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForDisconnect(30 * 1000)); } }).start(); // Start a new thread for bob to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(bobCall.waitForDisconnect(30 * 1000)); } }).start(); // assertTrue(bobCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore public synchronized void testDialConferenceWithContactHeaderPortNull() throws InterruptedException { deployer.deploy("DialTest"); final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.initiateOutgoingCall(fotiniContact, dialConf, null, body, "application", "sdp", null, null); assertLastOperationSuccess(fotiniCall); assertTrue(fotiniCall.waitOutgoingCallResponse(5 * 1000)); int responseFotini = fotiniCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseFotini == Response.TRYING || responseFotini == Response.RINGING); if (responseFotini == Response.TRYING) { assertTrue(fotiniCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, fotiniCall.getLastReceivedResponse().getStatusCode()); } assertTrue(fotiniCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, fotiniCall.getLastReceivedResponse().getStatusCode()); fotiniCall.sendInviteOkAck(); assertTrue(!(fotiniCall.getLastReceivedResponse().getStatusCode() >= 400)); // George calls to the conference final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialConf, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); // Wait for the media to play and the call to hangup. fotiniCall.listenForDisconnect(); georgeCall.listenForDisconnect(); // Start a new thread for george to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForDisconnect(30 * 1000)); } }).start(); // Start a new thread for bob to wait disconnect new Thread(new Runnable() { @Override public void run() { assertTrue(fotiniCall.waitForDisconnect(30 * 1000)); } }).start(); // assertTrue(bobCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore // Non regression test for // https://bitbucket.org/telestax/telscale-restcomm/issue/113/when-restcomm-cannot-find-an-app-url-it public synchronized void testDialApplicationInvalidURL() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, notFoundDialNumber, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); // wait for 100 Trying // assertTrue(bobCall.waitOutgoingCallResponse(10000)); // Thread.sleep(3000); // wait for 180 Ringing assertTrue(bobCall.waitOutgoingCallResponse(10000)); // wait for 404 Not Found assertTrue(bobCall.waitOutgoingCallResponse(10000)); SipResponse lastResponse = bobCall.getLastReceivedResponse(); assertTrue(lastResponse.getStatusCode() == 503); } @Test @Ignore public synchronized void testDialUriAliceHangup() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialURI, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. aliceCall.disconnect(); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(30 * 1000)); assertTrue(bobCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore public synchronized void testDialUriBobHangup() throws InterruptedException, ParseException { deployer.deploy("DialTest"); int initialCdrSize = 0; //Check CDR JsonObject cdrs = RestcommCallsTool.getInstance().getCalls("http://127.0.0.1:8080/restcomm", adminAccountSid, adminAuthToken); if (cdrs != null) { initialCdrSize = cdrs.get("calls").getAsJsonArray().size(); } // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialURI, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); //Ringing time 5 sec Thread.sleep(5000); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } Thread.sleep(3000); //Check CDR cdrs = RestcommCallsTool.getInstance().getCalls("http://127.0.0.1:8080/restcomm", adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); System.out.println("cdrsArray.size(): "+cdrsArray.size()); assertTrue((cdrsArray.size() - initialCdrSize )== 2); } @Test @Ignore public synchronized void testDialUriBobHangupCheckCDRs() throws InterruptedException, ParseException { deployer.deploy("DialTest"); int initialCdrSize = 0; //Check CDR JsonObject cdrs = RestcommCallsTool.getInstance().getCalls("http://127.0.0.1:8080/restcomm", adminAccountSid, adminAuthToken); if (cdrs != null) { initialCdrSize = cdrs.get("calls").getAsJsonArray().size(); } // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialURI, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); //Ringing time 5 sec Thread.sleep(5000); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); aliceCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); assertTrue(aliceCall.respondToDisconnect()); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } Thread.sleep(6000); //Check CDR cdrs = RestcommCallsTool.getInstance().getCalls("http://127.0.0.1:8080/restcomm", adminAccountSid, adminAuthToken); assertNotNull(cdrs); JsonArray cdrsArray = cdrs.get("calls").getAsJsonArray(); if (((JsonObject)cdrsArray.get(initialCdrSize)).get("direction").getAsString().equalsIgnoreCase("inbound")) { assertTrue(((JsonObject)cdrsArray.get(initialCdrSize)).get("sid").getAsString().equals(((JsonObject)cdrsArray.get(initialCdrSize+1)).get("parent_call_sid").getAsString())); int inboundDuration = ((JsonObject)cdrsArray.get(initialCdrSize)).get("duration").getAsInt(); assertTrue(inboundDuration==8); } else { assertTrue(((JsonObject)cdrsArray.get(initialCdrSize+1)).get("sid").getAsString().equals(((JsonObject)cdrsArray.get(initialCdrSize)).get("parent_call_sid").getAsString())); int outboundDuration = ((JsonObject)cdrsArray.get(initialCdrSize+1)).get("duration").getAsInt(); int outboundRingDuration = ((JsonObject)cdrsArray.get(initialCdrSize+1)).get("ring_duration").getAsInt(); assertTrue(outboundDuration==3); assertTrue(outboundRingDuration==5); } assertTrue((cdrsArray.size() - initialCdrSize) == 2); } @Test @Ignore public synchronized void testDialClientAlice() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClient, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } final String screeningResponse = "<Response></Response>"; @Test @Ignore public synchronized void testDialClientAliceWithScreeningAbsoluteURL() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/screening")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(screeningResponse))); deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithScreeningUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore public synchronized void testDialClientAliceWithScreeningRelativeURL() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithScreeningRelativeUrl, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore //Ignore because of issue: https://github.com/Mobicents/sipunit/issues/4 public synchronized void testDialClientAliceTCP() throws InterruptedException, ParseException { deployer.deploy("DialTest"); aliceTcpPhone.setLoopback(true); // Phone2 register as alice SipURI uri = aliceTcpSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(aliceTcpPhone.register(uri, "alice", "1234", aliceTcpContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = aliceTcpPhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClient, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); aliceCall.listenForIncomingCall(); assertTrue(aliceCall.waitForIncomingCall(60 * 1000)); System.out.println("!!!!!!!!! Exception: "+aliceCall.getException()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } //DialTest1 up to here //Test for issue RESTCOMM-617 @Test @Ignore public synchronized void testDialClientAliceToBigDID() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialDIDGreaterThan15Digits, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore public synchronized void testDialClientAliceWithRecord() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithRecord, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); final String deploymentUrl = "http://127.0.0.1:8080/restcomm/"; JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl, adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(0)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); } @Test @Ignore //Test case for issue 320 public synchronized void testDialClientAliceWithRecordAndStatusCallbackForApp() throws InterruptedException, ParseException { deployer.deploy("DialTest"); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithRecordWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); final String deploymentUrl = "http://127.0.0.1:8080/restcomm/"; JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl, adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(0)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); logger.info("About to check the Status Callback Requests"); Map<String, String> statusCallbacks = new HashMap<String,String>(); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); for (LoggedRequest loggedRequest : requests) { String queryParam = loggedRequest.getUrl().replaceFirst("/StatusCallBack?", ""); String[] params = queryParam.split("&"); String callSid = params[0].split("=")[1]; String callStatus = params[4].split("=")[1]; if (statusCallbacks.containsKey(callSid)) { statusCallbacks.remove(callSid); } statusCallbacks.put(callSid, callStatus); } assertTrue(statusCallbacks.size()==1); Iterator<String> iter = statusCallbacks.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); assertTrue(statusCallbacks.get(key).equalsIgnoreCase("completed")); } } @Test @Ignore //Test case for issue 320 public synchronized void testDialClientAliceWithRecordAndStatusCallbackForAppForThreeCalls() throws InterruptedException, ParseException, MalformedURLException { deployer.deploy("DialTest"); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialClientWithRecordWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); Request messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(5000); final String deploymentUrl = "http://127.0.0.1:8080/restcomm/"; JsonArray recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl, adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue(recordings.size() == 1); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(0)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(0)).get("uri").getAsString()); /* * Start the second call */ Thread.sleep(2000); bobCall.initiateOutgoingCall(bobContact, dialClientWithRecordWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(3000); recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl, adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue(recordings.size() == 2); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(1)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(1)).get("uri").getAsString()); /* * Start the third call */ Thread.sleep(2000); bobCall.initiateOutgoingCall(bobContact, dialClientWithRecordWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(7000); // hangup. bobCall.disconnect(); bobCall.stopListeningForRequests(); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } bobCall.listenForMessage(); assertTrue(bobCall.waitForMessage(60 * 1000)); assertTrue(bobCall.sendMessageResponse(200, "OK-Message Received", 3600)); messageReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(messageReceived.getRawContent()).equalsIgnoreCase("Hello World!")); Thread.sleep(3000); recordings = RestcommCallsTool.getInstance().getRecordings(deploymentUrl, adminAccountSid, adminAuthToken); assertNotNull(recordings); assertTrue(recordings.size() == 3); assertTrue("7.0".equalsIgnoreCase(((JsonObject)recordings.get(2)).get("duration").getAsString())); assertNotNull(((JsonObject)recordings.get(2)).get("uri").getAsString()); logger.info("About to check the Status Callback Requests"); Map<String, String> statusCallbacks = new HashMap<String,String>(); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); for (LoggedRequest loggedRequest : requests) { String queryParam = loggedRequest.getUrl().replaceFirst("/StatusCallBack?", ""); String[] params = queryParam.split("&"); String callSid = params[0].split("=")[1]; String callStatus = params[4].split("=")[1]; if (statusCallbacks.containsKey(callSid)) { statusCallbacks.remove(callSid); } statusCallbacks.put(callSid, callStatus); } assertTrue(statusCallbacks.size()==3); Iterator<String> iter = statusCallbacks.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); assertTrue(statusCallbacks.get(key).equalsIgnoreCase("completed")); } } @Test @Ignore public synchronized void testDialNumberGeorge() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialNumber, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); final SipRequest lastRequest = georgeCall.getLastReceivedRequest(); String receivedBody = new String(lastRequest.getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // the number dialed uses a callerId of "+13055872294", which is what George should receive String contactHeader = georgeCall.getLastReceivedRequest().getMessage().getHeader("Contact").toString().replaceAll("\r\n",""); assertTrue(contactHeader.equalsIgnoreCase("Contact: \"+13055872294\" <sip:[email protected]:5080>")); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(!bobCall.callTimeoutOrError()); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } //Non-regression test for https://github.com/Mobicents/RestComm/issues/505 @Test @Ignore public synchronized void testDialNumberGeorge_403Forbidden() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // SipURI uri = bobSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); // assertTrue(bobPhone.register(uri, "bob", "1234", bobContact, 3600, 3600)); // // Credential c = new Credential("127.0.0.1", "bob", "1234"); // bobPhone.addUpdateCredential(c); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialNumber, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.FORBIDDEN, "FORBIDDEN-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); } //Non-regression test for https://github.com/Mobicents/RestComm/issues/505 @Test @Ignore public synchronized void testDialNumberGeorge_404_OnBye() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialNumber, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); bobCall.disconnect(); georgeCall.listenForDisconnect(); georgeCall.waitForDisconnect(5000); georgeCall.respondToDisconnect(404, "Not Here"); georgeCall.disposeNoBye(); Thread.sleep(1000); } final String dialNumberNoCallerId = "<Response><Dial><Number url=\"http://127.0.0.1:8080/restcomm/hello-play.xml\">131313</Number></Dial></Response>"; //Test for Issue 210: https://telestax.atlassian.net/browse/RESTCOMM-210 //Bob callerId should pass to the call created by Dial Number @Test @Ignore public synchronized void testDialNumberGeorgePassInitialCallerId() throws InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberNoCallerId))); deployer.deploy("DialTest"); // Prepare George phone to receive call georgePhone.setLoopback(true); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); SipRequest georgeInvite = georgeCall.getLastReceivedRequest(); assertTrue(((FromHeader)georgeInvite.getMessage().getHeader("From")).getAddress().getDisplayName().contains("bob")); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50 * 1000)); Thread.sleep(3000); georgeCall.listenForDisconnect(); // hangup. bobCall.disconnect(); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore public synchronized void testDialFork() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialFork, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // Start a new thread for George new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(486, "Busy Here-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); } }).start(); // Start a new thread for Alice new Thread(new Runnable() { @Override public void run() { assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(486, "Busy Here-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); } }).start(); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique-1", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore public synchronized void testDialForkWithStatusCallback() throws InterruptedException, ParseException { deployer.deploy("DialTest"); stubFor(get(urlPathMatching("/StatusCallBack.*")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialForkWithStatusCallback, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); // Start a new thread for George new Thread(new Runnable() { @Override public void run() { assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(486, "Busy Here-George", 3600)); assertTrue(georgeCall.waitForAck(50 * 1000)); } }).start(); // Start a new thread for Alice new Thread(new Runnable() { @Override public void run() { assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(486, "Busy Here-Alice", 3600)); assertTrue(aliceCall.waitForAck(50 * 1000)); } }).start(); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique-1", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } logger.info("About to check the Status Callback Requests"); Map<String, String> statusCallbacks = new HashMap<String,String>(); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/StatusCallBack.*"))); for (LoggedRequest loggedRequest : requests) { String queryParam = loggedRequest.getUrl().replaceFirst("/StatusCallBack?", ""); String[] params = queryParam.split("&"); String callSid = params[0].split("=")[1]; String callStatus = params[4].split("=")[1]; if (statusCallbacks.containsKey(callSid)) { statusCallbacks.remove(callSid); } statusCallbacks.put(callSid, callStatus); } assertTrue(statusCallbacks.size()==1); Iterator<String> iter = statusCallbacks.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); assertTrue(statusCallbacks.get(key).equalsIgnoreCase("completed")); } } //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test @Ignore public synchronized void testDialForkNoAnswerButFromHenrique() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialFork, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique-1", 3600)); String receivedBody = new String(henriqueCall.getLastReceivedRequest().getRawContent()); Thread.sleep(1000); assertTrue(henriqueCall.sendIncomingCallResponse(Response.OK, "OK-Henrique", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(henriqueCall.waitForAck(50 * 1000)); assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(henriqueCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test @Ignore public synchronized void testDialForkNoAnswerButFromGeorgePSTN() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialFork, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 600)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); Thread.sleep(2000); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(50 * 1000)); assertTrue(henriqueCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(30 * 1000); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); georgeCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(georgeCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } //DialTest2 up to here //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test @Ignore public synchronized void testDialForkNoAnswerButFromAliceClient() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialFork, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.TRYING, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique", 600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); Thread.sleep(2000); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); assertTrue(henriqueCall.listenForCancel()); assertTrue(georgeCall.listenForCancel()); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(30 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(henriqueCancelTransaction); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); aliceCall.respondToCancel(georgeCancelTransaction, 200, "OK - Alice", 600); aliceCall.listenForDisconnect(); Thread.sleep(8000); // hangup. bobCall.disconnect(); assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test @Ignore public synchronized void testDialForkNoAnswerMoveToTheNextVerbAndCallFotini() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialFork, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique-1", 3600)); //No one will answer the call and RCML will move to the next verb to call Fotini assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(20 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(20 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(20 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); //Now Fotini should receive a call assertTrue(fotiniCall.waitForIncomingCall(30 * 1000)); assertTrue(fotiniCall.sendIncomingCallResponse(100, "Trying-Fotini", 600)); assertTrue(fotiniCall.sendIncomingCallResponse(180, "Ringing-Fotini", 600)); String receivedBody = new String(fotiniCall.getLastReceivedRequest().getRawContent()); assertTrue(fotiniCall.sendIncomingCallResponse(Response.OK, "OK-Fotini", 3600, receivedBody, "application", "sdp", null, null)); fotiniCall.listenForDisconnect(); Thread.sleep(4000); // hangup. bobCall.disconnect(); assertTrue(fotiniCall.waitForDisconnect(50 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } // @Rule // public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private String rcmlToReturn = "<Dial timeout=\"50\"><Uri>sip:[email protected]:5060</Uri></Dial>"; //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test @Ignore public synchronized void testDialForkNoAnswerExecuteRCML_ReturnedFromActionURL() throws InterruptedException, ParseException { deployer.deploy("DialTest"); stubFor(post(urlEqualTo("/test")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlToReturn))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Prepare Henrique phone to receive call // henriquePhone.setLoopback(true); final SipCall henriqueCall = henriquePhone.createSipCall(); henriqueCall.listenForIncomingCall(); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialFork_with_RCML, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(100, "Trying-George", 600)); assertTrue(georgeCall.sendIncomingCallResponse(180, "Ringing-George", 600)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(100, "Trying-Alice", 600)); assertTrue(aliceCall.sendIncomingCallResponse(180, "Ringing-Alice", 600)); assertTrue(henriqueCall.waitForIncomingCall(30 * 1000)); assertTrue(henriqueCall.sendIncomingCallResponse(100, "Trying-Henrique", 600)); assertTrue(henriqueCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Henrique-1", 3600)); //No one will answer the call and RCML will move to the next verb to call Fotini assertTrue(georgeCall.listenForCancel()); assertTrue(aliceCall.listenForCancel()); assertTrue(henriqueCall.listenForCancel()); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(50 * 1000); SipTransaction henriqueCancelTransaction = henriqueCall.waitForCancel(50 * 1000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(50 * 1000); assertNotNull(georgeCancelTransaction); assertNotNull(aliceCancelTransaction); assertNotNull(henriqueCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK - George", 600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK - Alice", 600); henriqueCall.respondToCancel(henriqueCancelTransaction, 200, "OK - Henrique", 600); assertTrue(alicePhone.unregister(aliceContact, 3600)); //Now Fotini should receive a call assertTrue(fotiniCall.waitForIncomingCall(30 * 1000)); assertTrue(fotiniCall.sendIncomingCallResponse(100, "Trying-Fotini", 600)); assertTrue(fotiniCall.sendIncomingCallResponse(180, "Ringing-Fotini", 600)); String receivedBody = new String(fotiniCall.getLastReceivedRequest().getRawContent()); assertTrue(fotiniCall.sendIncomingCallResponse(Response.OK, "OK-Fotini", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(fotiniCall.waitForAck(5000)); fotiniCall.listenForDisconnect(); Thread.sleep(2000); // hangup. assertTrue(bobCall.disconnect()); assertTrue(fotiniCall.waitForDisconnect(50 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } // private String rcmlToReturn = "<Dial timeout=\"50\"><Uri>sip:[email protected]:5060</Uri></Dial>"; //Non regression test for https://github.com/Mobicents/RestComm/issues/612 @Test @Ignore public synchronized void testRecord_ExecuteRCML_ReturnedFromActionURL() throws InterruptedException, ParseException { deployer.deploy("DialTest"); stubFor(post(urlEqualTo("/test")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(rcmlToReturn))); //Prepare Fotini phone to receive a call final SipCall fotiniCall = fotiniPhone.createSipCall(); fotiniCall.listenForIncomingCall(); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, recordWithRCMLFromRecordAction, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); //At this point bob leaves a voicemail //Now Fotini should receive a call assertTrue(fotiniCall.waitForIncomingCall(30 * 1000)); assertTrue(fotiniCall.sendIncomingCallResponse(100, "Trying-Fotini", 600)); assertTrue(fotiniCall.sendIncomingCallResponse(180, "Ringing-Fotini", 600)); String receivedBody = new String(fotiniCall.getLastReceivedRequest().getRawContent()); assertTrue(fotiniCall.sendIncomingCallResponse(Response.OK, "OK-Fotini", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(fotiniCall.waitForAck(5000)); fotiniCall.listenForDisconnect(); Thread.sleep(2000); // hangup. assertTrue(bobCall.disconnect()); assertTrue(fotiniCall.waitForDisconnect(50 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } private String sayRcml = "<Response><Say>Hello</Say></Response>"; //Non regression test for https://telestax.atlassian.net/browse/RESTCOMM-585 @Test @Ignore public synchronized void testDialWithCustomHeaders() throws InterruptedException, ParseException { deployer.deploy("DialTest"); //Received request: GET /rcml?CallSid=CA154c8c93d7eb439989a6ea42915b6c1b&AccountSid=ACae6e420f425248d6a26948c17a9e2acf&From=bob&To=%2B17778& //CallStatus=ringing&ApiVersion=2012-04-24&Direction=inbound&CallerName&ForwardedFrom&SipHeader_X-MyCustom-Header1=Value1&SipHeader_X-MyCustom-Header2=Value2 HTTP/1.1 stubFor(get(urlPathEqualTo("/rcml")) .withQueryParam("SipHeader_X-MyCustom-Header1", containing("Value1")) .withQueryParam("SipHeader_X-MyCustom-Header2", containing("Value2")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(sayRcml))); ArrayList<String> additionalHeaders = new ArrayList<String>(); additionalHeaders.add(bobPhone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header1", "Value1").toString()); additionalHeaders.add(bobPhone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header2", "Value2").toString()); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialForCustomHeaders, null, body, "application", "sdp", additionalHeaders, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); bobCall.listenForDisconnect(); Thread.sleep(1000); assertTrue(bobCall.waitForDisconnect(5 * 1000)); assertTrue(bobCall.respondToDisconnect()); } @Test @Ignore // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out public synchronized void testDialSip() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialSip, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.disconnect(); // assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Ignore @Test // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // in auth manner public synchronized void testDialSipAuth() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialSipSecurity, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); DigestServerAuthenticationMethod dsam = new DigestServerAuthenticationMethod(); dsam.initialize(); // it should read values from file, now all static ProxyAuthenticateHeader proxyAuthenticate = aliceSipStack.getHeaderFactory().createProxyAuthenticateHeader( dsam.getScheme()); proxyAuthenticate.setParameter("realm", dsam.getRealm(null)); proxyAuthenticate.setParameter("nonce", dsam.generateNonce()); // proxyAuthenticateImpl.setParameter("domain",authenticationMethod.getDomain()); proxyAuthenticate.setParameter("opaque", ""); proxyAuthenticate.setParameter("algorithm", dsam.getAlgorithm()); ArrayList<Header> headers = new ArrayList<Header>(); headers.add(proxyAuthenticate); assertTrue(aliceCall.sendIncomingCallResponse(Response.PROXY_AUTHENTICATION_REQUIRED, "Non authorized", 3600, headers, null, null)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite.getHeader(ProxyAuthorizationHeader.NAME)); ProxyAuthorizationHeader proxyAuthorization = (ProxyAuthorizationHeader) invite .getHeader(ProxyAuthorizationHeader.NAME); boolean res = dsam.doAuthenticate("alice", "1234", proxyAuthorization, (Request) invite); assertTrue(res); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.disconnect(); // assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // with URL screening public synchronized void testDialSipTagScreening() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialSipTagScreening, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); ArrayList<String> headers = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-mycustomheader", "customValue"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-myothereader", "customOtherValue"); headers.add(customHeader.toString()); headers.add(otherHeader.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", headers, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.disconnect(); // assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // with Dial Action screening public synchronized void testDialSipDialTagScreening() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialSipDialTagScreening, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); ArrayList<String> headers = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-mycustomheader", "customValue"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-myothereader", "customOtherValue"); headers.add(customHeader.toString()); headers.add(otherHeader.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.NOT_FOUND, "Not-Found", 3600, receivedBody, "application", "sdp", headers, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.disconnect(); // assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Test @Ignore // Non regression test for https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // with Dial Action screening public synchronized void testDialSipDialTagScreening180Decline() throws InterruptedException, ParseException { deployer.deploy("DialTest"); // Phone2 register as alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, dialSipDialTagScreening, null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); MessageExt invite = (MessageExt) aliceCall.getLastReceivedRequest().getMessage(); assertNotNull(invite); assertEquals(Request.INVITE, invite.getCSeqHeader().getMethod()); Header mycustomheader = invite.getHeader("X-mycustomheader"); Header myotherheader = invite.getHeader("X-myotherheader"); assertNotNull(mycustomheader); assertNotNull(myotherheader); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing", 3600, receivedBody, "application", "sdp", null, null)); ArrayList<String> headers = new ArrayList<String>(); Header customHeader = aliceSipStack.getHeaderFactory().createHeader("X-mycustomheader", "customValue"); Header otherHeader = aliceSipStack.getHeaderFactory().createHeader("X-myothereader", "customOtherValue"); headers.add(customHeader.toString()); headers.add(otherHeader.toString()); assertTrue(aliceCall.sendIncomingCallResponse(Response.DECLINE, "Declined", 3600, receivedBody, "application", "sdp", headers, null)); assertTrue(aliceCall.waitForAck(50 * 1000)); Thread.sleep(3000); // hangup. bobCall.disconnect(); aliceCall.disconnect(); // assertTrue(aliceCall.waitForDisconnect(30 * 1000)); try { Thread.sleep(10 * 1000); } catch (final InterruptedException exception) { exception.printStackTrace(); } } @Deployment(name = "DialTest", managed = false, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-conference-entry.xml"); archive.addAsWebResource("dial-fork-entry.xml"); archive.addAsWebResource("dial-fork-with-action-entry.xml"); archive.addAsWebResource("dial-uri-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("dial-client-entry-with-screening-url.xml"); archive.addAsWebResource("dial-client-entry-with-screening-relative-url.xml"); archive.addAsWebResource("screening.xml"); archive.addAsWebResource("dial-client-entry-with-recording.xml"); archive.addAsWebResource("dial-sip.xml"); archive.addAsWebResource("dial-sip-auth.xml"); archive.addAsWebResource("dial-sip-screening.xml"); archive.addAsWebResource("dial-sip-dial-screening.xml"); archive.addAsWebResource("dial-number-entry.xml"); archive.addAsWebResource("sip-url-screening-test.jsp"); archive.addAsWebResource("sip-dial-url-screening-test.jsp"); archive.addAsWebResource("hello-play.xml"); archive.addAsWebResource("send-sms.xml"); archive.addAsWebResource("record-withActionUrl.xml"); logger.info("Packaged Test App"); return archive; } }
116,467
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UserAgentManagerWithSBCTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ua/UserAgentManagerWithSBCTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony.ua; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import javax.sip.InvalidArgumentException; import javax.sip.RequestEvent; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; //import org.restcomm.connect.telephony.Version; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import gov.nist.javax.sip.address.SipUri; import gov.nist.javax.sip.message.SIPResponse; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (George Vagenas) */ @RunWith(Arquillian.class) @Category(value={WithInMinsTests.class, ParallelClassTests.class}) public final class UserAgentManagerWithSBCTest { private static Logger logger = Logger.getLogger(UserAgentManagerWithSBCTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static SipStackTool tool1; private SipStack sipStack; private SipPhone phone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort + ";transport=udp"; private static SipStackTool tool2; private SipStack sipStack2; private SipPhone phone2; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; private static SipStackTool tool3; private SipStack sipStack3; private SipPhone phone3; private static String alicePort3 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact3 = "sip:[email protected]:" + alicePort3 + ";transport=udp;rc-id=7616"; private static SipStackTool tool4; private SipStack sipStack4; private SipPhone phone4; private static String alicePort4 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact4 = "sip:[email protected]:" + alicePort4; private static SipStackTool tool5; private SipStack sipStack5; private SipPhone phone5; private static String mariaPort5 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String mariaContact5 = "sip:maria.test%[email protected]:" + mariaPort5; private static SipStackTool tool6; private SipStack sipStack6; private SipPhone phone6; private static String alicePort6 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact6 = "sip:[email protected]:" + alicePort6; private static SipStackTool tool7; private SipStack sipStack7; private SipPhone phone7; private static String alicePort7 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact7 = "sip:[email protected]:" + alicePort7; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; public UserAgentManagerWithSBCTest() { super(); } @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("UserAgentTest1"); tool2 = new SipStackTool("UserAgentTest2"); tool3 = new SipStackTool("UserAgentTest3"); tool4 = new SipStackTool("UserAgentTest4"); tool5 = new SipStackTool("UserAgentTest5"); tool6 = new SipStackTool("UserAgentTest6"); tool7 = new SipStackTool("UserAgentTest7"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { sipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); phone = sipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); sipStack2 = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); phone2 = sipStack2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); sipStack3 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort3, restcommContact); phone3 = sipStack3.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact3); sipStack4 = tool4.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort4, restcommContact); phone4 = sipStack4.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact4); sipStack5 = tool5.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", mariaPort5, restcommContact); phone5 = sipStack5.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, mariaContact5); sipStack6 = tool6.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort6, restcommContact); phone6 = sipStack6.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact6); sipStack7 = tool7.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort7, restcommContact); phone7 = sipStack7.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact7); } @After public void after() throws Exception { if (phone != null) { phone.dispose(); } if (sipStack != null) { sipStack.dispose(); } if (phone2 != null) { phone2.dispose(); } if (sipStack2 != null) { sipStack2.dispose(); } if (phone3 != null) { phone3.dispose(); } if (sipStack3 != null) { sipStack3.dispose(); } if (phone4 != null) { phone4.dispose(); } if (sipStack4 != null) { sipStack4.dispose(); } if (sipStack5 != null) { sipStack5.dispose(); } // deployer.undeploy("UserAgentTest"); } /* * Ensures that the OPTIONS comes back with the contact it was sent with in REGISTER */ @Test public void registerUserAgentWithOptionsPing() throws ParseException, InterruptedException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", "sip:[email protected]:" + alicePort + ";extraparam=restcomr0cks", 3600, 3600)); Thread.sleep(500); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); // This is necessary for SipUnit to accept unsolicited requests. // phone.setLoopback(true); phone.listenRequestMessage(); RequestEvent requestEvent = phone.waitRequest(75000); assertNotNull(requestEvent); assertTrue(requestEvent.getRequest().getMethod().equals(SipRequest.OPTIONS)); assertEquals("sip:[email protected]:" + alicePort + ";extraparam=restcomr0cks", requestEvent.getRequest().getRequestURI().toString()); logger.info("RequestEvent :"+requestEvent.getRequest().toString()); Response response = sipStack.getMessageFactory().createResponse(SIPResponse.OK, requestEvent.getRequest()); phone.sendReply(requestEvent, response); Thread.sleep(1000); // Clean up (Unregister). assertTrue(phone.unregister(aliceContact, 0)); } @Test @Category({FeatureAltTests.class}) public void registerUserAgentWithExtraParamsAndOptionsPing() throws ParseException, InterruptedException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", "sip:[email protected]:" + alicePort + ";transport=udp;rc-id=7616", 3600, 3600)); Thread.sleep(500); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==1); // This is necessary for SipUnit to accept unsolicited requests. // phone.setLoopback(true); phone.listenRequestMessage(); RequestEvent requestEvent = phone.waitRequest(75000); assertNotNull(requestEvent); assertTrue(requestEvent.getRequest().getMethod().equals(SipRequest.OPTIONS)); String extraParam = ((SipUri)requestEvent.getRequest().getRequestURI()).getParameter("rc-id"); assertNotNull(extraParam); logger.info("RequestEvent :"+requestEvent.getRequest().toString()); Response response = sipStack.getMessageFactory().createResponse(SIPResponse.OK, requestEvent.getRequest()); phone.sendReply(requestEvent, response); Thread.sleep(1000); // Clean up (Unregister). assertTrue(phone.unregister(aliceContact, 0)); } @Test @Category({FeatureExpTests.class}) public void registerUserAgentWith408ErrorResponse() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack2.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","bob", "1234"); phone2.addUpdateCredential(c); phone2.setAutoResponseOptionsRequests(false); assertTrue(phone2.register(uri, "bob", "1234", bobContact, 3600, 3600)); Thread.sleep(2000); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone2.setAutoResponseOptionsRequests(true); } @Test @Category({FeatureExpTests.class}) public void registerUserAgentWithExtraParamsAnd408ToOptionsPing() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack3.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone3.addUpdateCredential(c); phone3.setAutoResponseOptionsRequests(false); assertTrue(phone3.register(uri, "alice", "1234", aliceContact3, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone3.setAutoResponseOptionsRequests(true); } @Deployment(name = "UserAgentTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(alicePort)); replacements.put("5071", String.valueOf(alicePort3)); replacements.put("5072", String.valueOf(alicePort4)); replacements.put("5073", String.valueOf(mariaPort5)); replacements.put("5074", String.valueOf(alicePort6)); replacements.put("5075", String.valueOf(alicePort7)); replacements.put("5090", String.valueOf(bobPort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm_UserAgentManagerWithSBCTest.xml", "restcomm.script_UserAgentTest", replacements); } }
15,239
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UserAgentManagerClientAlgorithmTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ua/UserAgentManagerClientAlgorithmTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2018, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.restcomm.connect.testsuite.telephony.ua; import com.google.gson.Gson; import com.google.gson.JsonObject; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommOrganizationsTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.servlet.sip.SipServletResponse; import javax.sip.InvalidArgumentException; import javax.sip.RequestEvent; import javax.sip.address.SipURI; import javax.sip.header.Header; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; //import org.restcomm.connect.telephony.Version; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (George Vagenas) */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={WithInMinsTests.class, ParallelClassTests.class}) public final class UserAgentManagerClientAlgorithmTest { private static Logger logger = Logger.getLogger(UserAgentManagerClientAlgorithmTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static SipStackTool tool1; private SipStack sipStack; private SipPhone phone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort + ";transport=udp"; private static SipStackTool tool2; private SipStack sipStack2; private SipPhone phone2; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; private static SipStackTool tool3; private SipStack sipStack3; private SipPhone phone3; private static String alicePort3 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact3 = "sip:[email protected]:" + alicePort3 + ";transport=udp;rc-id=7616"; private static SipStackTool tool4; private SipStack sipStack4; private SipPhone phone4; private static String alicePort4 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact4 = "sip:[email protected]:" + alicePort4; private static SipStackTool tool5; private SipStack sipStack5; private SipPhone phone5; private static String mariaPort5 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String mariaContact5 = "sip:maria.test%[email protected]:" + mariaPort5; private static SipStackTool tool6; private SipStack sipStack6; private SipPhone phone6; private static String alicePort6 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact6 = "sip:[email protected]:" + alicePort6; private static SipStackTool tool7; private SipStack sipStack7; private SipPhone phone7; private static String alicePort7 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact7 = "sip:[email protected]:" + alicePort7; private static SipStackTool tool8; private SipStack sipStack8; private SipPhone closedPhone; private static String closedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String closedContact = "sip:[email protected]:" + closedPort; private static SipStackTool tool9; private SipStack sipStack9; private SipPhone suspendedPhone; private static String suspendedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String suspendedContact = "sip:[email protected]:" + suspendedPort; private static SipStackTool tool10; private SipStack sipStack10; private SipPhone org1AlicePhone; private static String org1AlicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String org1AliceContact = "sip:[email protected]:" + suspendedPort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; public UserAgentManagerClientAlgorithmTest () { super(); } @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("UserAgentTest1"); tool2 = new SipStackTool("UserAgentTest2"); tool3 = new SipStackTool("UserAgentTest3"); tool4 = new SipStackTool("UserAgentTest4"); tool5 = new SipStackTool("UserAgentTest5"); tool6 = new SipStackTool("UserAgentTest6"); tool7 = new SipStackTool("UserAgentTest7"); tool8 = new SipStackTool("UserAgentTest8"); tool9 = new SipStackTool("UserAgentTest9"); tool10 = new SipStackTool("UserAgentTest10"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { sipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); phone = sipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); sipStack2 = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); phone2 = sipStack2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); sipStack3 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort3, restcommContact); phone3 = sipStack3.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact3); sipStack4 = tool4.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort4, restcommContact); phone4 = sipStack4.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact4); sipStack5 = tool5.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", mariaPort5, restcommContact); phone5 = sipStack5.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, mariaContact5); sipStack6 = tool6.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort6, restcommContact); phone6 = sipStack6.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact6); sipStack7 = tool7.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort7, restcommContact); phone7 = sipStack7.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact7); sipStack8 = tool8.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", closedPort, restcommContact); closedPhone = sipStack8.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, closedContact); sipStack9 = tool9.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", suspendedPort, restcommContact); suspendedPhone = sipStack9.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, suspendedContact); sipStack10 = tool10.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", org1AlicePort, restcommContact); org1AlicePhone = sipStack10.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, org1AliceContact); } @After public void after() throws Exception { if (phone != null) { phone.dispose(); } if (sipStack != null) { sipStack.dispose(); } if (phone2 != null) { phone2.dispose(); } if (sipStack2 != null) { sipStack2.dispose(); } if (phone3 != null) { phone3.dispose(); } if (sipStack3 != null) { sipStack3.dispose(); } if (phone4 != null) { phone4.dispose(); } if (sipStack4 != null) { sipStack4.dispose(); } if (phone5 != null) { phone5.dispose(); } if (sipStack5 != null) { sipStack5.dispose(); } if (phone6 != null) { phone6.dispose(); } if (sipStack6 != null) { sipStack6.dispose(); } if (phone7 != null) { phone7.dispose(); } if (sipStack7 != null) { sipStack7.dispose(); } if (closedPhone != null) { closedPhone.dispose(); } if (sipStack8 != null) { sipStack8.dispose(); } if (suspendedPhone != null) { suspendedPhone.dispose(); } if (sipStack9 != null) { sipStack9.dispose(); } if (org1AlicePhone != null) { org1AlicePhone.dispose(); } if (sipStack10 != null) { sipStack10.dispose(); } } @Test public void registerUserAgent() throws Exception { SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", "sip:127.0.0.1:" + alicePort, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone.unregister("sip:127.0.0.1:" + alicePort, 0)); Thread.sleep(500); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerClosedClient() throws Exception { SipURI uri = sipStack8.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","closed", "1234"); closedPhone.addUpdateCredential(c); assertFalse(closedPhone.register(uri, "closed", "1234", "sip:127.0.0.1:" + closedPort, 3600, 3600)); Thread.sleep(500); assertEquals(Response.FORBIDDEN, closedPhone.getReturnCode()); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); // assertTrue(closedPhone.unregister("sip:127.0.0.1:" + closedPort, 0)); // Thread.sleep(500); // assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerSuspendedClient() throws Exception { SipURI uri = sipStack9.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","suspended", "1234"); suspendedPhone.addUpdateCredential(c); assertFalse(suspendedPhone.register(uri, "suspended", "1234", "sip:127.0.0.1:" + suspendedPort, 3600, 3600)); Thread.sleep(500); assertEquals(Response.FORBIDDEN, suspendedPhone.getReturnCode()); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); // assertTrue(suspendedPhone.unregister("sip:127.0.0.1:" + closedPort, 0)); // Thread.sleep(500); // assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerUserAgentWithTransport() throws Exception { SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone.unregister(aliceContact, 0)); Thread.sleep(500); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerUserAgentWithSecureTransport() throws Exception { SipURI uri = sipStack4.getAddressFactory().createSipURI(null, restcommContact); uri.setSecure(true); Credential c = new Credential("127.0.0.1","alice", "1234"); phone4.addUpdateCredential(c); assertTrue(phone4.register(uri, "alice", "1234", aliceContact4, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone4.unregister(aliceContact4, 0)); Thread.sleep(500); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerUserAgentWithReRegister() throws Exception { // deployer.deploy("UserAgentTest"); SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", "sip:127.0.0.1:" + alicePort, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone.register(uri, "alice", "1234", "sip:127.0.0.1:" + alicePort, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone.unregister("sip:127.0.0.1:" + alicePort, 0)); Thread.sleep(500); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerUserAgentWithOptionsPing() throws ParseException, InterruptedException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(15000); // Clean up (Unregister). assertTrue(phone.getLastReceivedOptionsRequest() != null); assertTrue(phone.unregister(aliceContact, 0)); } @Test public void registerUserAgentWithExtraParamsAndOptionsPing() throws ParseException, InterruptedException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", "sip:[email protected]:" + alicePort + ";transport=udp;rc-id=7616", 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(15000); assertTrue(phone.getLastReceivedOptionsRequest() != null); // Clean up (Unregister). assertTrue(phone.unregister(aliceContact, 0)); } @Test public void registerUserAgentWithExceptionOnOptionsPing() throws ParseException, InterruptedException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); phone.setAutoResponseOptionsRequests(false); assertTrue(phone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWith503ErrorResponse() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack2.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","bob", "1234"); phone2.addUpdateCredential(c); assertTrue(phone2.register(uri, "bob", "1234", bobContact, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone2.setAutoResponseOptionsRequests(false); phone2.setErrorRespondToOptions(SipServletResponse.SC_SERVICE_UNAVAILABLE); phone2.listenRequestMessage(); RequestEvent request = phone2.waitRequest(10000); assertEquals(request.getRequest().getMethod(), SipRequest.OPTIONS); ArrayList<Header> additionalHeader = new ArrayList<Header>(); Header reason = sipStack2.getHeaderFactory().createReasonHeader("udp", 503, "Destination not available"); additionalHeader.add(reason); phone2.sendReply(request, 503, "Service unavailable", null, null, 3600, additionalHeader, null, null); Thread.sleep(50000); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); phone2.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWithExtraParamsAnd503ToOptionsPing() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack3.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone3.addUpdateCredential(c); phone3.setAutoResponseOptionsRequests(false); phone3.setErrorRespondToOptions(SipServletResponse.SC_SERVICE_UNAVAILABLE); assertTrue(phone3.register(uri, "alice", "1234", aliceContact3, 3600, 3600)); Thread.sleep(500); assertEquals(1,MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone3.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWithExtraParamsAnd503ToOptionsPingNoTransport() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack3.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone3.addUpdateCredential(c); phone3.setAutoResponseOptionsRequests(false); phone3.setErrorRespondToOptions(SipServletResponse.SC_SERVICE_UNAVAILABLE); assertTrue(phone3.register(uri, "alice", "1234", aliceContact3, 3600, 3600)); Thread.sleep(500); assertEquals(1,MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone3.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWithExtraParamsAnd408ToOptionsPing() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack3.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone3.addUpdateCredential(c); phone3.setAutoResponseOptionsRequests(false); assertTrue(phone3.register(uri, "alice", "1234", aliceContact3, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone3.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWith408ErrorResponse() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack2.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","bob", "1234"); phone2.addUpdateCredential(c); phone2.setAutoResponseOptionsRequests(false); assertTrue(phone2.register(uri, "bob", "1234", bobContact, 3600, 3600)); Thread.sleep(2000); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone2.setAutoResponseOptionsRequests(true); } @Test @Ignore @Category(UnstableTests.class) public void registerUserAgentWith486BusyErrorResponse() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack2.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","bob", "1234"); phone2.addUpdateCredential(c); assertTrue(phone2.register(uri, "bob", "1234", bobContact, 3600, 3600)); phone2.setAutoResponseOptionsRequests(false); phone2.setErrorRespondToOptions(SipServletResponse.SC_BUSY_HERE); Thread.sleep(2000); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone2.setAutoResponseOptionsRequests(true); } /** * registerUserAgentWithAtTheRateSignInLogin * we should be able to register and remove registration on non-response to options * @throws ParseException * @throws InterruptedException * @throws InvalidArgumentException */ @Test public void registerUserAgentWithAtTheRateSignInLogin() throws ParseException, InterruptedException, InvalidArgumentException { SipURI uri = sipStack5.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","[email protected]", "1234"); phone5.addUpdateCredential(c); phone5.setAutoResponseOptionsRequests(false); assertTrue(phone5.register(uri, "[email protected]", "1234", mariaContact5, 3600, 3600)); Thread.sleep(2000); //user should be registered successfully assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone5.setAutoResponseOptionsRequests(true); } /** * registerMultipleUsersWithSameLoginUnderDifferentOrganizations * https://github.com/RestComm/Restcomm-Connect/issues/2106 * @throws ParseException * @throws InterruptedException * @throws InvalidArgumentException */ @Test public void registerMultipleUsersWithSameLoginUnderDifferentOrganizations() throws ParseException, InterruptedException, InvalidArgumentException { //register alice of organization (testdomain2.restcomm.com) SipURI uri = sipStack6.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("testdomain2.restcomm.com","alice", "1234"); phone6.addUpdateCredential(c); phone6.setAutoResponseOptionsRequests(false); assertTrue(phone6.register(uri, "alice", "1234", aliceContact6, 3600, 3600)); Thread.sleep(500); //alice should be registered successfully assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); //register another alice of organization (127.0.0.1) uri = sipStack7.getAddressFactory().createSipURI(null, restcommContact); c = new Credential("127.0.0.1","alice", "1234"); phone7.addUpdateCredential(c); phone7.setAutoResponseOptionsRequests(false); assertTrue(phone7.register(uri, "alice", "1234", aliceContact7, 3600, 3600)); Thread.sleep(500); //both users should be registered successfully int totalRegistrations = MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken); logger.info("Totatl Registrations: "+totalRegistrations); assertEquals(2, totalRegistrations); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone6.setAutoResponseOptionsRequests(true); phone7.setAutoResponseOptionsRequests(true); } @Test @Category(FeatureAltTests.class) public void migrateClientsPasswordAndRegister() throws ParseException, InterruptedException, InvalidArgumentException { Gson gson = new Gson(); String org1 = "OR11111111111111111111111111111111"; //register alice of organization (org1.restcomm.com) SipURI uri = sipStack10.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("org1.restcomm.com","alice", "1234"); org1AlicePhone.addUpdateCredential(c); assertTrue(org1AlicePhone.register(uri, "alice", "1234", org1AliceContact, 3600, 3600)); Thread.sleep(500); //alice should be registered successfully assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(500); assertTrue(org1AlicePhone.unregister(org1AliceContact, 3600)); Thread.sleep(500); //alice should be registered successfully assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); //Hash client's passwords of Org1 JsonObject clientsMigratedJsonObj = RestcommOrganizationsTool.getInstance().migrateClientsOfOrganization(deploymentUrl.toString(), adminAccountSid, adminAuthToken, org1); assertNotNull(clientsMigratedJsonObj); Map<String,String> migratedClients = new HashMap<>(); migratedClients = (Map<String,String>) gson.fromJson(clientsMigratedJsonObj, migratedClients.getClass()); assertNotNull(migratedClients); assertEquals(4, migratedClients.size()); assertTrue(org1AlicePhone.register(uri, "alice", "1234", org1AliceContact, 3600, 3600)); Thread.sleep(500); //alice should be registered successfully assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(500); assertTrue(org1AlicePhone.unregister(org1AliceContact, 3600)); Thread.sleep(500); //alice should be registered successfully assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Deployment(name = "UserAgentTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(alicePort)); replacements.put("5071", String.valueOf(alicePort3)); replacements.put("5072", String.valueOf(alicePort4)); replacements.put("5073", String.valueOf(mariaPort5)); replacements.put("5074", String.valueOf(alicePort6)); replacements.put("5075", String.valueOf(alicePort7)); replacements.put("5090", String.valueOf(bobPort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm_UserAgentManagerTest.xml", "restcomm.script_UserAgentTestClientAlgorithm", replacements); } }
33,169
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UserAgentManagerTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ua/UserAgentManagerTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony.ua; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.servlet.sip.SipServletResponse; import javax.sip.InvalidArgumentException; import javax.sip.RequestEvent; import javax.sip.address.SipURI; import javax.sip.header.Header; import javax.sip.message.Response; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; //import org.restcomm.connect.telephony.Version; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (George Vagenas) */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={WithInMinsTests.class, ParallelClassTests.class}) public final class UserAgentManagerTest { private static Logger logger = Logger.getLogger(UserAgentManagerTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static SipStackTool tool1; private SipStack sipStack; private SipPhone phone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort + ";transport=udp"; private static SipStackTool tool2; private SipStack sipStack2; private SipPhone phone2; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; private static SipStackTool tool3; private SipStack sipStack3; private SipPhone phone3; private static String alicePort3 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact3 = "sip:[email protected]:" + alicePort3 + ";transport=udp;rc-id=7616"; private static SipStackTool tool4; private SipStack sipStack4; private SipPhone phone4; private static String alicePort4 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact4 = "sip:[email protected]:" + alicePort4; private static SipStackTool tool5; private SipStack sipStack5; private SipPhone phone5; private static String mariaPort5 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String mariaContact5 = "sip:maria.test%[email protected]:" + mariaPort5; private static SipStackTool tool6; private SipStack sipStack6; private SipPhone phone6; private static String alicePort6 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact6 = "sip:[email protected]:" + alicePort6; private static SipStackTool tool7; private SipStack sipStack7; private SipPhone phone7; private static String alicePort7 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact7 = "sip:[email protected]:" + alicePort7; private static SipStackTool tool8; private SipStack sipStack8; private SipPhone closedPhone; private static String closedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String closedContact = "sip:[email protected]:" + closedPort; private static SipStackTool tool9; private SipStack sipStack9; private SipPhone suspendedPhone; private static String suspendedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String suspendedContact = "sip:[email protected]:" + suspendedPort; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; public UserAgentManagerTest() { super(); } @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("UserAgentTest1"); tool2 = new SipStackTool("UserAgentTest2"); tool3 = new SipStackTool("UserAgentTest3"); tool4 = new SipStackTool("UserAgentTest4"); tool5 = new SipStackTool("UserAgentTest5"); tool6 = new SipStackTool("UserAgentTest6"); tool7 = new SipStackTool("UserAgentTest7"); tool8 = new SipStackTool("UserAgentTest8"); tool9 = new SipStackTool("UserAgentTest9"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { sipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); phone = sipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); sipStack2 = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); phone2 = sipStack2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); sipStack3 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort3, restcommContact); phone3 = sipStack3.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact3); sipStack4 = tool4.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort4, restcommContact); phone4 = sipStack4.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact4); sipStack5 = tool5.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", mariaPort5, restcommContact); phone5 = sipStack5.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, mariaContact5); sipStack6 = tool6.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort6, restcommContact); phone6 = sipStack6.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact6); sipStack7 = tool7.initializeSipStack(SipStack.PROTOCOL_TCP, "127.0.0.1", alicePort7, restcommContact); phone7 = sipStack7.createSipPhone("127.0.0.1", SipStack.PROTOCOL_TCP, restcommPort, aliceContact7); sipStack8 = tool8.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", closedPort, restcommContact); closedPhone = sipStack8.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, closedContact); sipStack9 = tool9.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", suspendedPort, restcommContact); suspendedPhone = sipStack9.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, suspendedContact); } @After public void after() throws Exception { if (phone != null) { phone.dispose(); } if (sipStack != null) { sipStack.dispose(); } if (phone2 != null) { phone2.dispose(); } if (sipStack2 != null) { sipStack2.dispose(); } if (phone3 != null) { phone3.dispose(); } if (sipStack3 != null) { sipStack3.dispose(); } if (phone4 != null) { phone4.dispose(); } if (sipStack4 != null) { sipStack4.dispose(); } if (phone5 != null) { phone5.dispose(); } if (sipStack5 != null) { sipStack5.dispose(); } if (phone6 != null) { phone6.dispose(); } if (sipStack6 != null) { sipStack6.dispose(); } if (phone7 != null) { phone7.dispose(); } if (sipStack7 != null) { sipStack7.dispose(); } if (closedPhone != null) { closedPhone.dispose(); } if (sipStack8 != null) { sipStack8.dispose(); } if (suspendedPhone != null) { suspendedPhone.dispose(); } if (sipStack9 != null) { sipStack9.dispose(); } // deployer.undeploy("UserAgentTest"); } @Test public void registerUserAgent() throws Exception { SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", "sip:127.0.0.1:" + alicePort, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone.unregister("sip:127.0.0.1:" + alicePort, 0)); Thread.sleep(500); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerClosedClient() throws Exception { SipURI uri = sipStack8.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","closed", "1234"); closedPhone.addUpdateCredential(c); assertFalse(closedPhone.register(uri, "closed", "1234", "sip:127.0.0.1:" + closedPort, 3600, 3600)); Thread.sleep(500); assertEquals(Response.FORBIDDEN, closedPhone.getReturnCode()); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); // assertTrue(closedPhone.unregister("sip:127.0.0.1:" + closedPort, 0)); // Thread.sleep(500); // assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerSuspendedClient() throws Exception { SipURI uri = sipStack9.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","suspended", "1234"); suspendedPhone.addUpdateCredential(c); assertFalse(suspendedPhone.register(uri, "suspended", "1234", "sip:127.0.0.1:" + suspendedPort, 3600, 3600)); Thread.sleep(500); assertEquals(Response.FORBIDDEN, suspendedPhone.getReturnCode()); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); // assertTrue(suspendedPhone.unregister("sip:127.0.0.1:" + closedPort, 0)); // Thread.sleep(500); // assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerUserAgentWithTransport() throws Exception { SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone.unregister(aliceContact, 0)); Thread.sleep(500); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerUserAgentWithSecureTransport() throws Exception { SipURI uri = sipStack4.getAddressFactory().createSipURI(null, restcommContact); uri.setSecure(true); Credential c = new Credential("127.0.0.1","alice", "1234"); phone4.addUpdateCredential(c); assertTrue(phone4.register(uri, "alice", "1234", aliceContact4, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone4.unregister(aliceContact4, 0)); Thread.sleep(500); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerUserAgentWithReRegister() throws Exception { // deployer.deploy("UserAgentTest"); SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", "sip:127.0.0.1:" + alicePort, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone.register(uri, "alice", "1234", "sip:127.0.0.1:" + alicePort, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); assertTrue(phone.unregister("sip:127.0.0.1:" + alicePort, 0)); Thread.sleep(500); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); } @Test public void registerUserAgentWithOptionsPing() throws ParseException, InterruptedException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(15000); // Clean up (Unregister). assertTrue(phone.getLastReceivedOptionsRequest() != null); assertTrue(phone.unregister(aliceContact, 0)); } @Test public void registerUserAgentWithExtraParamsAndOptionsPing() throws ParseException, InterruptedException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); assertTrue(phone.register(uri, "alice", "1234", "sip:[email protected]:" + alicePort + ";transport=udp;rc-id=7616", 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(15000); assertTrue(phone.getLastReceivedOptionsRequest() != null); // Clean up (Unregister). assertTrue(phone.unregister(aliceContact, 0)); } @Test public void registerUserAgentWithExceptionOnOptionsPing() throws ParseException, InterruptedException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone.addUpdateCredential(c); phone.setAutoResponseOptionsRequests(false); assertTrue(phone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWith503ErrorResponse() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack2.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","bob", "1234"); phone2.addUpdateCredential(c); assertTrue(phone2.register(uri, "bob", "1234", bobContact, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone2.setAutoResponseOptionsRequests(false); phone2.setErrorRespondToOptions(SipServletResponse.SC_SERVICE_UNAVAILABLE); phone2.listenRequestMessage(); RequestEvent request = phone2.waitRequest(10000); assertEquals(request.getRequest().getMethod(), SipRequest.OPTIONS); ArrayList<Header> additionalHeader = new ArrayList<Header>(); Header reason = sipStack2.getHeaderFactory().createReasonHeader("udp", 503, "Destination not available"); additionalHeader.add(reason); phone2.sendReply(request, 503, "Service unavailable", null, null, 3600, additionalHeader, null, null); Thread.sleep(50000); assertTrue(MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)==0); phone2.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWithExtraParamsAnd503ToOptionsPing() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack3.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone3.addUpdateCredential(c); phone3.setAutoResponseOptionsRequests(false); phone3.setErrorRespondToOptions(SipServletResponse.SC_SERVICE_UNAVAILABLE); assertTrue(phone3.register(uri, "alice", "1234", aliceContact3, 3600, 3600)); Thread.sleep(500); assertEquals(1,MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone3.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWithExtraParamsAnd503ToOptionsPingNoTransport() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack3.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone3.addUpdateCredential(c); phone3.setAutoResponseOptionsRequests(false); phone3.setErrorRespondToOptions(SipServletResponse.SC_SERVICE_UNAVAILABLE); assertTrue(phone3.register(uri, "alice", "1234", aliceContact3, 3600, 3600)); Thread.sleep(500); assertEquals(1,MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone3.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWithExtraParamsAnd408ToOptionsPing() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack3.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","alice", "1234"); phone3.addUpdateCredential(c); phone3.setAutoResponseOptionsRequests(false); assertTrue(phone3.register(uri, "alice", "1234", aliceContact3, 3600, 3600)); Thread.sleep(500); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone3.setAutoResponseOptionsRequests(true); } @Test public void registerUserAgentWith408ErrorResponse() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack2.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","bob", "1234"); phone2.addUpdateCredential(c); phone2.setAutoResponseOptionsRequests(false); assertTrue(phone2.register(uri, "bob", "1234", bobContact, 3600, 3600)); Thread.sleep(2000); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone2.setAutoResponseOptionsRequests(true); } @Test @Ignore @Category(UnstableTests.class) public void registerUserAgentWith486BusyErrorResponse() throws ParseException, InterruptedException, InvalidArgumentException { // deployer.deploy("UserAgentTest"); // Register the phone so we can get OPTIONS pings from RestComm. SipURI uri = sipStack2.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","bob", "1234"); phone2.addUpdateCredential(c); assertTrue(phone2.register(uri, "bob", "1234", bobContact, 3600, 3600)); phone2.setAutoResponseOptionsRequests(false); phone2.setErrorRespondToOptions(SipServletResponse.SC_BUSY_HERE); Thread.sleep(2000); assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone2.setAutoResponseOptionsRequests(true); } /** * registerUserAgentWithAtTheRateSignInLogin * we should be able to register and remove registration on non-response to options * @throws ParseException * @throws InterruptedException * @throws InvalidArgumentException */ @Test public void registerUserAgentWithAtTheRateSignInLogin() throws ParseException, InterruptedException, InvalidArgumentException { SipURI uri = sipStack5.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("127.0.0.1","[email protected]", "1234"); phone5.addUpdateCredential(c); phone5.setAutoResponseOptionsRequests(false); assertTrue(phone5.register(uri, "[email protected]", "1234", mariaContact5, 3600, 3600)); Thread.sleep(2000); //user should be registered successfully assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone5.setAutoResponseOptionsRequests(true); } /** * registerMultipleUsersWithSameLoginUnderDifferentOrganizations * https://github.com/RestComm/Restcomm-Connect/issues/2106 * @throws ParseException * @throws InterruptedException * @throws InvalidArgumentException */ @Test public void registerMultipleUsersWithSameLoginUnderDifferentOrganizations() throws ParseException, InterruptedException, InvalidArgumentException { //register alice of organization (testdomain2.restcomm.com) SipURI uri = sipStack6.getAddressFactory().createSipURI(null, restcommContact); Credential c = new Credential("testdomain2.restcomm.com","alice", "1234"); phone6.addUpdateCredential(c); phone6.setAutoResponseOptionsRequests(false); assertTrue(phone6.register(uri, "alice", "1234", aliceContact6, 3600, 3600)); Thread.sleep(500); //alice should be registered successfully assertEquals(1, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); //register another alice of organization (127.0.0.1) uri = sipStack7.getAddressFactory().createSipURI(null, restcommContact); c = new Credential("127.0.0.1","alice", "1234"); phone7.addUpdateCredential(c); phone7.setAutoResponseOptionsRequests(false); assertTrue(phone7.register(uri, "alice", "1234", aliceContact7, 3600, 3600)); Thread.sleep(500); //both users should be registered successfully int totalRegistrations = MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken); logger.info("Totatl Registrations: "+totalRegistrations); assertEquals(2, totalRegistrations); Thread.sleep(50000); assertEquals(0, MonitoringServiceTool.getInstance().getRegisteredUsers(deploymentUrl.toString(),adminAccountSid, adminAuthToken)); phone6.setAutoResponseOptionsRequests(true); phone7.setAutoResponseOptionsRequests(true); } @Deployment(name = "UserAgentTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5070", String.valueOf(alicePort)); replacements.put("5071", String.valueOf(alicePort3)); replacements.put("5072", String.valueOf(alicePort4)); replacements.put("5073", String.valueOf(mariaPort5)); replacements.put("5074", String.valueOf(alicePort6)); replacements.put("5075", String.valueOf(alicePort7)); replacements.put("5090", String.valueOf(bobPort)); return WebArchiveUtil.createWebArchiveNoGw("restcomm_UserAgentManagerTest.xml", "restcomm.script_UserAgentTest", replacements); } }
29,804
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AuthenticationMethod.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/security/AuthenticationMethod.java
package org.restcomm.connect.testsuite.telephony.security; import javax.sip.header.AuthorizationHeader; import javax.sip.message.Request; public interface AuthenticationMethod { /** * Get the authentication scheme */ public String getScheme(); /** * Initialize the authentication method. This has to be done outside the constructor as the constructor is generic (created * from the class name specified in the authentication method). */ public void initialize(); /** * Get the authentication realm. */ public String getRealm(String resource); /** * get the authentication domain. */ public String getDomain(); /** * Get the authentication Algorithm */ public String getAlgorithm(); /** * Generate the challenge string. */ public String generateNonce(); /** * Check the response and answer true if authentication succeeds. Not all of these fields are relevant for every method - a * basic scheme may simply do a username password check. * * @param username is the username and password. * @param authorizationHeader is the authorization header from the SIP request. */ public boolean doAuthenticate(String username, String password, AuthorizationHeader authorizationHeader, Request request); }
1,355
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DigestServerAuthenticationMethod.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/security/DigestServerAuthenticationMethod.java
package org.restcomm.connect.testsuite.telephony.security; /* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.Random; import javax.sip.address.URI; import javax.sip.header.AuthorizationHeader; import javax.sip.message.Request; /** * Implements the HTTP digest authentication method. * * @author M. Ranganathan * @author Marc Bednarek */ public class DigestServerAuthenticationMethod implements AuthenticationMethod { public static final String DEFAULT_SCHEME = "Digest"; public static final String DEFAULT_DOMAIN = "" + System.getProperty("org.mobicents.testsuite.testhostaddr") + ""; public static final String DEFAULT_ALGORITHM = "MD5"; public final static String DEFAULT_REALM = "sip-servlets-realm"; private MessageDigest messageDigest; /** to hex converter */ private static final char[] toHex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; /** * Default constructor. */ public DigestServerAuthenticationMethod() { try { messageDigest = MessageDigest.getInstance(DEFAULT_ALGORITHM); } catch (NoSuchAlgorithmException ex) { System.out.println("Algorithm not found " + ex); ex.printStackTrace(); } } public static String toHexString(byte b[]) { int pos = 0; char[] c = new char[b.length * 2]; for (int i = 0; i < b.length; i++) { c[pos++] = toHex[(b[i] >> 4) & 0x0F]; c[pos++] = toHex[b[i] & 0x0f]; } return new String(c); } /** * Initialize */ public void initialize() { System.out.println("DEBUG, DigestAuthenticationMethod, initialize()," + " the realm is:" + DEFAULT_REALM); } /** * Get the authentication scheme * * @return the scheme name */ public String getScheme() { return DEFAULT_SCHEME; } /** * get the authentication realm * * @return the realm name */ public String getRealm(String resource) { return DEFAULT_REALM; } /** * get the authentication domain. * * @return the domain name */ public String getDomain() { return DEFAULT_DOMAIN; } /** * Get the authentication Algorithm * * @return the alogirithm name (i.e. Digest). */ public String getAlgorithm() { return DEFAULT_ALGORITHM; } /** * Generate the challenge string. * * @return a generated nonce. */ public String generateNonce() { // Get the time of day and run MD5 over it. Date date = new Date(); long time = date.getTime(); Random rand = new Random(); long pad = rand.nextLong(); String nonceString = (Long.valueOf(time)).toString() + (Long.valueOf(pad)).toString(); byte mdbytes[] = messageDigest.digest(nonceString.getBytes()); // Convert the mdbytes array into a hex string. return toHexString(mdbytes); } /** * Check the response and answer true if authentication succeeds. We are making simplifying assumptions here and assuming * that the password is available to us for computation of the MD5 hash. We also dont cache authentications so that the user * has to authenticate on each registration. * * @param user is the username * @param authHeader is the Authroization header from the SIP request. */ public boolean doAuthenticate(String user, String password, AuthorizationHeader authHeader, Request request) { String realm = authHeader.getRealm(); String username = authHeader.getUsername(); if (username == null) { System.out.println("DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "WARNING: userName parameter not set in the header received!!!"); username = user; } if (realm == null) { System.out.println("DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "WARNING: realm parameter not set in the header received!!! WE use the default one"); realm = DEFAULT_REALM; } System.out.println("DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "Trying to authenticate user: " + username + " for " + " the realm: " + realm); String nonce = authHeader.getNonce(); // If there is a URI parameter in the Authorization header, // then use it. URI uri = authHeader.getURI(); // There must be a URI parameter in the authorization header. if (uri == null) { System.out.println("DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "ERROR: uri paramater not set in the header received!"); return false; } System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), username:" + username); System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), realm:" + realm); System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), password:" + password); System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), uri:" + uri); System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), nonce:" + nonce); System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), method:" + request.getMethod()); String A1 = username + ":" + realm + ":" + password; String A2 = request.getMethod().toUpperCase() + ":" + uri.toString(); byte mdbytes[] = messageDigest.digest(A1.getBytes()); String HA1 = toHexString(mdbytes); System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), HA1:" + HA1); mdbytes = messageDigest.digest(A2.getBytes()); String HA2 = toHexString(mdbytes); String KD = HA1 + ":" + nonce; System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), HA2:" + HA2); String nonceCount = authHeader.getParameter("nc"); String cnonce = authHeader.getCNonce(); String qop = authHeader.getQop(); if (cnonce != null && nonceCount != null && qop != null && (qop.equalsIgnoreCase("auth") || qop.equalsIgnoreCase("auth-int"))) { System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), cnonce:" + cnonce); System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), nonceCount:" + nonceCount); System.out.println("DEBUG, DigestAuthenticationMethod, doAuthenticate(), qop:" + qop); KD += ":" + nonceCount; KD += ":" + cnonce; KD += ":" + qop; } KD += ":" + HA2; mdbytes = messageDigest.digest(KD.getBytes()); String mdString = toHexString(mdbytes); String response = authHeader.getResponse(); System.out.println("DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "we have to compare his response: " + response + " with our computed" + " response: " + mdString); int res = (mdString.compareTo(response)); if (res == 0) { System.out.println("DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "User authenticated..."); } else { System.out.println("DEBUG, DigestAuthenticateMethod, doAuthenticate(): " + "User not authenticated..."); } return res == 0; } }
8,395
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProxyManagerTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/proxy/ProxyManagerTest.java
package org.restcomm.connect.testsuite.telephony.proxy; import gov.nist.javax.sip.header.Authorization; import java.sql.SQLException; import java.text.ParseException; import java.util.*; import javax.sip.InvalidArgumentException; import javax.sip.RequestEvent; import javax.sip.address.SipURI; import javax.sip.header.ContactHeader; import javax.sip.header.WWWAuthenticateHeader; import javax.sip.message.Response; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.commons.annotations.WithInMinsTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import org.restcomm.connect.testsuite.http.RestcommCallsTool; //import org.restcomm.connect.telephony.Version; @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value={WithInMinsTests.class, ParallelClassTests.class}) public final class ProxyManagerTest { private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static SipStackTool tool1; private static SipStackTool tool2; private SipStack augustSipStack; private SipPhone augustPhone; private static int augustPort = NetworkPortAssigner.retrieveNextPort(); private String augustContact = "sip:[email protected]:" + augustPort; private SipStack imsSipStack; private SipPhone imsAugustPhone; private static int imsPort = NetworkPortAssigner.retrieveNextPort(); private String imsContact = "sip:127.0.0.1:" + imsPort; public ProxyManagerTest() { super(); } @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("ImsClientsDialTest1"); tool2 = new SipStackTool("ImsClientsDialTest2"); } @Before public void before() throws Exception { imsSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", String.valueOf(imsPort), restcommContact); augustSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", String.valueOf(augustPort), restcommContact); augustPhone = augustSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, augustContact); imsAugustPhone = imsSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, augustContact); imsAugustPhone.setLoopback(true); } private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @After public void after() throws Exception { if (augustPhone != null) { augustPhone.dispose(); } if (augustSipStack != null) { augustSipStack.dispose(); } if (imsSipStack != null) { imsSipStack.dispose(); } if (imsAugustPhone != null) { imsAugustPhone.dispose(); } if (imsSipStack != null) { imsSipStack.dispose(); } if (imsAugustPhone != null) { imsAugustPhone.dispose(); } deployer.undeploy("ProxyManagerTest"); } @Test @Category(UnstableTests.class) public void testRegisterWithGateWayWhenUserNameContainHost() throws ParseException, InterruptedException, SQLException { deployer.deploy("ProxyManagerTest"); SipURI uri = augustSipStack.getAddressFactory().createSipURI(null, restcommContact); final String userName = "[email protected]:" + augustPort; String deploymentUrl = "http://127.0.0.1:"+ restcommHTTPPort +"/restcomm/"; RestcommCallsTool.getInstance().setGateWay(deploymentUrl, adminAccountSid, adminAuthToken, "friendlyName", userName, "abcdef", "127.0.0.1:" + imsPort, true, "3600"); imsAugustPhone.listenRequestMessage(); RequestEvent requestEvent = imsAugustPhone.waitRequest(30000); assertNotNull(requestEvent); assertTrue(requestEvent.getRequest() != null); try { Response response = imsSipStack.getMessageFactory().createResponse(401, requestEvent.getRequest()); WWWAuthenticateHeader wwwAuthenticateHeader = imsSipStack.getHeaderFactory().createWWWAuthenticateHeader("Digest realm=\"ims.tp.pl\",\n" + " nonce=\"b7c9036dbf357f7683f054aea940e9703dc8f84c1108\",\n" + " opaque=\"ALU:QbkRBthOEgEQAkgVEwwHRAIBHgkdHwQCQ1lFRkZWDhMyIXBqLCs0Zj06ZTwhdHpgZmI_\",\n" + " algorithm=MD5,\n" + " qop=\"auth\""); response.setHeader(wwwAuthenticateHeader); ContactHeader contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); requestEvent = imsAugustPhone.waitRequest(10000); response = imsSipStack.getMessageFactory().createResponse(200, requestEvent.getRequest()); Authorization auth = (Authorization)requestEvent.getRequest().getHeader(Authorization.NAME); ContactHeader contHeader = (ContactHeader) requestEvent.getRequest().getHeader(ContactHeader.NAME); assertNotNull(auth); assertTrue(auth.getUsername().equals(userName)); assertTrue(contHeader.toString().contains("[email protected]:" + restcommPort)); contactHeader = augustSipStack.getHeaderFactory().createContactHeader(); contactHeader.setExpires(600); contactHeader.setAddress(augustSipStack.getAddressFactory().createAddress(imsContact)); response.addHeader(contactHeader); imsAugustPhone.sendReply(requestEvent, response); } catch (ParseException e) { e.printStackTrace(); fail(e.getMessage()); }catch (InvalidArgumentException e) { e.printStackTrace(); fail(e.getMessage()); } } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Deployment(name = "ProxyManagerTest", managed = false, testable = false) public static WebArchive createWebArchive() { reconfigurePorts(); Map<String,String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5060", String.valueOf(imsPort)); replacements.put("5092", String.valueOf(augustPort)); List<String> resources = new ArrayList(Arrays.asList("dial-client-entry_wActionUrl.xml")); return WebArchiveUtil.createWebArchiveNoGw("restcomm.xml", "restcomm.script",resources, replacements); } }
8,489
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallPushNotificationServerTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/push/CallPushNotificationServerTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.telephony.push; import com.github.tomakehurst.wiremock.http.RequestListener; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.CreateClientsTool; import javax.sip.address.SipURI; import javax.sip.message.Response; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.UnstableTests; /** * @author [email protected] (Oleg Agafonov) */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CallPushNotificationServerTest { private final static Logger logger = Logger.getLogger(CallPushNotificationServerTest.class.getName()); private static final String BODY = new String(new byte[]{ 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }); private static final String CLIENT_PASSWORD = "qwerty1234RT"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); @ArquillianResource URL deploymentUrl; private static SipStackTool tool1; private static SipStackTool tool2; private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("CallPushNotificationServerTest1"); tool2 = new SipStackTool("CallPushNotificationServerTest2"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); } @After @SuppressWarnings("Duplicates") public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>"; @Test @Category(UnstableTests.class) public void testRcmlCall() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); stubFor(post(urlPathEqualTo("/api/notifications")) .withHeader("Content-Type", matching("application/json;.*")) .willReturn(aResponse() .withStatus(200))); final SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); wireMockRule.addMockServiceRequestListener(new RequestListener() { @Override public void requestReceived(com.github.tomakehurst.wiremock.http.Request request, com.github.tomakehurst.wiremock.http.Response response) { if (request.getAbsoluteUrl().contains("/api/notifications") && response.getStatus() == 200) { assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); } } }); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, BODY, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(4000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); verify(postRequestedFor(urlEqualTo("/api/notifications"))); } @Test public void testB2BUACall() throws ParseException, InterruptedException, IOException { stubFor(post(urlPathEqualTo("/api/notifications")) .withHeader("Content-Type", matching("application/json;.*")) .willReturn(aResponse() .withStatus(200))); final SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); wireMockRule.addMockServiceRequestListener(new RequestListener() { @Override public void requestReceived(com.github.tomakehurst.wiremock.http.Request request, com.github.tomakehurst.wiremock.http.Response response) { if (request.getAbsoluteUrl().contains("/api/notifications") && response.getStatus() == 200) { assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); } } }); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "bob", CLIENT_PASSWORD, null); Credential c = new Credential("127.0.0.1", "bob", CLIENT_PASSWORD); bobPhone.addUpdateCredential(c); assertTrue(bobPhone.register(uri, "bob", CLIENT_PASSWORD, bobContact, 3600, 3600)); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, aliceContact, null, BODY, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(3000)); assertTrue(aliceCall.waitForIncomingCall(5000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp", null, null)); int response; do { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: " + response); } while (response == Response.TRYING); assertEquals(Response.RINGING, response); logger.info("Last response: " + response); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForAck(5000)); Thread.sleep(4000); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); Thread.sleep(500); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); verify(postRequestedFor(urlEqualTo("/api/notifications"))); } @SuppressWarnings("Duplicates") @Deployment(name = "CallPushNotificationServerTest", testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + Version.getVersion()).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.delete("/WEB-INF/classes/application.conf"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_pushNotificationServer.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_pushNotificationServer", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); archive.addAsWebResource("dial-client-entry_wActionUrl.xml"); logger.info("Packaged Test App"); return archive; } }
13,059
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OutboundBlockingExtensionTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/extensions/OutboundBlockingExtensionTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.extensions; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; import com.sun.jersey.api.client.UniformInterfaceException; import java.io.IOException; import java.net.URISyntaxException; import org.cafesip.sipunit.Credential; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.testsuite.sms.SmsEndpointTool; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; /** * Test for Dial Action attribute. Reference: * https://www.twilio.com/docs/api/twiml/dial#attributes-action The 'action' * attribute takes a URL as an argument. When the dialed call ends, Restcomm * will make a GET or POST request to this URL * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value = {ParallelClassTests.class}) public class OutboundBlockingExtensionTest { private final static Logger logger = Logger.getLogger(OutboundBlockingExtensionTest.class.getName()); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static SipStackTool tool1; private static SipStackTool tool2; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/"; private static String toUnresolvedNumber1 = "+19194347"; private static String toUnresolvedNumber2 = "+69194347"; private static String from = "9999"; private static String msgBody1 = "Hello1!"; private String allowBaseURL = "2012-04-24/Accounts/" + adminAccountSid + "/AvailablePhoneNumbers/"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } private String dialAliceRcml = "<Response><Dial><Client>alice1</Client></Dial></Response>"; @Test public void testOutboundVoiceBlocked() throws ParseException, InterruptedException, MalformedURLException, IOException, URISyntaxException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice1", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); assertTrue(bobCall.sendInviteOkAck()); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String smsRcml = "<Response><Sms to=\"alice1\">Hello World!</Sms></Response>"; @Test @Category(value = {FeatureAltTests.class}) public void testOutboundSmsRcmlBlocked() throws ParseException, IOException, URISyntaxException { stubFor(get(urlPathEqualTo("/smsApp1")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(smsRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice1", "1234", aliceContact, 3600, 3600)); Credential credential = new Credential("127.0.0.1", "alice1", "1234"); alicePhone.addUpdateCredential(credential); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); // Wait for a response sms. alicePhone.setLoopback(true); aliceCall.listenForMessage(); // // Send restcomm an sms. final String proxy = bobPhone.getStackAddress() + ":" + restcommPort + ";lr/udp"; final String to = "sip:6666@" + restcommContact; final String smsBody = "Hello, waiting your response!"; final SipCall call = bobPhone.createSipCall(); call.initiateOutgoingMessage(bobContact, to, proxy, null, null, smsBody); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, call.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + call.getLastReceivedResponse().getStatusCode()); } assertTrue(!aliceCall.waitForMessage(5000)); } @Test @Category(value = {FeatureAltTests.class}) public void testOutboundSmsEndpoint() throws ParseException, IOException, URISyntaxException { JsonObject callResult; try { callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, toUnresolvedNumber1, msgBody1, null); fail("expected error response"); } catch (UniformInterfaceException e) { assertEquals(403, e.getResponse().getStatus()); } try { callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, toUnresolvedNumber2, msgBody1, null); fail("expected error response"); } catch (UniformInterfaceException e) { assertEquals(403, e.getResponse().getStatus()); } } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String, String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); Map<String, String> webInfResources = new HashMap(); webInfResources.put("org/restcomm/connect/testsuite/extensions/restcomm.xml", "conf/restcomm.xml"); webInfResources.put("org/restcomm/connect/testsuite/extensions/restcomm.script", "data/hsql/restcomm.script"); webInfResources.put("akka_application.conf", "classes/application.conf"); webInfResources.put("sip.xml", "/sip.xml"); webInfResources.put("web.xml", "web.xml"); webInfResources.put("org/restcomm/connect/testsuite/extensions/extensions_outbound_blocking.xml", "conf/extensions.xml"); return WebArchiveUtil.createWebArchiveNoGw( webInfResources, new ArrayList(), replacements); } }
14,350
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BlockingExtensionTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/extensions/BlockingExtensionTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.extensions; import com.cloudhopper.commons.charset.CharsetUtil; import com.cloudhopper.smpp.type.SmppInvalidArgumentException; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import java.net.MalformedURLException; import java.net.URL; import java.text.ParseException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import junit.framework.Assert; import org.cafesip.sipunit.Credential; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.restcomm.connect.testsuite.provisioning.number.nexmo.NexmoIncomingPhoneNumbersEndpointTestUtils; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.testsuite.http.NotificationEndpointTool; import org.restcomm.connect.testsuite.provisioning.number.nexmo.NexmoAvailablePhoneNumbersEndpointTestUtils; import org.restcomm.connect.testsuite.smpp.MockSmppServer; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; /** * Test for Dial Action attribute. Reference: * https://www.twilio.com/docs/api/twiml/dial#attributes-action The 'action' * attribute takes a URL as an argument. When the dialed call ends, Restcomm * will make a GET or POST request to this URL * * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value = {ParallelClassTests.class}) public class BlockingExtensionTest { private final static Logger logger = Logger.getLogger(BlockingExtensionTest.class.getName()); private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10}; private static final String body = new String(bytes); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(mockPort); private static int smppPort = NetworkPortAssigner.retrieveNextPortByFile(); private static MockSmppServer mockSmppServer; private static SipStackTool tool1; private static SipStackTool tool2; // Bob is a simple SIP Client. Will not register with Restcomm private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/"; private static String toUnresolvedNumber1 = "+19194347"; private static String toUnresolvedNumber2 = "+69194347"; private static String from = "9999"; private static String msgBody1 = "Hello1!"; private String allowBaseURL = "2012-04-24/Accounts/" + adminAccountSid + "/AvailablePhoneNumbers/"; private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("DialActionTest1"); tool2 = new SipStackTool("DialActionTest2"); mockSmppServer = new MockSmppServer(smppPort); logger.info("Will wait for the SMPP link to be established"); do { Thread.sleep(1000); } while (!mockSmppServer.isLinkEstablished()); logger.info("SMPP link is now established"); } public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); mockSmppServer.cleanup(); Thread.sleep(5000); } @AfterClass public static void cleanup() { if (mockSmppServer != null) { mockSmppServer.stop(); } } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @AfterClass public static void afterClass() { System.gc(); System.out.println("System.gc() run"); } private String dialAliceRcml = "<Response><Dial><Client>alice1</Client></Dial></Response>"; @Test public void inboundRcmlVoiceBlocked() throws ParseException, InterruptedException, MalformedURLException { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAliceRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice1", "1234", aliceContact, 3600, 3600)); // Prepare second phone to receive call SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Create outgoing call with first phone final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:1111@" + restcommContact, null, body, "application", "sdp", null, null); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + bobCall.getLastReceivedResponse().getStatusCode()); } JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String smsRcml = "<Response><Sms to=\"alice1\">Hello World!</Sms></Response>"; @Test @Category(value = {FeatureAltTests.class}) public void inboundRcmlSmsBlocked() throws ParseException { stubFor(get(urlPathEqualTo("/smsApp1")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(smsRcml))); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice1", "1234", aliceContact, 3600, 3600)); Credential credential = new Credential("127.0.0.1", "alice1", "1234"); alicePhone.addUpdateCredential(credential); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); // Wait for a response sms. alicePhone.setLoopback(true); aliceCall.listenForMessage(); // // Send restcomm an sms. final String proxy = bobPhone.getStackAddress() + ":" + restcommPort + ";lr/udp"; final String to = "sip:6666@" + restcommContact; final String smsBody = "Hello, waiting your response!"; final SipCall call = bobPhone.createSipCall(); call.initiateOutgoingMessage(bobContact, to, proxy, null, null, smsBody); assertTrue(call.waitOutgoingCallResponse(5 * 1000)); final int response = call.getLastReceivedResponse().getStatusCode(); if (response == Response.TRYING) { assertTrue(call.waitOutgoingCallResponse(5 * 1000)); } assertEquals(Response.FORBIDDEN, call.getLastReceivedResponse().getStatusCode()); logger.info("Last response: " + call.getLastReceivedResponse().getStatusCode()); } @Test public void incomingPhoneBlocked() throws Exception { stubFor(post(urlMatching("/nexmo/number/buy/.*/.*/US/14156902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlMatching("/nexmo/number/update/.*/.*/US/14156902867.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); Assert.assertEquals(403, clientResponse.getStatus()); } private static String to = "9999"; private static String msgBodyResp = "Response from Restcomm to SMPP server"; private static String msgBody = "Message from SMPP Server to Restcomm"; private String smsEchoRcml = "<Response><Sms to=\"" + from + "\" from=\"" + to + "\">" + msgBodyResp + "</Sms></Response>"; @Test public void inboundSMPPBlocked() throws SmppInvalidArgumentException, IOException, InterruptedException { stubFor(get(urlPathEqualTo("/smsApp")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(smsEchoRcml))); mockSmppServer.sendSmppMessageToRestcomm(msgBody, to, from, CharsetUtil.CHARSET_GSM); Thread.sleep(2000); assertTrue(mockSmppServer.isMessageSent()); Thread.sleep(2000); assertFalse(mockSmppServer.isMessageReceived()); JsonObject notifications = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken ); JsonArray notArray = notifications.get("notifications").getAsJsonArray(); assertTrue("notification 11011 expected", notArray.size() > 0); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-1 * available local phone numbers in the United States in the 510 area code. */ @Test @Category(FeatureAltTests.class) public void avaiPhoneNumBlocked() { stubFor(get(urlMatching("/nexmo/number/search/.*/.*/CA\\?pattern=1450&search_pattern=0")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(NexmoAvailablePhoneNumbersEndpointTestUtils.bodyCA450AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + allowBaseURL + "CA/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("AreaCode", "450").accept("application/json") .get(ClientResponse.class); assertEquals(403, clientResponse.getStatus()); } @Deployment(name = "DialAction", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String, String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("2776", String.valueOf(smppPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(mockPort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5090", String.valueOf(bobPort)); replacements.put("5091", String.valueOf(alicePort)); Map<String, String> webInfResources = new HashMap(); webInfResources.put("org/restcomm/connect/testsuite/extensions/restcomm.xml", "conf/restcomm.xml"); webInfResources.put("org/restcomm/connect/testsuite/extensions/restcomm.script", "data/hsql/restcomm.script"); webInfResources.put("akka_application.conf", "classes/application.conf"); webInfResources.put("sip.xml", "/sip.xml"); webInfResources.put("web.xml", "web.xml"); webInfResources.put("org/restcomm/connect/testsuite/extensions/extensions_blocking.xml", "conf/extensions.xml"); return WebArchiveUtil.createWebArchiveNoGw( webInfResources, new ArrayList(), replacements); } }
18,645
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApplicationsEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/ApplicationsEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; import javax.ws.rs.core.MultivaluedMap; import junit.framework.Assert; import org.apache.http.client.ClientProtocolException; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.dao.Sid; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.UnstableTests; /** * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ApplicationsEndpointTest { private final static Logger logger = Logger.getLogger(ApplicationsEndpointTest.class); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @After public void after() throws InterruptedException { Thread.sleep(1000); } @Test @Category(UnstableTests.class) public void testCreateAndGetApplication() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { // Define application attributes String friendlyName, voiceCallerIdLookup, rcmlUrl, kind; // Test create application via POST MultivaluedMap<String, String> applicationParams = new MultivaluedMapImpl(); applicationParams.add("FriendlyName", friendlyName = "APPCreateGet"); applicationParams.add("VoiceCallerIdLookup", voiceCallerIdLookup = "true"); applicationParams.add("RcmlUrl", rcmlUrl = "/restcomm/rcmlurl/test"); applicationParams.add("Kind", kind = "voice"); JsonObject applicationJson = RestcommApplicationsTool.getInstance().createApplication(deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, applicationParams); Sid applicationSid = new Sid(applicationJson.get("sid").getAsString()); // Test asserts via GET to a single application applicationJson = RestcommApplicationsTool.getInstance().getApplication(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid.toString()); SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); assertTrue(df.parse(applicationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(applicationJson.get("date_updated").getAsString()) != null); assertTrue(applicationJson.get("friendly_name").getAsString().equals(friendlyName)); assertTrue(applicationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(applicationJson.get("api_version").getAsString().equals("2012-04-24")); assertTrue(applicationJson.get("voice_caller_id_lookup").getAsString().equals(voiceCallerIdLookup)); assertTrue(applicationJson.get("rcml_url").getAsString().equals(rcmlUrl)); assertTrue(applicationJson.get("kind").getAsString().equals(kind)); // Test asserts via GET to a application list JsonArray applicationsListJson = RestcommApplicationsTool.getInstance().getApplications(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid); applicationJson = applicationsListJson.get(0).getAsJsonObject(); assertTrue(df.parse(applicationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(applicationJson.get("date_updated").getAsString()) != null); assertTrue(applicationJson.get("friendly_name").getAsString().equals(friendlyName)); assertTrue(applicationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(applicationJson.get("api_version").getAsString().equals("2012-04-24")); assertTrue(applicationJson.get("voice_caller_id_lookup").getAsString().equals(voiceCallerIdLookup)); assertTrue(applicationJson.get("rcml_url").getAsString().equals(rcmlUrl)); assertTrue(applicationJson.get("kind").getAsString().equals(kind)); } @Test public void testGetApplicationAndNumbers() throws ParseException, IllegalArgumentException, IOException { // Define application attributes String friendlyName, voiceCallerIdLookup, rcmlUrl, kind; // Test asserts via GET to a single application JsonArray applicationJson = RestcommApplicationsTool.getInstance().getApplications(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, true); Assert.assertNotNull(applicationJson.get(0).getAsJsonObject().get("numbers")); JsonObject number = applicationJson.get(0).getAsJsonObject().get("numbers").getAsJsonArray().get(0).getAsJsonObject(); Assert.assertEquals("+1240",number.get("phone_number").getAsString()); Assert.assertEquals("AP73926e7113fa4d95981aa96b76eca854", number.get("voice_application_sid").getAsString()); } @Test public void testUpdateApplication() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { // Create application MultivaluedMap<String, String> applicationParams = new MultivaluedMapImpl(); applicationParams.add("FriendlyName", "APPUpdate"); applicationParams.add("VoiceCallerIdLookup", "true"); applicationParams.add("RcmlUrl", "/restcomm/rcmlurl/test"); applicationParams.add("Kind", "voice"); JsonObject applicationJson = RestcommApplicationsTool.getInstance().createApplication(deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, applicationParams); Sid applicationSid = new Sid(applicationJson.get("sid").getAsString()); // Define new values to the application attributes (POST test) String friendlyName, voiceCallerIdLookup, rcmlUrl, kind; MultivaluedMap<String, String> applicationParamsUpdate = new MultivaluedMapImpl(); applicationParamsUpdate.add("FriendlyName", friendlyName = "APPUpdate2"); applicationParamsUpdate.add("VoiceCallerIdLookup", voiceCallerIdLookup = "false"); applicationParamsUpdate.add("RcmlUrl", rcmlUrl = "/restcomm/rcmlurl/test2"); applicationParamsUpdate.add("Kind", kind = "voice"); // Update application via POST RestcommApplicationsTool.getInstance().updateApplication(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid.toString(), applicationParamsUpdate, false); // Test asserts via GET to a single application applicationJson = RestcommApplicationsTool.getInstance().getApplication(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid.toString()); SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); assertTrue(df.parse(applicationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(applicationJson.get("date_updated").getAsString()) != null); assertTrue(applicationJson.get("friendly_name").getAsString().equals(friendlyName)); assertTrue(applicationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(applicationJson.get("api_version").getAsString().equals("2012-04-24")); assertTrue(applicationJson.get("voice_caller_id_lookup").getAsString().equals(voiceCallerIdLookup)); assertTrue(applicationJson.get("rcml_url").getAsString().equals(rcmlUrl)); assertTrue(applicationJson.get("kind").getAsString().equals(kind)); // Define new values to the application attributes (PUT test) applicationParamsUpdate = new MultivaluedMapImpl(); applicationParamsUpdate.add("FriendlyName", friendlyName = "APPUpdate23"); applicationParamsUpdate.add("VoiceCallerIdLookup", voiceCallerIdLookup = "true"); applicationParamsUpdate.add("RcmlUrl", rcmlUrl = "/restcomm/rcmlurl/test23"); applicationParamsUpdate.add("Kind", kind = "voice"); // Update application via PUT RestcommApplicationsTool.getInstance().updateApplication(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid.toString(), applicationParamsUpdate, true); // Test asserts via GET to a single application applicationJson = RestcommApplicationsTool.getInstance().getApplication(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid.toString()); assertTrue(df.parse(applicationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(applicationJson.get("date_updated").getAsString()) != null); assertTrue(applicationJson.get("friendly_name").getAsString().equals(friendlyName)); assertTrue(applicationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(applicationJson.get("api_version").getAsString().equals("2012-04-24")); assertTrue(applicationJson.get("voice_caller_id_lookup").getAsString().equals(voiceCallerIdLookup)); assertTrue(applicationJson.get("rcml_url").getAsString().equals(rcmlUrl)); assertTrue(applicationJson.get("kind").getAsString().equals(kind)); } @Test public void testDeleteApplication() throws IllegalArgumentException, ClientProtocolException, IOException { // Create application MultivaluedMap<String, String> applicationParams = new MultivaluedMapImpl(); applicationParams.add("FriendlyName", "APPDelete"); applicationParams.add("VoiceCallerIdLookup", "true"); applicationParams.add("RcmlUrl", "/restcomm/rcmlurl/test"); applicationParams.add("Kind", "voice"); JsonObject applicationJson = RestcommApplicationsTool.getInstance().createApplication(deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, applicationParams); Sid applicationSid = new Sid(applicationJson.get("sid").getAsString()); // Delete application RestcommApplicationsTool.getInstance().deleteApplication(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid.toString()); // Check if it was removed applicationJson = RestcommApplicationsTool.getInstance().getApplication(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid.toString()); assertTrue(applicationJson == null); } @Deployment(name = "ApplicationsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script-applications", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
13,603
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UssdPushTestMessages.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/UssdPushTestMessages.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ public class UssdPushTestMessages { static String ussdPushNotifyOnlyMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ussd-data>\n" + "<language value=\"en\"></language>\n" +"<ussd-string value=\"The information you requested is 1234567890\"></ussd-string>\n" +"<anyExt>\n" +"<message-type>unstructuredSSNotify_Request</message-type>\n" +"</anyExt>\n" +"</ussd-data>"; static String ussdPushNotifyOnlyClientResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ussd-data>\n" + "<language>en</language>\n" + "<ussd-string></ussd-string>\n" + "<anyExt>\n" + "<message-type>unstructuredSSNotify_Response</message-type>\n" + "</anyExt>\n" + "</ussd-data>"; static String ussdPushNotifyOnlyFinalResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ussd-data>\n" + "<error-code value=\"1\"></error-code>\n" + "</ussd-data>"; static String ussdPushCollectMessage = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<ussd-data>\n" + "<language value=\"en\"></language>\n" + "<ussd-string value=\"Please press\n1 For option1\n2 For option2\"></ussd-string>\n" + "<anyExt>\n" + "<message-type>unstructuredSSRequest_Request</message-type>\n" + "</anyExt>\n" + "</ussd-data>\n"; static String ussdPushCollectClientResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" + "<ussd-data>\n" + "\t<language value=\"en\"/>\n" + "\t<ussd-string value=\"1\"/>\n" + "\t<anyExt>\n" + "\t\t<message-type>unstructuredSSRequest_Response</message-type>\n" + "\t</anyExt>\n" + "</ussd-data>"; // <?xml version="1.0" encoding="UTF-8"?> // <ussd-data> // <language value="en"></language> // <ussd-string value="Please press // 1 For option1 // 2 For option2"></ussd-string> // <anyExt> // <message-type>unstructuredSSRequest_Request</message-type> // </anyExt> // </ussd-data> }
3,153
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallsEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/CallsEndpointTest.java
package org.restcomm.connect.testsuite.http; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.URL; import java.util.HashMap; import java.util.Map; import com.google.gson.JsonElement; import com.sun.jersey.api.client.UniformInterfaceException; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.joda.time.DateTime; import org.junit.Assert; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; /** * @author <a href="mailto:[email protected]">gvagenas</a> * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CallsEndpointTest { private final static Logger logger = Logger.getLogger(CallsEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String topLevelAccountSid = "AC00000000000000000000000000000000"; private String subAccount1 = "AC10000000000000000000000000000000"; private String subAccount2 = "AC20000000000000000000000000000000"; private String subAccount11 = "AC11000000000000000000000000000000"; private String subAccount111 = "AC11100000000000000000000000000000"; private String commonAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test public void getCallsList() { JsonObject firstPage = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageCallsArray = firstPage.get("calls").getAsJsonArray(); int firstPageCallsArraySize = firstPageCallsArray.size(); assertEquals(firstPageCallsArraySize, 50); assertEquals(firstPage.get("start").getAsInt(), 0); assertEquals(firstPage.get("end").getAsInt(), 49); JsonObject secondPage = (JsonObject) RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 2, null, null, true); JsonArray secondPageCallsArray = secondPage.get("calls").getAsJsonArray(); assertEquals(secondPageCallsArray.size(), 50); assertEquals(secondPage.get("start").getAsInt(), 100); assertEquals(secondPage.get("end").getAsInt(), 149); JsonObject lastPage = (JsonObject) RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, firstPage.get("num_pages").getAsInt(), null, null, true); JsonArray lastPageCallsArray = lastPage.get("calls").getAsJsonArray(); assertEquals(lastPageCallsArray.get(lastPageCallsArray.size() - 1).getAsJsonObject().get("sid").getAsString(), "CA22ac5fd16a954c339f33519bdfe4af78"); assertEquals(lastPageCallsArray.size(), 48); assertEquals(lastPage.get("start").getAsInt(), 400); assertEquals(lastPage.get("end").getAsInt(), 448); assertEquals(totalSize, 448); } @Test public void getCallsListUsingSorting() { // Provide both sort field and direction // Provide ascending sorting and verify that the first row is indeed the earliest one JsonObject response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "DateCreated:asc", true); // Remember there is a discrepancy between the sort parameters and the result attribute in the .json response. For example DateCreated:asc, means // to sort based of DateCreated field, but in the response the field is called 'date_created', not DateCreated. This only happens only for .json; in // .xml the naming seems to be respected. // Notice that we are removing the timezone part from the end of the string, because CI potentially uses different timezone that messes the test up assertEquals("Fri, 5 Jul 2013 22:15:53", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); // Provide only sort field; all fields default to ascending response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "DateCreated", true); assertEquals("Fri, 5 Jul 2013 22:15:53", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "DateCreated:desc", true); assertEquals("Tue, 31 May 2016 16:20:22", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); try { // provide only direction, should cause an exception RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, ":asc", true); } catch (UniformInterfaceException e) { assertEquals(BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); } try { // provide sort field and direction, but direction is invalid (neither of asc or desc) RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "DateCreated:invalid", true); } catch (UniformInterfaceException e) { assertEquals(BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); } // From response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "From:asc", true); assertEquals("+101133679364376", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("from").getAsString()); response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "From:desc", true); assertEquals("thomas", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("from").getAsString()); // To response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "To:asc", true); assertEquals("+13052406432", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("to").getAsString()); response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "To:desc", true); assertEquals("15126002188", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("to").getAsString()); // Direction response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "Direction:asc", true); assertEquals("inbound", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("direction").getAsString()); response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "Direction:desc", true); assertEquals("outbound", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("direction").getAsString()); // Status response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "Status:asc", true); assertEquals("completed", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("status").getAsString()); response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "Status:desc", true); assertEquals("ringing", ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("status").getAsString()); // TODO: need to improve Duration and Price assertions because right now there are so many NULL values in duration that are messing this up. We should // probably add non null values in all duration and price fields to make these work better // Duration response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "Duration:asc", true); assertEquals(null, ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("duration")); response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "Duration:desc", true); assertEquals(null, ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("duration")); // Price response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "Price:asc", true); assertEquals(null, ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("price")); response = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 10, "Price:desc", true); assertEquals(null, ((JsonObject)response.get("calls").getAsJsonArray().get(0)).get("price\"")); } @Test @Category(FeatureAltTests.class) public void getCallsListUsingPageSize() { JsonObject firstPage = (JsonObject) RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, null, 100, null, true); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageCallsArray = firstPage.get("calls").getAsJsonArray(); int firstPageCallsArraySize = firstPageCallsArray.size(); assertEquals(firstPageCallsArraySize, 100); assertEquals(firstPage.get("start").getAsInt(), 0); assertEquals(firstPage.get("end").getAsInt(), 99); JsonObject secondPage = (JsonObject) RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 2, 100, null, true); JsonArray secondPageCallsArray = secondPage.get("calls").getAsJsonArray(); assertEquals(secondPageCallsArray.size(), 100); assertEquals(secondPage.get("start").getAsInt(), 200); assertEquals(secondPage.get("end").getAsInt(), 299); JsonObject lastPage = (JsonObject) RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken, firstPage.get("num_pages").getAsInt(), 100, null, true); JsonArray lastPageCallsArray = lastPage.get("calls").getAsJsonArray(); assertEquals("CA22ac5fd16a954c339f33519bdfe4af78",lastPageCallsArray.get(lastPageCallsArray.size() - 1).getAsJsonObject().get("sid").getAsString()); assertEquals(lastPageCallsArray.size(), 48); assertEquals(lastPage.get("start").getAsInt(), 400); assertEquals(lastPage.get("end").getAsInt(), 448); assertEquals(totalSize, 448); } @Test @Category(FeatureAltTests.class) public void getCallsListFilteredByStatus() { Map<String, String> filters = new HashMap<String, String>(); filters.put("Status", "in-progress"); JsonObject allCallsObject = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject filteredCallsByStatusObject = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(filteredCallsByStatusObject.get("calls").getAsJsonArray().size(), 50); assertEquals(allCallsObject.get("start").getAsInt(), 0); assertEquals(allCallsObject.get("end").getAsInt(), 49); assertEquals(filteredCallsByStatusObject.get("start").getAsInt(), 0); assertEquals(filteredCallsByStatusObject.get("end").getAsInt(), 49); assertEquals(allCallsObject.get("calls").getAsJsonArray().size(), filteredCallsByStatusObject.get("calls") .getAsJsonArray().size()); } @Test @Category(FeatureAltTests.class) public void getCallsListFilteredBySender() { Map<String, String> filters = new HashMap<String, String>(); filters.put("From", "3021097%"); JsonObject allCalls = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject filteredCallsBySender = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(filteredCallsBySender.get("calls").getAsJsonArray().size(), 50); assertEquals(allCalls.get("start").getAsInt(), 0); assertEquals(allCalls.get("end").getAsInt(), 49); assertEquals(filteredCallsBySender.get("start").getAsInt(), 0); assertEquals(filteredCallsBySender.get("end").getAsInt(), 49); assertEquals(allCalls.get("calls").getAsJsonArray().size(), filteredCallsBySender.get("calls").getAsJsonArray().size()); } @Test @Category(FeatureAltTests.class) public void getCallsListFilteredByRecipient() { Map<String, String> filters = new HashMap<String, String>(); filters.put("To", "1512600%"); JsonObject allCalls = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject filteredCallsByRecipient = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(filteredCallsByRecipient.get("calls").getAsJsonArray().size(), 50); assertEquals(allCalls.get("calls").getAsJsonArray().size(), filteredCallsByRecipient.get("calls").getAsJsonArray() .size()); } @Test @Category(FeatureAltTests.class) public void getCallsListFilteredByStartTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("StartTime", "2013-08-23 14:30:07.820000000"); JsonObject allCalls = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject filteredCallsByStartTime = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredCallsByStartTime.get("calls").getAsJsonArray().size() > 0); assertEquals(allCalls.get("calls").getAsJsonArray().size(), filteredCallsByStartTime.get("calls").getAsJsonArray() .size()); } @Test @Category(FeatureAltTests.class) public void getCallsListFilteredByParentCallSid() { Map<String, String> filters = new HashMap<String, String>(); filters.put("ParentCallSid", "CA01a09068a1f348269b6670ef599a6e57"); JsonObject filteredCallsByParentCallSid = RestcommCallsTool.getInstance().getCallsUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(filteredCallsByParentCallSid.get("calls").getAsJsonArray().size(), 0); } @Test @Category(FeatureAltTests.class) public void getCallsListFilteredUsingMultipleFilters() { Map<String, String> filters = new HashMap<String, String>(); filters.put("StartTime", "2013-08-23 14:30:07.820000000"); filters.put("To", "1512600%"); filters.put("From", "3021097%"); filters.put("Status", "in-progress"); JsonObject allCalls = RestcommCallsTool.getInstance().getCalls(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject filteredCallsUsingMultipleFilters = RestcommCallsTool.getInstance().getCallsUsingFilter( deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredCallsUsingMultipleFilters.get("calls").getAsJsonArray().size() > 0); assertTrue(allCalls.get("calls").getAsJsonArray().size() > filteredCallsUsingMultipleFilters.get("calls") .getAsJsonArray().size()); } @Test @Category(FeatureAltTests.class) public void getCallsListIncludingSubAccounts() { Map<String, String> filters = new HashMap<String, String>(); filters.put("SubAccounts", "true"); // retrieve top-level account cdrs JsonObject calls = RestcommCallsTool.getInstance().getCallsUsingFilter( deploymentUrl.toString(), topLevelAccountSid, commonAuthToken, filters); assertEquals(50,calls.get("calls").getAsJsonArray().size()); // that's because of the default page size int totalSize = calls.get("total").getAsInt(); assertEquals(54, calls.get("total").getAsInt()); // retrieve second page too filters.put("Page", "1"); calls = RestcommCallsTool.getInstance().getCallsUsingFilter( deploymentUrl.toString(), topLevelAccountSid, commonAuthToken, filters); assertEquals(4, calls.get("calls").getAsJsonArray().size()); // 50 + 4 = 54 filters.remove("Page"); // no page for the rest of the cases // retrieve first level child account cdrs calls = RestcommCallsTool.getInstance().getCallsUsingFilter( deploymentUrl.toString(), subAccount1, commonAuthToken, filters); assertEquals(33,calls.get("calls").getAsJsonArray().size()); // retrieve first level child (with no grandchildren) account cdrs calls = RestcommCallsTool.getInstance().getCallsUsingFilter( deploymentUrl.toString(), subAccount2, commonAuthToken, filters); assertEquals(19,calls.get("calls").getAsJsonArray().size()); // retrieve second level child cdrs calls = RestcommCallsTool.getInstance().getCallsUsingFilter( deploymentUrl.toString(), subAccount11, commonAuthToken, filters); assertEquals(18,calls.get("calls").getAsJsonArray().size()); // retrieve third level child cdrs calls = RestcommCallsTool.getInstance().getCallsUsingFilter( deploymentUrl.toString(), subAccount111, commonAuthToken, filters); assertEquals(11,calls.get("calls").getAsJsonArray().size()); // retrieve all cdrs of [email protected] but using the SubAccount filter calls = RestcommCallsTool.getInstance().getCallsUsingFilter( deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(50,calls.get("calls").getAsJsonArray().size()); } @Test public void getCallRecordingsList() { String callWithRecordingsSid = "CAfe9ce46f104f4beeb10c83a5dad2be66"; JsonArray callRecordings = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callWithRecordingsSid ); assertEquals("Call recordings size() should be 1", 1, callRecordings.size()); String callWithoutRecordings = "CAfd82074503754b80aa8555199dfcc703"; callRecordings = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callWithoutRecordings ); assertEquals("Call recordings size() should be 0", 0, callRecordings.size()); } @Deployment(name = "ClientsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
21,607
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EmailEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/EmailEndpointTest.java
package org.restcomm.connect.testsuite.http; import com.icegreen.greenmail.util.GreenMail; import com.icegreen.greenmail.util.GreenMailUtil; import com.icegreen.greenmail.util.ServerSetupTest; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.email.api.Mail; import javax.mail.Message; import javax.mail.MessagingException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import java.io.IOException; import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Created by gvagenas on 1/12/16. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class EmailEndpointTest { private final static Logger logger = Logger.getLogger(CallsEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private GreenMail mailServer; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Before public void before() throws Exception { mailServer = new GreenMail(ServerSetupTest.SMTP); mailServer.setUser("hascode@localhost", "hascode", "abcdef123"); mailServer.start(); logger.info("MailServer started"); Thread.sleep(2000); } @After public void after() { mailServer.reset(); mailServer.stop(); } @Test public void sendEmailTest() throws MessagingException, IOException { final Mail emailMsg = new Mail("hascode@localhost", "[email protected]","Testing Email Service" ,"This is the subject of the email service testing", "[email protected], [email protected], [email protected]", "[email protected], [email protected]"); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminAccountSid, adminAuthToken)); String url = deploymentUrl + "2012-04-24/Accounts/" + adminAccountSid + "/Email/Messages.json"; WebResource webResource = jerseyClient.resource(url); final String subject = "Test Email Subject"; final String body = "Test body"; MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("From", "[email protected]"); params.add("To", "[email protected]"); params.add("Subject", subject ); params.add("Body", body); // webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); assertNotNull(response); logger.info("Response: "+response); assertTrue(mailServer.waitForIncomingEmail(1)); Message[] messages = mailServer.getReceivedMessages(); assertEquals(1, messages.length); assertEquals(subject, messages[0].getSubject()); assertEquals(body, GreenMailUtil.getBody(messages[0]).trim()); } @Deployment(name = "EmailEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-EmailEndpoint.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
4,986
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ExtensionsConfigurationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/ExtensionsConfigurationTest.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import javax.ws.rs.core.MultivaluedMap; import java.io.UnsupportedEncodingException; import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * Created by gvagenas on 27/10/2016. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ExtensionsConfigurationTest { private final static Logger logger = Logger.getLogger(ExtensionsConfigurationTest.class.getName()); private static final String version = Version.getVersion(); private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String jsonConfiguration = "{\n" + " \"extension_name\": \"testExtension\",\n" + " \"option1\": \"true\",\n" + " \"option2\": \"20\",\n" + " \"option3\": \"false\",\n" + " \"setOfOptions\": {\n" + " \"subOption1\": \"true\",\n" + " \"subOption2\": \"50\"\n" + " },\n" + " \"enabed\": \"true\"\n" + "}"; private String updatedJsonConfiguration = "{\n" + " \"extension_name\": \"testExtension\",\n" + " \"option1\": \"false\",\n" + " \"option2\": \"40\",\n" + " \"option3\": \"true\",\n" + " \"setOfOptions\": {\n" + " \"subOption1\": \"false\",\n" + " \"subOption2\": \"100\"\n" + " },\n" + " \"enabed\": \"true\"\n" + "}"; @Test public void testCreateAndUpdateJsonConfiguration() throws UnsupportedEncodingException { String extensionName = "testExtension"; MultivaluedMap<String, String> configurationParams = new MultivaluedMapImpl(); configurationParams.add("ExtensionName", extensionName); configurationParams.add("ConfigurationData", jsonConfiguration); JsonObject response = RestcommExtensionsConfigurationTool.getInstance().postConfiguration(deploymentUrl.toString(), adminAccountSid, adminAuthToken, configurationParams); assertNotNull(response); JsonObject extension = RestcommExtensionsConfigurationTool.getInstance().getConfiguration(deploymentUrl.toString(), adminAccountSid, adminAuthToken, extensionName); assertNotNull(extension); String receivedConf = extension.get("configuration").getAsString(); assertEquals(jsonConfiguration, receivedConf); String extensionSid = extension.get("sid").getAsString(); MultivaluedMap<String, String> updatedConfigurationParams = new MultivaluedMapImpl(); updatedConfigurationParams.add("ExtensionName", extensionName); updatedConfigurationParams.add("ConfigurationData", updatedJsonConfiguration); JsonObject updatedExtension = RestcommExtensionsConfigurationTool.getInstance().updateConfiguration(deploymentUrl.toString(), adminAccountSid, adminAuthToken, extensionSid, updatedConfigurationParams); assertNotNull(updatedExtension); String updatedReceveivedConf = updatedExtension.get("configuration").getAsString(); assertEquals(updatedJsonConfiguration, updatedReceveivedConf); } @Test public void testCreateJsonConfigurationAndGetBySid() throws UnsupportedEncodingException { String extensionName = "testExtension2"; MultivaluedMap<String, String> configurationParams = new MultivaluedMapImpl(); configurationParams.add("ExtensionName", extensionName); configurationParams.add("ConfigurationData", jsonConfiguration); JsonObject response = RestcommExtensionsConfigurationTool.getInstance().postConfiguration(deploymentUrl.toString(), adminAccountSid, adminAuthToken, configurationParams); assertNotNull(response); JsonObject extension = RestcommExtensionsConfigurationTool.getInstance().getConfiguration(deploymentUrl.toString(), adminAccountSid, adminAuthToken, extensionName); assertNotNull(extension); String receivedConf = extension.get("configuration").getAsString(); assertEquals(jsonConfiguration, receivedConf); String extensionSid = extension.get("sid").getAsString(); JsonObject extensionBySid = RestcommExtensionsConfigurationTool.getInstance().getConfiguration(deploymentUrl.toString(), adminAccountSid, adminAuthToken, extensionSid); assertNotNull(extensionBySid); assertEquals(jsonConfiguration, extensionBySid.get("configuration").getAsString()); } @Deployment(name = "ExtensionsConfigurationTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("restcomm.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
6,384
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IncomingPhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/IncomingPhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2018, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.restcomm.connect.testsuite.http; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.Version; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import java.net.URL; import static org.junit.Assert.assertTrue; /** * @author gvagenas ([email protected]) */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class IncomingPhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(IncomingPhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource URL deploymentUrl; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/"; private String migrateURL = "2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acg/"; private String adminOrg2Username = "[email protected]"; private String adminOrg2AccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; private String adminOrg2AuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURLOrg2 = "2012-04-24/Accounts/" + adminOrg2AccountSid + "/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 String number1 = "9966"; String number2 = "9977"; @Test public void testCreateSipNumberOrg1 () { // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", number1); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); formData.add("isSIP", "true"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); } @Test public void testCreateSipNumberOrg2 () { // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminOrg2Username, adminOrg2AuthToken)); String provisioningURL = deploymentUrl + baseURLOrg2 + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", number1); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); formData.add("isSIP", "true"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); } @Test public void testCreateSipNumberTwoOrgs () { // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", number2); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); formData.add("isSIP", "true"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); Client jerseyClient2 = Client.create(); jerseyClient2.addFilter(new HTTPBasicAuthFilter(adminOrg2Username, adminOrg2AuthToken)); String provisioningURL2 = deploymentUrl + baseURLOrg2 + "IncomingPhoneNumbers.json"; WebResource webResource2 = jerseyClient2.resource(provisioningURL2); MultivaluedMap<String, String> formData2 = new MultivaluedMapImpl(); formData2.add("PhoneNumber", number2); formData2.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData2.add("FriendlyName", "My Company Line"); formData2.add("VoiceMethod", "GET"); formData2.add("isSIP", "true"); ClientResponse clientResponse2 = webResource2.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE) .accept("application/json").post(ClientResponse.class, formData2); assertTrue(clientResponse2.getStatus() == 200); String response2 = clientResponse2.getEntity(String.class); logger.info(response2); assertTrue(!response2.trim().equalsIgnoreCase("[]")); JsonObject jsonResponse2 = parser.parse(response2).getAsJsonObject(); logger.info(jsonResponse2.toString()); } @Deployment(name = "IncomingPhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw () { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
9,532
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RoleSensitiveTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/RoleSensitiveTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2016, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Assert; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.FeatureExpTests; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; /** * Selective testing (relies on accounts endpoint only) that involves accounts, roles and permissions. * * @author Orestis Tsakiridis */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RoleSensitiveTest extends EndpointTest { protected final static Logger logger = Logger.getLogger(RoleSensitiveTest.class); static String developerSid = "AC11111111111111111111111111111111"; static String developerUsername = "[email protected]"; static String developerAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; static String userSid = "AC22222222222222222222222222222222"; static String userUsername = "[email protected]"; static String userAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; static String powerUserSid = "AC33333333333333333333333333333333"; static String powerUserUsername = "[email protected]"; static String powerUserAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; static String guestSid = "AC44444444444444444444444444444444"; static String guestUsername = "[email protected]"; static String guestAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test @Category(FeatureExpTests.class) public void testSinglePermissionAccess() { // user can read his account Client jersey = getClient(userUsername, userAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/" + userSid) ); ClientResponse response = resource.get(ClientResponse.class); Assert.assertEquals("[email protected] cannot read his account", 200, response.getStatus()); // user is refused access when missing permission resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + userSid + ".json") ); MultivaluedMap<String, String> applicationParams = new MultivaluedMapImpl(); applicationParams.add("FriendlyName", "Test User UPDATED"); response = resource.accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, applicationParams); Assert.assertEquals(403, response.getStatus()); } @Test @Category(FeatureExpTests.class) public void testSiblingAccountPermissionAccess() { // user cannot read sibling account although he has Accounts:Read permission Client jersey = getClient(userUsername, userAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/" + developerSid) ); ClientResponse response = resource.get(ClientResponse.class); Assert.assertEquals(403, response.getStatus()); } @Test public void testStarPermission() { // power user can read his account Client jersey = getClient(powerUserUsername, powerUserAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/" + powerUserSid) ); ClientResponse response = resource.get(ClientResponse.class); Assert.assertEquals(200, response.getStatus()); // power user is refused access when missing permission resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/" + powerUserSid) ); MultivaluedMap<String, String> applicationParams = new MultivaluedMapImpl(); applicationParams.add("FriendlyName", "Test User UPDATED"); response = resource.accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, applicationParams); Assert.assertEquals(200, response.getStatus()); } @Test @Category(FeatureExpTests.class) public void testNoPermissions() { // guest cannot read his account Client jersey = getClient(guestUsername, guestAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/" + guestSid) ); ClientResponse response = resource.get(ClientResponse.class); Assert.assertEquals(403, response.getStatus()); } @Deployment(name = "RoleSensitiveTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_roles_permissions.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_roles_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
6,716
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GatewaysEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/GatewaysEndpointTest.java
package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.text.ParseException; import org.apache.http.client.ClientProtocolException; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import com.google.gson.JsonObject; import org.restcomm.connect.commons.Version; /** * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class GatewaysEndpointTest { private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String gwName = "MyGateway"; private String gwUsername = "myusername"; private String gwPassword = "mypassword"; private String gwProxy = "127.0.0.1:5090"; private String gwRegister = "true"; private String gwTTL = "3600"; @Before public void before() throws Exception { } @After public void after() throws Exception { } //Restcomm will try to register the Gateway but this will fail, we ignore that for now. @Test public void createGatewayTest() throws ClientProtocolException, IOException, ParseException, InterruptedException { JsonObject gateway = CreateGatewaysTool.getInstance().createGateway(deploymentUrl.toString(), gwName, gwUsername , gwPassword, gwProxy, gwRegister, gwTTL); assertNotNull(gateway); assertNotNull(gateway.get("sid").getAsString()); assertTrue(gwName.equalsIgnoreCase(gateway.get("friendly_name").getAsString())); assertTrue(gwUsername.equalsIgnoreCase(gateway.get("user_name").getAsString())); assertTrue(gwPassword.equalsIgnoreCase(gateway.get("password").getAsString())); String sid = gateway.get("sid").getAsString(); CreateGatewaysTool.getInstance().deleteGateway(deploymentUrl.toString(), sid); } //Restcomm will try to register the Gateway but this will fail, we ignore that for now. @Test public void updateGatewayTest() throws ClientProtocolException, IOException, ParseException, InterruptedException { JsonObject gateway = CreateGatewaysTool.getInstance().createGateway(deploymentUrl.toString(), gwName, gwUsername , gwPassword, gwProxy, gwRegister, gwTTL); assertNotNull(gateway); assertNotNull(gateway.get("sid").getAsString()); assertTrue(gwName.equalsIgnoreCase(gateway.get("friendly_name").getAsString())); assertTrue(gwUsername.equalsIgnoreCase(gateway.get("user_name").getAsString())); assertTrue(gwPassword.equalsIgnoreCase(gateway.get("password").getAsString())); String sid = gateway.get("sid").getAsString(); String newName = "MyNewGatewayName"; JsonObject updatedGateway = CreateGatewaysTool.getInstance().updateGateway(deploymentUrl.toString(), sid, newName, null, null, null, null, null); assertNotNull(updatedGateway); assertTrue(newName.equalsIgnoreCase(updatedGateway.get("friendly_name").getAsString())); assertTrue(gwUsername.equalsIgnoreCase(updatedGateway.get("user_name").getAsString())); assertTrue(gwPassword.equalsIgnoreCase(updatedGateway.get("password").getAsString())); String newSid = updatedGateway.get("sid").getAsString(); assertTrue(sid.equals(newSid)); CreateGatewaysTool.getInstance().deleteGateway(deploymentUrl.toString(), sid); } @Deployment(name = "ClientsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script", "data/hsql/restcomm.script"); return archive; } }
5,077
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateCallsTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/CreateCallsTest.java
package org.restcomm.connect.testsuite.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import javax.sip.address.SipURI; import javax.sip.header.FromHeader; import javax.sip.message.Response; import gov.nist.javax.sip.header.HeaderExt; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipRequest; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CreateCallsTest { private final static Logger logger = Logger.getLogger(CreateCallsTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; private SipStack alice2SipStack; private SipPhone alice2Phone; private String alice2Contact = "sip:[email protected]:5092"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("CreateCalls1"); tool2 = new SipStackTool("CreateCalls2"); tool3 = new SipStackTool("CreateCalls3"); tool4 = new SipStackTool("CreateCalls4"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); aliceSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); alice2SipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); alice2Phone = alice2SipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, alice2Contact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alice2Phone != null) { alice2Phone.dispose(); } if (alice2SipStack != null) { alice2SipStack.dispose(); } Thread.sleep(1000); } @Test // @Category(UnstableTests.class) // Create a call to a SIP URI. Non-regression test for issue https://bitbucket.org/telestax/telscale-restcomm/issue/175 // Use Calls Rest API to dial Bob (SIP URI sip:[email protected]:5090) and connect him to the RCML app dial-number-entry.xml. // This RCML will dial +131313 which George's phone is listening (use the dial-number-entry.xml as a side effect to verify // that the call created successfully) public void createCallSipUriTest() throws InterruptedException { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(3000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentOutgoingCalls").getAsInt(); assertEquals(2, maxConcurrentCalls); assertEquals(0,maxConcurrentIncomingCalls); assertEquals(2,maxConcurrentOutgoingCalls); } @Test @Category(FeatureAltTests.class) public void createCallSipUriWithCustomHeadersTest() throws InterruptedException { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact+"?X-Custom-Header1=1234&X-Custom-Header2=4321"; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(bobCall.waitForIncomingCall(5000)); //Check custom headers SipRequest invite = bobCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header1")).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header2")).getValue(); assertEquals("1234", customHeader1); assertEquals("4321", customHeader2); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(3000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentOutgoingCalls").getAsInt(); assertEquals(2, maxConcurrentCalls); assertEquals(0,maxConcurrentIncomingCalls); assertEquals(2,maxConcurrentOutgoingCalls); } @Test // @Category({FeatureAltTests.class, UnstableTests.class}) @Category(FeatureAltTests.class) // Create a call to a SIP URI. Non-regression test for issue https://github.com/Mobicents/RestComm/issues/150 // Use Calls Rest API to dial Bob (SIP URI sip:[email protected]:5090) and connect him to the RCML app dial-number-entry.xml. // This RCML will dial +131313 which George's phone is listening (use the dial-number-entry.xml as a side effect to verify // that the call created successfully) public void createCallSipUriAllowFromModificationTest() throws InterruptedException { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "sip:[email protected]"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(bobCall.waitForIncomingCall(5000)); FromHeader fromHeader = (FromHeader) bobCall.getLastReceivedRequest().getRequestEvent().getRequest().getHeader(FromHeader.NAME); assertNotNull(fromHeader); // System.out.println(fromHeader); assertEquals(from, fromHeader.getAddress().getURI().toString().trim()); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentOutgoingCalls").getAsInt(); assertEquals(2, maxConcurrentCalls); assertEquals(0,maxConcurrentIncomingCalls); assertEquals(2,maxConcurrentOutgoingCalls); } @Test // @Category(UnstableTests.class) // Create a call to a Restcomm Client. Non-regression test for issue // https://bitbucket.org/telestax/telscale-restcomm/issue/175 // Use Calls Rest API to dial Alice Restcomm client and connect him to the RCML app dial-number-entry.xml. // This RCML will dial +131313 which George's phone is listening (use the dial-number-entry.xml as a side effect to verify // that the call created successfully) public void createCallClientTest() throws InterruptedException, ParseException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "client:alice"; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentOutgoingCalls").getAsInt(); assertEquals(2, maxConcurrentCalls); assertEquals(0,maxConcurrentIncomingCalls); assertEquals(2,maxConcurrentOutgoingCalls); } @Test @Category(FeatureAltTests.class) public void createCallClientWithCustomHeadersTest() throws InterruptedException, ParseException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Credential c = new Credential("127.0.0.1", "alice", "1234"); alicePhone.addUpdateCredential(c); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "client:alice?X-Custom-Header1=1234&X-Custom-Header2=4321"; String rcmlUrl = deploymentUrl.toString() + "dial-number-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(aliceCall.waitForIncomingCall(5000)); SipRequest invite = aliceCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header1")).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header2")).getValue(); assertEquals("1234", customHeader1); assertEquals("4321", customHeader2); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentOutgoingCalls").getAsInt(); assertEquals(2, maxConcurrentCalls); assertEquals(0,maxConcurrentIncomingCalls); assertEquals(2,maxConcurrentOutgoingCalls); } @Test @Category({FeatureExpTests.class}) // Create a call to a Restcomm Client for wrong RCML url public void createCallClientTestWrongRcmlUrl() throws InterruptedException, ParseException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "client:alice"; String rcmlUrl = "/restcomm/dial-number-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); aliceCall.listenForDisconnect(); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentOutgoingCalls").getAsInt(); assertEquals(2, maxConcurrentCalls); assertEquals(0,maxConcurrentIncomingCalls); assertEquals(2,maxConcurrentOutgoingCalls); } @Test //Create call to client with multiple registrations. Client Alice has two registrations (2 locations) and both should ring public void createCallClientTestWithMultipleRegistrations() throws InterruptedException, ParseException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); assertTrue(alice2Phone.register(uri, "alice", "1234", alice2Contact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); SipCall alice2Call = alice2Phone.createSipCall(); alice2Call.listenForIncomingCall(); String from = "+15126002188"; String to = "client:alice"; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonArray callResult = (JsonArray) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(alice2Call.waitForIncomingCall(5000)); assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(alice2Call.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Here-Alice-2", 3600)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(3000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt(); int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt(); int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentOutgoingCalls").getAsInt(); assertEquals(2, maxConcurrentCalls); assertEquals(0,maxConcurrentIncomingCalls); assertEquals(2,maxConcurrentOutgoingCalls); } @Test // Create a call to a Number. Non-regression test for issue https://bitbucket.org/telestax/telscale-restcomm/issue/175 // Use Calls Rest API to dial Number +131313 which is George's phone and connect him to the RCML app dial-client-entry.xml. // This RCML will dial Alice Restcomm client (use the dial-number-entry.xml as a side effect to verify that the call created // successfully) public void createCallNumberTest() throws InterruptedException, ParseException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "+131313"; String rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); logger.info("CallResult: "+callResult); assertTrue(georgeCall.waitForIncomingCall(5000)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to Alice Restcomm client assertTrue(aliceCall.waitForIncomingCall(5000)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test @Category(FeatureAltTests.class) public void createCallNumberWithCustomHeadersTest() throws InterruptedException, ParseException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "+131313?X-Custom-Header1=1234&X-Custom-Header2=4321"; String rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(georgeCall.waitForIncomingCall(5000)); //Check custom headers SipRequest invite = georgeCall.getLastReceivedRequest(); assertEquals(SipRequest.INVITE, invite.getRequestEvent().getRequest().getMethod()); String customHeader1 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header1")).getValue(); String customHeader2 = ((HeaderExt) invite.getRequestEvent().getRequest().getHeader("X-Custom-Header2")).getValue(); assertEquals("1234", customHeader1); assertEquals("4321", customHeader2); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to Alice Restcomm client assertTrue(aliceCall.waitForIncomingCall(5000)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } String dialClient = "<Response><Dial timeLimit=\"10\" timeout=\"10\"><Client>alice</Client></Dial></Response>"; /* Calls REST API will create call to sipUnit client 'george' but there will be no answer within the timeout interval (10sec) Restcomm should cancel the call and cleanup */ @Test @Category({FeatureExpTests.class}) public void createCallNumberTestNoAnswer() throws InterruptedException, ParseException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClient))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "+131313"; String rcmlUrl = "http://127.0.0.1:8090/1111"; String timeout = "10"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl, timeout); assertNotNull(callResult); assertTrue(georgeCall.waitForIncomingCall(5000)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); Thread.sleep(15000); georgeCall.listenForCancel(); SipTransaction cancelTransaction = georgeCall.waitForCancel(100 * 1000); assertNotNull(cancelTransaction); assertTrue(georgeCall.respondToCancel(cancelTransaction, Response.OK, "George-OK-2-Cancel", 3600)); Thread.sleep(3000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } /* Calls REST API will create call to sipUnit client 'george' which will answer, next will create call to client 'alice' but there will be no answer within the timeout interval (10sec) and Restcomm should cancel the call to alice and disconnect 'george' call */ @Test // @Category({FeatureExpTests.class, UnstableTests.class}) @Category(FeatureExpTests.class) public void createCallNumberTestNoAnswerOnRcml() throws InterruptedException, ParseException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClient))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "+131313"; String rcmlUrl = "http://127.0.0.1:8090/1111"; String timeout = "10"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl, timeout); assertNotNull(callResult); assertTrue(georgeCall.waitForIncomingCall(5000)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to Alice Restcomm client assertTrue(aliceCall.waitForIncomingCall(5000)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); aliceCall.listenForCancel(); georgeCall.listenForDisconnect(); SipTransaction cancelTransaction = aliceCall.waitForCancel(100 * 1000); assertNotNull(cancelTransaction); assertTrue(aliceCall.respondToCancel(cancelTransaction, Response.OK, "Alice-OK-2-Cancel", 3600)); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } /* Calls REST API will create call to sipUnit client 'george' which will answer, next will create call to client 'alice' but the response will be 486 Busy here and Restcomm should disconnect 'george' call */ @Test // @Category({FeatureExpTests.class, UnstableTests.class}) @Category(FeatureExpTests.class) public void createCallNumberTestBusyOnRcml () throws InterruptedException, ParseException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClient))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "+131313"; String rcmlUrl = "http://127.0.0.1:8090/1111"; String timeout = "10"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl, timeout); assertNotNull(callResult); assertTrue(georgeCall.waitForIncomingCall(5000)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to Alice Restcomm client assertTrue(aliceCall.waitForIncomingCall(5000)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.BUSY_HERE, "Busy-Here-Alice", 3600)); assertTrue(aliceCall.waitForAck(5000)); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } @Test @Category({FeatureExpTests.class}) public void createCallNumberTestWith500ErrorResponse() throws InterruptedException, ParseException { SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "+131313"; String rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(georgeCall.waitForIncomingCall(5000)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.SERVER_INTERNAL_ERROR, "Service Unavailable", 3600)); assertTrue(georgeCall.waitForAck(5000)); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); } String dialClientWithRecord = "<Response><Dial record=\"true\"><Client>alice</Client></Dial></Response>"; /* Calls REST API will create call to sipUnit client 'george' but there will be no answer within the timeout interval (10sec) Restcomm should cancel the call and cleanup */ @Test public void createCallNumberWithRecord() throws InterruptedException, ParseException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialClientWithRecord))); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = "+131313"; String rcmlUrl = "http://127.0.0.1:8090/1111"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(georgeCall.waitForIncomingCall(5000)); String receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); String callSid = georgeCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); // Restcomm now should execute RCML that will create a call to Alice Restcomm client assertTrue(aliceCall.waitForIncomingCall(5000)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(aliceCall.waitForDisconnect(5000)); assertTrue(aliceCall.respondToDisconnect()); Thread.sleep(2000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0, liveCalls); assertEquals(0, liveCallsArraySize); //Check recording JsonArray recording = RestcommCallsTool.getInstance().getCallRecordings(deploymentUrl.toString(),adminAccountSid,adminAuthToken,callSid); assertNotNull(recording); assertEquals(1, recording.size()); double duration = recording.get(0).getAsJsonObject().get("duration").getAsDouble(); assertEquals(3.0, duration, 1.0); } @Deployment(name = "CreateCallsTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-number-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("hello-play.xml"); logger.info("Packaged Test App"); return archive; } }
51,891
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OutboudProxyCallsTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/OutboudProxyCallsTest.java
package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import com.google.gson.JsonObject; import org.restcomm.connect.commons.Version; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class OutboudProxyCallsTest { private final static Logger logger = Logger.getLogger(OutboudProxyCallsTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private SipStack primaryProxySipStack; private SipPhone primaryProxyPhone; private String primaryProxyContact = "sip:[email protected]:5070"; private SipStack fallbackProxySipStack; private SipPhone fallbackProxyPhone; private String fallbackProxyContact = "sip:[email protected]:5090"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5091"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("OutboundProxyCalls1"); tool2 = new SipStackTool("OutboundProxyCalls2"); tool3 = new SipStackTool("OutboundProxyCalls3"); } @Before public void before() throws Exception { primaryProxySipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); primaryProxyPhone = primaryProxySipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, primaryProxyContact); fallbackProxySipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); fallbackProxyPhone = fallbackProxySipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, fallbackProxyContact); georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (primaryProxyPhone != null) { primaryProxyPhone.dispose(); } if (primaryProxySipStack != null) { primaryProxySipStack.dispose(); } if (fallbackProxyPhone != null) { fallbackProxyPhone.dispose(); } if (fallbackProxySipStack != null) { fallbackProxySipStack.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } } @Test // Create a call to a SIP URI. Non-regression test for issue https://bitbucket.org/telestax/telscale-restcomm/issue/175 // Use Calls Rest API to dial Bob (SIP URI sip:[email protected]:5090) and connect him to the RCML app dial-number-entry.xml. // This RCML will dial +131313 which George's phone is listening (use the dial-number-entry.xml as a side effect to verify // that the call created successfully) public void createCallAndFallback() throws InterruptedException { String primaryProxy = "127.0.0.1:5070"; String fallbackProxy = "127.0.0.1:5090"; JsonObject activeProxyJsonObject = OutboundProxyTool.getInstance().getActiveProxy(deploymentUrl.toString(), adminAccountSid, adminAuthToken); String activeProxy = activeProxyJsonObject.get("ActiveProxy").getAsString(); assertTrue(activeProxy.equalsIgnoreCase(primaryProxy)); SipCall primaryProxyCall = primaryProxyPhone.createSipCall(); primaryProxyCall.listenForIncomingCall(); SipCall fallbackProxyCall = fallbackProxyPhone.createSipCall(); fallbackProxyCall.listenForIncomingCall(); String from = "+15126002188"; String to = primaryProxyContact; String rcmlUrl = deploymentUrl.toString() + ".application-"+version+"/dial-number-entry.xml"; for (int i = 0; i < 20; i++) { JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(primaryProxyCall.waitForIncomingCall(5000)); assertTrue(primaryProxyCall.sendIncomingCallResponse(480, "Temporarily Unavailable - Primary Proxy", 3600)); Thread.sleep(2000); } activeProxyJsonObject = OutboundProxyTool.getInstance().getActiveProxy(deploymentUrl.toString(), adminAccountSid, adminAuthToken); activeProxy = activeProxyJsonObject.get("ActiveProxy").getAsString(); assertTrue(activeProxy.equalsIgnoreCase(fallbackProxy)); to = fallbackProxyContact; for (int i = 0; i < 20; i++) { JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(fallbackProxyCall.waitForIncomingCall(5000)); assertTrue(fallbackProxyCall.sendIncomingCallResponse(480, "Temporarily Unavailable - Fallback Proxy", 3600)); Thread.sleep(2000); } activeProxyJsonObject = OutboundProxyTool.getInstance().getActiveProxy(deploymentUrl.toString(), adminAccountSid, adminAuthToken); activeProxy = activeProxyJsonObject.get("ActiveProxy").getAsString(); assertTrue(activeProxy.equalsIgnoreCase(primaryProxy)); } @Deployment(name = "OutboundCallsTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-number-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); logger.info("Packaged Test App"); return archive; } }
8,190
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RecordingEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/RecordingEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.HashMap; import java.util.Map; import com.sun.jersey.api.client.UniformInterfaceException; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.FeatureAltTests; /** * @author <a href="mailto:[email protected]">vunguyen</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RecordingEndpointTest extends EndpointTest{ private static Logger logger = Logger.getLogger(RecordingEndpointTest.class); private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test public void getRecordingList() { JsonObject firstPage = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageRecordingsArray = firstPage.get("recordings").getAsJsonArray(); int firstPageRecordingsArraySize = firstPageRecordingsArray.size(); assertTrue(firstPageRecordingsArraySize == 34); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 34); assertTrue(totalSize == 34); } @Test @Category(FeatureAltTests.class) public void getRecordingListUsingPageSize() { JsonObject firstPage = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, null, 10, null, true); JsonArray firstPageRecordingsArray = firstPage.get("recordings").getAsJsonArray(); assertTrue(firstPageRecordingsArray.size() == 10); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 9); JsonObject secondPage = (JsonObject) RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 2, 10, null, true); JsonArray secondPageRecordingsArray = secondPage.get("recordings").getAsJsonArray(); assertTrue(secondPageRecordingsArray.size() == 10); assertTrue(secondPage.get("start").getAsInt() == 20); assertTrue(secondPage.get("end").getAsInt() == 29); JsonObject lastPage = (JsonObject) RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, firstPage.get("num_pages").getAsInt(), 10, null, true); JsonArray lastPageRecordingsArray = lastPage.get("recordings").getAsJsonArray(); assertTrue(lastPageRecordingsArray.size() == 4); assertTrue(lastPage.get("start").getAsInt() == 30); assertTrue(lastPage.get("end").getAsInt() == 34); } @Test @Category(FeatureAltTests.class) public void getRecordingListFilteredByStartTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("StartTime", "2015-01-08 08:51:07.955000"); JsonObject filteredRecordingsByStartTime = RecordingEndpointTool.getInstance().getRecordingListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredRecordingsByStartTime.get("recordings").getAsJsonArray().size() == 32); assertTrue(filteredRecordingsByStartTime.get("start").getAsInt() == 0); assertTrue(filteredRecordingsByStartTime.get("end").getAsInt() == 32); } @Test @Category(FeatureAltTests.class) public void getRecordingListFilteredByEndTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("EndTime", "2015-01-08 08:51:07.955000"); JsonObject filteredRecordingsByEndTime = RecordingEndpointTool.getInstance().getRecordingListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredRecordingsByEndTime.get("recordings").getAsJsonArray().size() == 14); assertTrue(filteredRecordingsByEndTime.get("start").getAsInt() == 0); assertTrue(filteredRecordingsByEndTime.get("end").getAsInt() == 14); } @Test public void getRecordingListFilteredByCallSid() { Map<String, String> filters = new HashMap<String, String>(); filters.put("CallSid", "CAfe9ce46f104f5beeb10c83a5dad2be66"); JsonObject filteredRecordingsByCallSid = RecordingEndpointTool.getInstance().getRecordingListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredRecordingsByCallSid.get("recordings").getAsJsonArray().size() == 9); assertTrue(filteredRecordingsByCallSid.get("start").getAsInt() == 0); assertTrue(filteredRecordingsByCallSid.get("end").getAsInt() == 9); } @Test public void recordingDelete() { String recordingSid = "RE10000000000000000000000000000032"; RecordingEndpointTool.getInstance().deleteRecording(deploymentUrl.toString(), adminAccountSid, adminAuthToken, recordingSid); JsonObject firstPage = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageRecordingsArray = firstPage.get("recordings").getAsJsonArray(); int firstPageRecordingsArraySize = firstPageRecordingsArray.size(); assertTrue(firstPageRecordingsArraySize == 33); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 33); assertTrue(totalSize == 33); } @Test public void getRecordingListUsingSorting() { int pageSize = 30; // Provide both sort field and direction // Provide ascending sorting and verify that the first row is indeed the earliest one JsonObject response = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:asc", true); // Remember there is a discrepancy between the sort parameters and the result attribute in the .json response. For example DateCreated:asc, means // to sort based of DateCreated field, but in the response the field is called 'date_created', not DateCreated. This only happens only for .json; in // .xml the naming seems to be respected. // Notice that we are removing the timezone part from the end of the string, because CI potentially uses different timezone that messes the test up assertEquals("Mon, 6 Jan 2014 08:51:08", ((JsonObject)response.get("recordings").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); // Provide only sort field; all fields default to ascending response = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated", true); assertEquals("Mon, 6 Jan 2014 08:51:08", ((JsonObject)response.get("recordings").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); response = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:desc", true); assertEquals("Tue, 5 Jan 2016 08:51:07", ((JsonObject)response.get("recordings").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); try { // provide only direction, should cause an exception RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, ":asc", true); } catch (UniformInterfaceException e) { assertEquals(BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); } try { // provide sort field and direction, but direction is invalid (neither of asc or desc) RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:invalid", true); } catch (UniformInterfaceException e) { assertEquals(BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); } // Duration response = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Duration:asc", true); assertEquals("1.0", ((JsonObject)response.get("recordings").getAsJsonArray().get(0)).get("duration").getAsString()); response = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Duration:desc", true); assertEquals("59.0", ((JsonObject)response.get("recordings").getAsJsonArray().get(0)).get("duration").getAsString()); // CallSid response = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "CallSid:asc", true); assertEquals("CA009ce46f104f4beeb10c83a5dad2bf66", ((JsonObject)response.get("recordings").getAsJsonArray().get(0)).get("call_sid").getAsString()); response = RecordingEndpointTool.getInstance().getRecordingList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "CallSid:desc", true); assertEquals("CAff9ce46f104f4beeb10c83a5dad2bf66", ((JsonObject)response.get("recordings").getAsJsonArray().get(0)).get("call_sid").getAsString()); } @Deployment(name = "RecordingEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
12,396
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TranscriptionEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/TranscriptionEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.FeatureAltTests; /** * @author <a href="mailto:[email protected]">vunguyen</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TranscriptionEndpointTest extends EndpointTest{ private static Logger logger = Logger.getLogger(TranscriptionEndpointTest.class); private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test public void getTranscriptionList() { JsonObject firstPage = TranscriptionEndpointTool.getInstance().getTranscriptionList(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageTranscriptionsArray = firstPage.get("transcriptions").getAsJsonArray(); int firstPageTranscriptionsArraySize = firstPageTranscriptionsArray.size(); assertTrue(firstPageTranscriptionsArraySize == 34); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 34); assertTrue(totalSize == 34); } @Test @Category(FeatureAltTests.class) public void getTranscriptionListUsingPageSize() { JsonObject firstPage = TranscriptionEndpointTool.getInstance().getTranscriptionList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, null, 10, true); JsonArray firstPageTranscriptionsArray = firstPage.get("transcriptions").getAsJsonArray(); assertTrue(firstPageTranscriptionsArray.size() == 10); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 9); JsonObject secondPage = (JsonObject) TranscriptionEndpointTool.getInstance().getTranscriptionList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 2, 10, true); JsonArray secondPageTranscriptionsArray = secondPage.get("transcriptions").getAsJsonArray(); assertTrue(secondPageTranscriptionsArray.size() == 10); assertTrue(secondPage.get("start").getAsInt() == 20); assertTrue(secondPage.get("end").getAsInt() == 29); JsonObject lastPage = (JsonObject) TranscriptionEndpointTool.getInstance().getTranscriptionList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, firstPage.get("num_pages").getAsInt(), 10, true); JsonArray lastPageTranscriptionsArray = lastPage.get("transcriptions").getAsJsonArray(); assertTrue(lastPageTranscriptionsArray.size() == 4); assertTrue(lastPage.get("start").getAsInt() == 30); assertTrue(lastPage.get("end").getAsInt() == 34); } @Test @Category(FeatureAltTests.class) public void getTranscriptionListFilteredByStartTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("StartTime", "2013-11-30 16:28:33.403000000"); JsonObject filteredTranscriptionsByStartTime = TranscriptionEndpointTool.getInstance().getTranscriptionListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredTranscriptionsByStartTime.get("transcriptions").getAsJsonArray().size() == 20); assertTrue(filteredTranscriptionsByStartTime.get("start").getAsInt() == 0); assertTrue(filteredTranscriptionsByStartTime.get("end").getAsInt() == 20); } @Test @Category(FeatureAltTests.class) public void getTranscriptionListFilteredByEndTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("EndTime", "2013-10-30 16:28:33.403000000"); JsonObject filteredTranscriptionsByEndTime = TranscriptionEndpointTool.getInstance().getTranscriptionListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredTranscriptionsByEndTime.get("transcriptions").getAsJsonArray().size() == 14); assertTrue(filteredTranscriptionsByEndTime.get("start").getAsInt() == 0); assertTrue(filteredTranscriptionsByEndTime.get("end").getAsInt() == 14); } @Test @Category(FeatureAltTests.class) public void getTranscriptionListFilteredByTranscriptionText() { Map<String, String> filters = new HashMap<String, String>(); filters.put("TranscriptionText", "RestComm"); JsonObject filteredTranscriptionsByTranscriptionText = TranscriptionEndpointTool.getInstance().getTranscriptionListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredTranscriptionsByTranscriptionText.get("transcriptions").getAsJsonArray().size() == 13); assertTrue(filteredTranscriptionsByTranscriptionText.get("start").getAsInt() == 0); assertTrue(filteredTranscriptionsByTranscriptionText.get("end").getAsInt() == 13); } @Deployment(name = "TranscriptionEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
7,515
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConferenceEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/ConferenceEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertTrue; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; /** * @author Maria */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ConferenceEndpointTest { private final static Logger logger = Logger.getLogger(ConferenceEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Deployment(name = "ClientsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } @Test public void getConferences() { JsonObject page = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalSize = page.get("total").getAsInt(); JsonArray firstPageConferenceArray = page.get("conferences").getAsJsonArray(); int firstPageConferenceArraySize = firstPageConferenceArray.size(); assertTrue(firstPageConferenceArraySize == 2); assertTrue(page.get("start").getAsInt() == 0); assertTrue(page.get("end").getAsInt() == 2); assertTrue(totalSize == 2); } @Test @Category(FeatureAltTests.class) public void getConferencesFilteredByStatus() { Map<String, String> filters = new HashMap<String, String>(); filters.put("Status", "COMPLETED"); JsonObject allConferencesObject = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject filteredConferencesByStatusObject = RestcommConferenceTool.getInstance().getConferencesUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredConferencesByStatusObject.get("conferences").getAsJsonArray().size() == 1); assertTrue(allConferencesObject.get("start").getAsInt() == 0); assertTrue(allConferencesObject.get("end").getAsInt() == 2); assertTrue(filteredConferencesByStatusObject.get("start").getAsInt() == 0); assertTrue(filteredConferencesByStatusObject.get("end").getAsInt() == 1); assertTrue(allConferencesObject.get("conferences").getAsJsonArray().size() > filteredConferencesByStatusObject.get("conferences") .getAsJsonArray().size()); } @Test @Category(FeatureAltTests.class) public void getConferencesFilteredByFriendlyName() { Map<String, String> filters = new HashMap<String, String>(); filters.put("FriendlyName", "1111"); JsonObject allConferencesObject = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject filteredConferencesByFNObject = RestcommConferenceTool.getInstance().getConferencesUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredConferencesByFNObject.get("conferences").getAsJsonArray().size() == 2); assertTrue(allConferencesObject.get("start").getAsInt() == 0); assertTrue(allConferencesObject.get("end").getAsInt() == 2); assertTrue(filteredConferencesByFNObject.get("start").getAsInt() == 0); assertTrue(filteredConferencesByFNObject.get("end").getAsInt() == 2); assertTrue(allConferencesObject.get("conferences").getAsJsonArray().size() == filteredConferencesByFNObject.get("conferences") .getAsJsonArray().size()); } @Test @Category(FeatureAltTests.class) public void getConferencesFilteredUsingMultipleFilters() { Map<String, String> filters = new HashMap<String, String>(); filters.put("FriendlyName", "1111"); filters.put("Status", "COMPLETED"); JsonObject allConferencesObject = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonObject filteredConferencesByFNObject = RestcommConferenceTool.getInstance().getConferencesUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredConferencesByFNObject.get("conferences").getAsJsonArray().size() == 1); assertTrue(allConferencesObject.get("start").getAsInt() == 0); assertTrue(allConferencesObject.get("end").getAsInt() == 2); assertTrue(filteredConferencesByFNObject.get("start").getAsInt() == 0); assertTrue(filteredConferencesByFNObject.get("end").getAsInt() == 1); assertTrue(allConferencesObject.get("conferences").getAsJsonArray().size() > filteredConferencesByFNObject.get("conferences") .getAsJsonArray().size()); } }
7,544
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CorsRelaxTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/CorsRelaxTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import junit.framework.Assert; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Ignore; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import javax.ws.rs.core.MultivaluedMap; import java.net.URL; /** * Tests whether CORS restrictions are relaxed when <rcmlserver/> configuration contains an absolute baseurl. * Currently it only tests Accounts endpoint where CORS-relax logic has been applied * * @author [email protected] - Orestis Tsakiridis * * It was written for the case when restcomm should accept CORS requests and return the appropriate headers. * Initially that would happen if restcomm would be in a different domain from RVD. * Later, we decided to put everything (restcomm and RVD) behind the same domain. * So, relaxing CORS restrictions is not really needed */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Ignore public class CorsRelaxTest extends EndpointTest { private final static Logger logger = Logger.getLogger(CorsRelaxTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; String accountSid = "ACae6e420f425248d6a26948c17a9e2acf"; String accountToken = "77f8c12cc7b8f8423e5c38b035249166"; // Tests cors headers existence when retrieving an account @Test public void corsHeadersAreReturnedForAccount() { // Bypass jersey restriction for "Origin" header. By default it can't be added to a WebResource object. System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); Client jersey = Client.create(); // make a preflight OPTIONS request using an origin present in restcomm.xml/rcmlserver i.e. http://testing.restcomm.com WebResource resource = jersey.resource(getResourceUrl("/2012-04-24/Accounts.json/ACae6e420f425248d6a26948c17a9e2acf")); ClientResponse response = resource.header("Origin", "http://testing.restcomm.com").options(ClientResponse.class); Assert.assertEquals(200, response.getStatus()); MultivaluedMap<String,String> headers = response.getHeaders(); String originHeader = headers.getFirst("Access-Control-Allow-Origin"); Assert.assertEquals("http://testing.restcomm.com",originHeader); // make a preflight OPTIONS request using an origin NOT present in restcomm.xml/rcmlserver i.e. http://otherhost.restcomm.com WebResource resource2 = jersey.resource(getResourceUrl("/restcomm/2012-04-24/Accounts.json/ACae6e420f425248d6a26948c17a9e2acf")); ClientResponse response2 = resource2.header("Origin", "http://otherhost.restcomm.com").options(ClientResponse.class); originHeader = response2.getHeaders().getFirst("Access-Control-Allow-Origin"); Assert.assertEquals(200, response2.getStatus()); Assert.assertNull(originHeader); } @Deployment(name = "CorsRelaxTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-corsRelax.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
5,476
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
LiveCallModificationAnswerDelayTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/LiveCallModificationAnswerDelayTest.java
package org.restcomm.connect.testsuite.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.UnstableTests; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category({FeatureAltTests.class, UnstableTests.class}) public class LiveCallModificationAnswerDelayTest { private final static Logger logger = Logger.getLogger(CreateCallsTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("LiveCallModification1"); tool2 = new SipStackTool("LiveCallModification2"); tool3 = new SipStackTool("LiveCallModification3"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); aliceSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } @Test // Terminate a call in-progress using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 public void terminateInProgressCall() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(1000); bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "completed", null); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); georgeCall.dispose(); bobCall.dispose(); } @Test // Terminate a call in-progress using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 public void terminateInProgressCallAlreadyTerminated() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(1000); bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "completed", null); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "completed", null); assertNotNull(callResult); georgeCall.dispose(); bobCall.dispose(); } @Test // Terminate a call that is ringing using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 public void terminateRingingCall() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry-lcm.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob1", 3600)); Thread.sleep(1000); bobCall.listenForDisconnect(); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "canceled", null); SipTransaction transaction = bobCall.waitForCancel(5000); assertNotNull(transaction); bobCall.respondToCancel(transaction, 200, "OK-2-Cancel-Bob", 3600); georgeCall.dispose(); bobCall.dispose(); } @Test // Redirect a call to a different URL using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 // TODO: This test is expected to fail because of issue https://bitbucket.org/telestax/telscale-restcomm/issue/192 public void redirectCall() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitForAck(5000)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to redirect the call\n ********************\n"); rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, rcmlUrl); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); // Restcomm now should execute the new RCML and create a call to Alice Restcomm client // TODO: This test is expected to fail because of issue https://bitbucket.org/telestax/telscale-restcomm/issue/192 assertTrue(aliceCall.waitForIncomingCall(5000)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(aliceCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); } String dialConference = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Response>\n" + "\t<Dial timeout=\"10\">\n" + "\t <Conference muted=\"true\" startConferenceOnEnter=\"false\" beep=\"false\">Conf1234</Conference>\n" + "\t</Dial>\n" + "</Response>"; @Test @Category(UnstableTests.class) // Redirect a call to a different URL using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 // TODO: This test is expected to fail because of issue https://bitbucket.org/telestax/telscale-restcomm/issue/192 public void redirectCallInConferenceMuted() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConference))); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); Credential bobCredential = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(bobCredential); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertTrue(bobCall.waitForAuthorisation(5000)); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } // assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); // assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); // assertTrue(bobCall.sendInviteOkAck()); // // // String from = "+15126002188"; // String to = bobContact; // String rcmlUrl = "http://127.0.0.1:8090/1111"; // // JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, // adminAuthToken, from, to, rcmlUrl); // assertNotNull(callResult); // String callSid = callResult.get("sid").getAsString(); // // assertTrue(bobCall.waitForIncomingCall(5000)); // String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); // assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); // assertTrue(bobCall // .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // // assertTrue(bobCall.waitForAck(5000)); // // // Restcomm now should execute RCML that will create a call to +131313 (george's phone) // // assertTrue(georgeCall.waitForIncomingCall(5000)); // receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); // assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); // assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", // null, null)); // // assertTrue(georgeCall.waitForAck(5000)); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to redirect the call\n ********************\n"); String rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, rcmlUrl); // georgeCall.listenForDisconnect(); // assertTrue(georgeCall.waitForDisconnect(10000)); // assertTrue(georgeCall.respondToDisconnect()); // Restcomm now should execute the new RCML and create a call to Alice Restcomm client // TODO: This test is expected to fail because of issue https://bitbucket.org/telestax/telscale-restcomm/issue/192 assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(aliceCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); } private String dialAlice = "<Response><Dial><Client>alice</Client></Dial></Response>"; private String confUnHold = "<Response>\n" + " <Dial>\n" + " <Conference startConferenceOnEnter=\"true\">HoldConf1234</Conference>\n" + " </Dial>\n" + "</Response>"; private String confHold = "<Response>\n" + "\t<Dial>\n" + "\t\t<Conference startConferenceOnEnter=\"false\" waitUrl=\"/restcomm/music/rock/nickleus_-_original_guitar_song_200907251723.wav\">HoldConf1234</Conference>\n" + "\t</Dial>\n" + "</Response>"; @Test @Category(UnstableTests.class) public void holdCall() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAlice))); stubFor(post(urlPathEqualTo("/hold")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(confHold))); stubFor(post(urlPathEqualTo("/unhold")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(confUnHold))); Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertTrue(bobCall.waitForAuthorisation(5000)); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(bobCall.sendInviteOkAck()); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to put call on hold\n ********************\n"); String rcmlUrl = "http://127.0.0.1:8090/hold"; JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, rcmlUrl, true); Thread.sleep(10000); JsonObject confObject = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(confObject); JsonArray confArray = confObject.getAsJsonArray("conferences"); assertNotNull(confArray); String confSid = confArray.get(0).getAsJsonObject().get("sid").getAsString(); assertNotNull(confSid); JsonObject partObject = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confSid); assertNotNull(partObject); JsonArray callsArray = partObject.getAsJsonArray("calls"); int size = callsArray.size(); assertEquals(2, size); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to unhold calls\n ********************\n"); rcmlUrl = "http://127.0.0.1:8090/unhold"; callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, rcmlUrl, true); Thread.sleep(2000); partObject = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confSid); assertNotNull(partObject); callsArray = partObject.getAsJsonArray("calls"); size = callsArray.size(); assertEquals(2, size); Thread.sleep(2000); bobCall.disconnect(); aliceCall.disconnect(); Thread.sleep(1000); partObject = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confSid); assertNotNull(partObject); callsArray = partObject.getAsJsonArray("calls"); size = callsArray.size(); assertEquals(0, size); } @Test // Redirect a call to a different URL using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 public void redirectCallInvalidCallSid() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitForAck(5000)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to redirect the call\n ********************\n"); rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; //String invalidCallSid = Sid.generate(Sid.Type.CALL).toString(); // restcomm-connect/1907 String invalidCallSid = "IDaaaaaaaaaaabbbbbbbbbbbcccccccddd-CAaaaaaabbbbbcccccdddddeeeeeffffgg"; callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, invalidCallSid, null, rcmlUrl); assertNotNull(callResult); String exc = callResult.get("Exception").getAsString(); assertTrue(callResult.get("Exception").getAsString().equals("406")); georgeCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); } private String dialFork = "<Response><Dial record=\"true\" timeout=\"150\" action=\"/completed\"><Client>alice</Client><Number>+131313</Number></Dial></Response>"; @Test //@Ignore // Problem with CDRs status after call is disconnected public void testTerminateDialForkCallWhileRinging_LCM_to_dial_branches() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); stubFor(post(urlPathEqualTo("/completed")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } String bobCallSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String georgeCallSid = georgeCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String aliceCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); georgeCall.listenForCancel(); aliceCall.listenForCancel(); //LCM request to terminate RINGING calls JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, aliceCallSid, "canceled", null); assertNotNull(callResult); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, georgeCallSid, "canceled", null); assertNotNull(callResult); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(aliceCancelTransaction); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.SERVER_INTERNAL_ERROR, bobCall.getLastReceivedResponse().getStatusCode()); //Wait to cancel the other branches Thread.sleep(3000); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, aliceCallSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+aliceCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("canceled")); cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, georgeCallSid); jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+georgeCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("canceled")); cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, bobCallSid); jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+bobCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("canceled")); } @Test //@Ignore // Problem with CDRs status after call is disconnected public void testTerminateDialForkCallWhileRinging_LCM_to_initial_call() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); stubFor(post(urlPathEqualTo("/completed")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } String bobCallSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); // assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); // assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); // bobCall.sendInviteOkAck(); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); // assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String georgeCallSid = georgeCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String aliceCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); georgeCall.listenForCancel(); aliceCall.listenForCancel(); //LCM request to terminate the initial call which is in-progress JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "canceled", null); assertNotNull(callResult); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(aliceCancelTransaction); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TERMINATED, bobCall.getLastReceivedResponse().getStatusCode()); //Wait to cancel the other branches Thread.sleep(3000); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, aliceCallSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+aliceCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("canceled")); cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, georgeCallSid); jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+georgeCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("canceled")); cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, bobCallSid); jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+bobCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); } private String hangupRcml = "<Response><Hangup></Hangup></Response>"; @Test //@Ignore // Problem with CDRs status after call is disconnected public void testTerminateDialForkCallWhileRinging_LCM_to_move_initial_call_to_hangup_rcml() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); stubFor(post(urlPathEqualTo("/completed")) .willReturn(aResponse() .withStatus(200))); stubFor(post(urlPathEqualTo("/hangupRcml")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupRcml))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } String bobCallSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); // assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); // assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); // bobCall.sendInviteOkAck(); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); // assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String georgeCallSid = georgeCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String aliceCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); georgeCall.listenForCancel(); aliceCall.listenForCancel(); //LCM request to move initial call to Hangup RCML String hangupUrl = "http://127.0.0.1:8090/hangupRcml"; JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, hangupUrl); assertNotNull(callResult); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(aliceCancelTransaction); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.REQUEST_TERMINATED, bobCall.getLastReceivedResponse().getStatusCode()); //Wait to cancel the other branches Thread.sleep(3000); JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, aliceCallSid); JsonObject jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+aliceCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("canceled")); cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, georgeCallSid); jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+georgeCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("canceled")); cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, bobCallSid); jsonObj = cdr.getAsJsonObject(); logger.info("Status for call: "+bobCallSid+" : "+jsonObj.get("status").getAsString()); assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed")); } @Deployment(name = "LiveCallModificationTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-delay.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-number-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("hello-play.xml"); logger.info("Packaged Test App"); return archive; } }
48,172
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountsEndpointClosingTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/AccountsEndpointClosingTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import junit.framework.Assert; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import javax.ws.rs.core.MultivaluedMap; import java.net.URL; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import org.junit.Ignore; /** * @author [email protected] - Orestis Tsakiridis */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AccountsEndpointClosingTest extends EndpointTest { private final static Logger logger = Logger.getLogger(AccountsEndpointClosingTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; String toplevelSid = "ACA0000000000000000000000000000000"; String toplevelKey = "77f8c12cc7b8f8423e5c38b035249166"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); @Before public void before() { stubFor(post(urlMatching("/visual-designer/services/notifications")).willReturn(aResponse().withStatus(200))); } // verify that acount-removal notifications are sent to the application server (RVD) @Test public void removeAccountAndSendNotifications() throws InterruptedException { String closedParentSid = "ACA1000000000000000000000000000000"; Client jersey = getClient(toplevelSid, toplevelKey); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/" + closedParentSid) ); MultivaluedMap<String,String> params = new MultivaluedMapImpl(); params.add("Status","closed"); ClientResponse response = resource.put(ClientResponse.class,params); Assert.assertEquals(200, response.getStatus()); // wait until all asynchronous request have been sent to RVD verify(6, postRequestedFor(urlMatching("/visual-designer/services/notifications")) .withHeader("Content-Type", containing("application/json")) //.withRequestBody(equalToJson("[{\"type\":\"accountClosed\",\"accountSid\":\"ACA1000000000000000000000000000005\"},{\"type\":\"accountClosed\",\"accountSid\":\"ACA1000000000000000000000000000004\"},{\"type\":\"accountClosed\",\"accountSid\":\"ACA1000000000000000000000000000003\"},{\"type\":\"accountClosed\",\"accountSid\":\"ACA1000000000000000000000000000002\"},{\"type\":\"accountClosed\",\"accountSid\":\"ACA1000000000000000000000000000001\"},{\"type\":\"accountClosed\",\"accountSid\":\"ACA1000000000000000000000000000000\"}]") ); } // verify that DID provider (nexmo) was contacted to cancel the numbers when the account is removed @Test public void removeAccountAndReleaseProvidedNumbers() { stubFor(post(urlMatching("/nexmo/number/cancel/.*/.*/US/12223334444")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(""))); stubFor(post(urlMatching("/nexmo/number/cancel/.*/.*/US/12223334445")) .willReturn(aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody(""))); String closedParentSid = "ACA2000000000000000000000000000000"; Client jersey = getClient(toplevelSid, toplevelKey); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/" + closedParentSid) ); MultivaluedMap<String,String> params = new MultivaluedMapImpl(); params.add("Status","closed"); ClientResponse response = resource.put(ClientResponse.class,params); Assert.assertEquals(200, response.getStatus()); // make sure the request reached nexmo verify(postRequestedFor(urlMatching("/nexmo/number/cancel/.*/.*/US/12223334444"))); verify(postRequestedFor(urlMatching("/nexmo/number/cancel/.*/.*/US/12223334445"))); // confirm that numbers that were not successfully released, are still in the database resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + closedParentSid + "/IncomingPhoneNumbers/PH00000000000000000000000000000002.json") ); response = resource.get(ClientResponse.class); Assert.assertEquals(200, response.getStatus()); } @Deployment(name = "AccountsEndpointClosingTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm-accountRemoval.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_account_removal_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
7,615
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProfilesEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/ProfilesEndpointTest.java
package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Before; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.BrokenTests; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResourceLinkHeaders; import com.sun.jersey.core.header.LinkHeader; /** * @author maria */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ProfilesEndpointTest extends EndpointTest { private final static Logger logger = Logger.getLogger(ProfilesEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static final String SUPER_ADMIN_ACCOUNT_SID = "ACae6e420f425248d6a26948c17a9e2acf"; private static final String ADMIN_ACCOUNT_SID = "AC574d775522c96f9aacacc5ca60c8c74g"; private static final String DEVELOPER_ACCOUNT_SID = "AC574d775522c96f9aacacc5ca60c8c74f"; private static final String AUTH_TOKEN = "77f8c12cc7b8f8423e5c38b035249166"; private static final String DEFAULT_PROFILE_SID = "PRae6e420f425248d6a26948c17a9e2acf"; private static final String SECONDARY_PROFILE_SID = "PRae6e420f425248d6a26948c17a9e2acg"; private static final String UNKNOWN_PROFILE_SID = "PRafbe225ad37541eba518a74248f0ac4d"; private static final String ORGANIZATION_SID = "ORafbe225ad37541eba518a74248f0ac4c"; private static final String UNKNOWN_ACCOUNT_SID = "AC1111225ad37541eba518a74248f0ac4d"; private static final String UNKNOWN_ORGANIZATION_SID = "OR1111225ad37541eba518a74248f0ac4d"; private static final String PROFILE_DOCUMENT="{ \"featureEnablement\": { \"DIDPurchase\": { \"allowedCountries\": [\"US\", \"CA\"] }, \"outboundPSTN\": { }, \"inboundPSTN\": { }, \"outboundSMS\": { }, \"inboundSMS\": { } }, \"sessionThrottling\": { \"PSTNCallsPerTime\": { \"events\" : 300, \"time\" : 30, \"timeUnit\" : \"days\" } } }"; private static final String UPDATE_PROFILE_DOCUMENT="{ \"featureEnablement\": { \"DIDPurchase\": { \"allowedCountries\": [\"PK\", \"CA\"] }, \"outboundPSTN\": { }, \"inboundPSTN\": { }, \"outboundSMS\": { }, \"inboundSMS\": { } }, \"sessionThrottling\": { \"PSTNCallsPerTime\": { \"events\" : 300, \"time\" : 30, \"timeUnit\" : \"days\" } } }"; private static final String INVALID_PROFILE_DOCUMENT="{ \"featureEnablement\": { \"DIDPurchase\": { \"allowedCountries\": [\"PKeuietue\", \"CA\"] }, \"outboundPSTN\": { }, \"inboundPSTN\": { }, \"outboundSMS\": { }, \"inboundSMS\": { } }, \"sessionThrottling\": { \"PSTNCallsPerTime\": { \"events\" : 300, \"time\" : 30, \"timeUnit\" : \"days\" } } }"; @Before public void before() { } /** * this test will try to Read single profile */ @Test public void getProfile(){ ClientResponse clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID); String responseBody = clientResponse.getEntity(String.class); logger.info("profile: "+responseBody); assertEquals(200, clientResponse.getStatus()); JsonObject jsonResponse = new JsonParser().parse(responseBody).getAsJsonObject(); assertNotNull(jsonResponse); } /** * getProfileList */ @Test public void getProfileList() { ClientResponse clientResponse = RestcommProfilesTool.getInstance().getProfileListClientResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN); String responseBody = clientResponse.getEntity(String.class); logger.info("profile list: "+responseBody); assertNotNull(clientResponse); assertEquals(200, clientResponse.getStatus()); JsonArray jsonArray = new JsonParser().parse(responseBody).getAsJsonArray(); assertNotNull(jsonArray); //as we have one default and one secondary profile and based on other tests creating profiles, we may have more assertTrue(jsonArray.size()>=2); } /** * this test will try to Read single profile with an unknown profile Sid */ @Test @Category(FeatureExpTests.class) public void getProfileUnknownSid(){ ClientResponse clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, UNKNOWN_PROFILE_SID); assertNotNull(clientResponse); assertEquals(404, clientResponse.getStatus()); } /** * super admin can read any profile * others can read profile applicatble only to them */ @Test @Category(FeatureExpTests.class) public void getProfilePermissionTest(){ // super admin account gets associated profile - should be able to get it ClientResponse clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID); assertNotNull(clientResponse); assertEquals(200, clientResponse.getStatus()); // super admin account gets not associated profile - should be able to get it clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, SECONDARY_PROFILE_SID); assertNotNull(clientResponse); assertEquals(200, clientResponse.getStatus()); // admin account gets associated profile - should be able to get it clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), ADMIN_ACCOUNT_SID, AUTH_TOKEN, SECONDARY_PROFILE_SID); assertNotNull(clientResponse); assertEquals(200, clientResponse.getStatus()); // admin account gets not associated profile - should not be able to get it clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID); assertNotNull(clientResponse); assertEquals(403, clientResponse.getStatus()); // dev account gets associated profile that is not explicitly assign to it but associated by inheritance - should be able to get it clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), DEVELOPER_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID); assertNotNull(clientResponse); assertEquals(200, clientResponse.getStatus()); // dev account gets un associated profile - should not be able to get it clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), DEVELOPER_ACCOUNT_SID, AUTH_TOKEN, SECONDARY_PROFILE_SID); assertNotNull(clientResponse); assertEquals(403, clientResponse.getStatus()); } /** * Create, Read And Update Profile Test */ @Test public void createReadUpdateDeleteProfileTest() throws IOException, URISyntaxException{ /* * create a profile */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().createProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, PROFILE_DOCUMENT); assertEquals(201, clientResponse.getStatus()); assertEquals(PROFILE_DOCUMENT, clientResponse.getEntity(String.class)); //extract profileSid of newly created profile Sid. URI location = clientResponse.getLocation(); assertNotNull(location); String profileLocation = location.toString(); String[] profileUriElements = profileLocation.split("/"); assertNotNull(profileUriElements); String newlyCreatedProfileSid = profileUriElements[profileUriElements.length-1]; /** * link default profile to dev account */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid, SUPER_ADMIN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /* * read newly created profile */ clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid); assertEquals(200, clientResponse.getStatus()); assertEquals(PROFILE_DOCUMENT, clientResponse.getEntity(String.class)); /* * update the profile */ clientResponse = RestcommProfilesTool.getInstance().updateProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid, UPDATE_PROFILE_DOCUMENT); assertEquals(200, clientResponse.getStatus()); assertEquals(UPDATE_PROFILE_DOCUMENT, clientResponse.getEntity(String.class)); /* * unlink a profile from an account */ response = RestcommProfilesTool.getInstance().unLinkProfileWithOverride(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid, SUPER_ADMIN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /* * delete the profile */ clientResponse = RestcommProfilesTool.getInstance().deleteProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid); assertEquals(200, clientResponse.getStatus()); /* * read again */ clientResponse = RestcommProfilesTool.getInstance().getProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid); assertEquals(404, clientResponse.getStatus()); } /** * createProfileTestInvalidSchema */ @Test @Category(FeatureExpTests.class) public void createProfileTestInvalidSchema(){ /* * create a profile with invalid schema */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().createProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, INVALID_PROFILE_DOCUMENT); assertEquals(400, clientResponse.getStatus()); } /** * updateProfileUnknownSidTest */ @Test @Category(FeatureExpTests.class) public void updateProfileUnknownSidTest(){ /* * update a profile with unknown sid */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().updateProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, UNKNOWN_PROFILE_SID, UPDATE_PROFILE_DOCUMENT); assertEquals(404, clientResponse.getStatus()); } /** * updateProfilePermissionTest */ @Test @Category(FeatureExpTests.class) public void updateProfilePermissionTest(){ /* * update a profile from admin account */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().updateProfileResponse(deploymentUrl.toString(), ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, UPDATE_PROFILE_DOCUMENT); assertEquals(403, clientResponse.getStatus()); /* * update a profile from dev account */ clientResponse = RestcommProfilesTool.getInstance().updateProfileResponse(deploymentUrl.toString(), DEVELOPER_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, UPDATE_PROFILE_DOCUMENT); assertEquals(403, clientResponse.getStatus()); } /** * updateDefaultProfileTest * updating default profile is not allowed */ @Test @Category(FeatureExpTests.class) public void updateDefaultProfileTest(){ /* * update default profile */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().updateProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, UPDATE_PROFILE_DOCUMENT); assertEquals(403, clientResponse.getStatus()); } /** * deleteDefaultProfileTest * deleteing default profile is not allowed */ @Test @Category(FeatureExpTests.class) public void deleteDefaultProfileTest(){ /* * delete default profile */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().deleteProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID); assertEquals(403, clientResponse.getStatus()); } /** * deleteProfilePermissionTest */ @Test @Category(FeatureExpTests.class) public void deleteProfilePermissionTest(){ /* * delete a profile from admin account */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().deleteProfileResponse(deploymentUrl.toString(), ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID); assertEquals(403, clientResponse.getStatus()); /* * delete a profile from Dev account */ clientResponse = RestcommProfilesTool.getInstance().deleteProfileResponse(deploymentUrl.toString(), DEVELOPER_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID); assertEquals(403, clientResponse.getStatus()); } /** * deleteProfileUnknownSidTest */ @Test @Category(FeatureExpTests.class) public void deleteProfileUnknownSidTest(){ /* * delete a profile with unknown sid */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().deleteProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, UNKNOWN_PROFILE_SID); assertEquals(404, clientResponse.getStatus()); } @Test @Category({FeatureExpTests.class, BrokenTests.class}) public void createExceedingProfileTest(){ String longProfile = new String(new char[10000001]); //admin tries to create profile ClientResponse clientResponse = RestcommProfilesTool.getInstance().createProfileResponse(deploymentUrl.toString(), ADMIN_ACCOUNT_SID, AUTH_TOKEN, longProfile); assertEquals(413, clientResponse.getStatus()); } @Test @Category(FeatureExpTests.class) public void createProfilePermissionTest(){ //admin tries to create profile ClientResponse clientResponse = RestcommProfilesTool.getInstance().createProfileResponse(deploymentUrl.toString(), ADMIN_ACCOUNT_SID, AUTH_TOKEN, PROFILE_DOCUMENT); assertEquals(403, clientResponse.getStatus()); //developer tries to create profile clientResponse = RestcommProfilesTool.getInstance().createProfileResponse(deploymentUrl.toString(), DEVELOPER_ACCOUNT_SID, AUTH_TOKEN, PROFILE_DOCUMENT); assertEquals(403, clientResponse.getStatus()); } /** * link/unlink a give Profile To an Account * @throws IOException * @throws ClientProtocolException * @throws URISyntaxException */ @Test public void linkUnLinkProfileToAccount() throws ClientProtocolException, IOException, URISyntaxException{ /* * link a profile to an account */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfileWithOverride(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, SECONDARY_PROFILE_SID, SUPER_ADMIN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /* * Get associated profile * from Accounts endpoint: * to verify association establishment. */ ClientResponse accountEndopintResponse = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, SUPER_ADMIN_ACCOUNT_SID); WebResourceLinkHeaders linkHeaders = accountEndopintResponse.getLinks(); logger.info("accountEndopintResponse WebResourceLinkHeaders: "+linkHeaders); assertNotNull(linkHeaders); LinkHeader linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("accountEndopintResponse WebResourceLinkHeaders linkHeader: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(SECONDARY_PROFILE_SID)); /* * unlink a profile from an account */ response = RestcommProfilesTool.getInstance().unLinkProfileWithOverride(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, SECONDARY_PROFILE_SID, SUPER_ADMIN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /* * Get associated profile * from Accounts endpoint: * to verify association removal */ accountEndopintResponse = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, SUPER_ADMIN_ACCOUNT_SID); linkHeaders = accountEndopintResponse.getLinks(); logger.info("accountEndopintResponse WebResourceLinkHeaders: "+linkHeaders); linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("accountEndopintResponse WebResourceLinkHeaders linkHeader: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(DEFAULT_PROFILE_SID)); } /** * link/unlink a give Profile To an Organization * @throws IOException * @throws ClientProtocolException * @throws URISyntaxException */ @Test public void linkUnLinkProfileToOrganization() throws ClientProtocolException, IOException, URISyntaxException{ /* * link a profile to an organizations */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, SECONDARY_PROFILE_SID, ORGANIZATION_SID, RestcommProfilesTool.AssociatedResourceType.ORGANIZATION); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /* * Get associated profile * from Organizations endpoint: * to verify association establishment. */ ClientResponse orgEndopintResponse = RestcommOrganizationsTool.getInstance().getOrganizationResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, ORGANIZATION_SID); WebResourceLinkHeaders linkHeaders = orgEndopintResponse.getLinks(); logger.info("accountEndopintResponse WebResourceLinkHeaders: "+linkHeaders); assertNotNull(linkHeaders); LinkHeader linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("accountEndopintResponse WebResourceLinkHeaders linkHeader: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(SECONDARY_PROFILE_SID)); /* * unlink a profile from an organization */ response = RestcommProfilesTool.getInstance().unLinkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, SECONDARY_PROFILE_SID, ORGANIZATION_SID, RestcommProfilesTool.AssociatedResourceType.ORGANIZATION); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /* * Get associated profile * from Organizations endpoint: * to verify association removal. */ orgEndopintResponse = RestcommOrganizationsTool.getInstance().getOrganizationResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, ORGANIZATION_SID); linkHeaders = orgEndopintResponse.getLinks(); logger.info("orgEndopintResponse WebResourceLinkHeaders: "+linkHeaders); linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("orgEndopintResponse WebResourceLinkHeaders linkHeader: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(DEFAULT_PROFILE_SID)); } /** * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ @Test @Category(FeatureExpTests.class) public void linkUnLinkProfilePermissionTest() throws ClientProtocolException, IOException, URISyntaxException{ /* * link a profile by admin account */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, ORGANIZATION_SID, RestcommProfilesTool.AssociatedResourceType.ORGANIZATION); assertEquals(403, response.getStatusLine().getStatusCode()); /* * unlink a profile by dev account */ response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), DEVELOPER_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, ORGANIZATION_SID, RestcommProfilesTool.AssociatedResourceType.ORGANIZATION); assertEquals(403, response.getStatusLine().getStatusCode()); } /** * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ @Test @Category(FeatureExpTests.class) public void linkUnLinkProfileUnknownProfileSidTest() throws ClientProtocolException, IOException, URISyntaxException{ /* * link a profile with unknown profile sid */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, UNKNOWN_PROFILE_SID, ORGANIZATION_SID, RestcommProfilesTool.AssociatedResourceType.ORGANIZATION); assertEquals(404, response.getStatusLine().getStatusCode()); /* * unlink a profile with unknown profile sid */ response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, UNKNOWN_PROFILE_SID, ORGANIZATION_SID, RestcommProfilesTool.AssociatedResourceType.ORGANIZATION); assertEquals(404, response.getStatusLine().getStatusCode()); } /** * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ @Test @Category(FeatureExpTests.class) public void linkUnLinkProfileUnknownAccountSidTest() throws ClientProtocolException, IOException, URISyntaxException{ /* * link a profile with unknown account sid */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, UNKNOWN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); assertEquals(404, response.getStatusLine().getStatusCode()); /* * unlink a profile with unknown account sid */ response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, UNKNOWN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); assertEquals(404, response.getStatusLine().getStatusCode()); } /** * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ @Test @Category(FeatureExpTests.class) public void linkUnLinkProfileUnknownOrganizationSidTest() throws ClientProtocolException, IOException, URISyntaxException{ /* * link a profile with unknown organization sid */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, UNKNOWN_ORGANIZATION_SID, RestcommProfilesTool.AssociatedResourceType.ORGANIZATION); assertEquals(404, response.getStatusLine().getStatusCode()); /* * unlink a profile with unknown organization sid */ response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, UNKNOWN_ORGANIZATION_SID, RestcommProfilesTool.AssociatedResourceType.ORGANIZATION); assertEquals(404, response.getStatusLine().getStatusCode()); } /** * test removal of association onnce we delete a profile * @throws URISyntaxException * @throws IOException * @throws ClientProtocolException */ @Test @Category(FeatureAltTests.class) public void testRemovalOfAssociationOnDeleteProfile() throws ClientProtocolException, IOException, URISyntaxException{ /* * create a profile */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().createProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, PROFILE_DOCUMENT); assertEquals(201, clientResponse.getStatus()); assertEquals(PROFILE_DOCUMENT, clientResponse.getEntity(String.class)); //extract profileSid of newly created profile Sid. URI location = clientResponse.getLocation(); assertNotNull(location); String profileLocation = location.toString(); String[] profileUriElements = profileLocation.split("/"); assertNotNull(profileUriElements); String newlyCreatedProfileSid = profileUriElements[profileUriElements.length-1]; /* * link this profile to an account */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid, ADMIN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); assertEquals(200, response.getStatusLine().getStatusCode()); /* * delete the profile */ clientResponse = RestcommProfilesTool.getInstance().deleteProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid); assertEquals(200, clientResponse.getStatus()); /* * Get associated profile * from Accounts endpoint: * to verify association was removed. */ ClientResponse accountEndopintResponse = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, ADMIN_ACCOUNT_SID); WebResourceLinkHeaders linkHeaders = accountEndopintResponse.getLinks(); LinkHeader linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("linkHeader after deleteing profile: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(DEFAULT_PROFILE_SID)); } @Test public void getProfileSchemaTest() throws Exception { ClientResponse clientResponse = RestcommProfilesTool.getInstance().getProfileSchema(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN); assertEquals(200, clientResponse.getStatus()); String str = clientResponse.getEntity(String.class); assertNotNull(str); JsonObject jsonResponse = new JsonParser().parse(str).getAsJsonObject(); assertNotNull(jsonResponse); } /** * link a Profile To an Account which is already linked to a different profile * @throws IOException * @throws ClientProtocolException * @throws URISyntaxException */ @Test @Category(FeatureAltTests.class) public void linkAccountToNewProfile() throws ClientProtocolException, IOException, URISyntaxException{ /** * link default profile to dev account */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, DEVELOPER_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /** * Get associated profile * from Accounts endpoint: * to verify association establishment. */ ClientResponse accountEndopintResponse = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEVELOPER_ACCOUNT_SID); WebResourceLinkHeaders linkHeaders = accountEndopintResponse.getLinks(); logger.info("accountEndopintResponse WebResourceLinkHeaders: "+linkHeaders); assertNotNull(linkHeaders); LinkHeader linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("accountEndopintResponse WebResourceLinkHeaders linkHeader: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(DEFAULT_PROFILE_SID)); /** * Create a new profile */ ClientResponse clientResponse = RestcommProfilesTool.getInstance().createProfileResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, PROFILE_DOCUMENT); assertEquals(201, clientResponse.getStatus()); assertEquals(PROFILE_DOCUMENT, clientResponse.getEntity(String.class)); //extract profileSid of newly created profile Sid. URI location = clientResponse.getLocation(); assertNotNull(location); String profileLocation = location.toString(); String[] profileUriElements = profileLocation.split("/"); assertNotNull(profileUriElements); String newlyCreatedProfileSid = profileUriElements[profileUriElements.length-1]; /** * link newlyCreated profile to dev account. */ response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, newlyCreatedProfileSid, DEVELOPER_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /** * Get associated profile * from Accounts endpoint: * to verify new association is establishment. */ accountEndopintResponse = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEVELOPER_ACCOUNT_SID); linkHeaders = accountEndopintResponse.getLinks(); logger.info("accountEndopintResponse WebResourceLinkHeaders: "+linkHeaders); assertNotNull(linkHeaders); linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("accountEndopintResponse WebResourceLinkHeaders linkHeader: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(newlyCreatedProfileSid)); } /** * link a Profile To an Account which is already linked to the same profile. * @throws IOException * @throws ClientProtocolException * @throws URISyntaxException */ @Test @Category(FeatureAltTests.class) public void linkAccountAgainToSameProfile() throws ClientProtocolException, IOException, URISyntaxException{ /** * link default profile to admin account */ HttpResponse response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, ADMIN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /** * Get associated profile * from Accounts endpoint: * to verify association establishment. */ ClientResponse accountEndopintResponse = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, ADMIN_ACCOUNT_SID); WebResourceLinkHeaders linkHeaders = accountEndopintResponse.getLinks(); logger.info("accountEndopintResponse WebResourceLinkHeaders: "+linkHeaders); assertNotNull(linkHeaders); LinkHeader linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("accountEndopintResponse WebResourceLinkHeaders linkHeader: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(DEFAULT_PROFILE_SID)); /** * link default profile to admin account again. */ response = RestcommProfilesTool.getInstance().linkProfile(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, DEFAULT_PROFILE_SID, ADMIN_ACCOUNT_SID, RestcommProfilesTool.AssociatedResourceType.ACCOUNT); logger.info("HttpResponse: "+response); assertEquals(200, response.getStatusLine().getStatusCode()); /** * Get associated profile * from Accounts endpoint: * to verify association is still established. */ accountEndopintResponse = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), SUPER_ADMIN_ACCOUNT_SID, AUTH_TOKEN, ADMIN_ACCOUNT_SID); linkHeaders = accountEndopintResponse.getLinks(); logger.info("accountEndopintResponse WebResourceLinkHeaders: "+linkHeaders); assertNotNull(linkHeaders); linkHeader = linkHeaders.getLink(RestcommProfilesTool.PROFILE_REL_TYPE); logger.info("accountEndopintResponse WebResourceLinkHeaders linkHeader: "+linkHeader); assertNotNull(linkHeader); assertTrue(linkHeader.getUri().toString().contains(DEFAULT_PROFILE_SID)); } @Deployment(name = "ProfilesEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_accounts_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
34,723
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MultitenancyDenyAccessApiTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/MultitenancyDenyAccessApiTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureExpTests; import junit.framework.Assert; import wiremock.org.apache.http.client.ClientProtocolException; /** * The aim of this scenario is to ensure that an account can not manage information from parent accounts or from accounts in the * same level. Accounts and Applications endpoints are tested separately due its particularities. * * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(FeatureExpTests.class) public class MultitenancyDenyAccessApiTest { private final static Logger logger = Logger.getLogger(MultitenancyDenyAccessApiTest.class); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private final static String primaryUsername = "[email protected]"; private final static String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private final static String secondaryAccountSid = "AC97c556cd186f58a08520fe5391c54f36"; private final static String adminApplicationSid = "APf9edf166b5ed4fe58174135df3807601"; private final static String secondaryApplicationSid = "AP908a3a52b8a548cc9db97f1a1dd9d23b"; private final static String accountsPassword = "RestComm"; private final static int httpUnauthorized = 403; private final static String apiPath = "2012-04-24/Accounts/"; private final static String jsonExtension = ".json"; private enum Endpoint { INCOMING_PHONE_NUMBERS("IncomingPhoneNumbers", true, true, true, true, new HashMap<String,String>(){{ put("PhoneNumber","1111"); put("AreaCode","100"); }}, "PNff22dc8d1cdf4d449d666ac09f0bb110", "PN9f9cf955aeb94ebb9d2e09cead5683a4"), CALLS("Calls", true, true, false, false, new HashMap<String,String>(){{ put("From","bob"); put("To","alice"); put("Url","/restcomm/url"); }}, "CA9aa1b61e9b864477a820d5c1c9d9bb7d", "CAc6a057e16aa74cb0923c538725ffcf01"), SMS_MESSAGES("SMS/Messages", true, true, false, false, new HashMap<String,String>(){{ put("From","bob"); put("To","alice"); put("Body","Hi"); }}, "SMa272937700b3461bb5d68a3569c61bf1", "SMa272937700b3461bb5d68a3569c61bf2"), CLIENTS("Clients", true, true, true, true, new HashMap<String,String>(){{ put("Login","test"); put("Password","1234"); }}, "CLe95ba029114147c9a9aa42becd0518c0", "CL9bfcb54ead2b44e6bae03f337967a249"), OUTGOING_CALLER_IDS("OutgoingCallerIds", true, true, false, true, new HashMap<String,String>(){{ put("PhoneNumber","1111"); }}, "PNfa413fdbf3944932b37bef4bd661c7f7", "PN5a33fa8232d84578af023b1e81e30f67"), RECORDINGS("Recordings", true, false, false, false, null, "REacaffdf107da4dc3926e37bddfff44ed", "REacaffdf107da4dc3926e37bddfff44ee"), TRANSCRIPTIONS("Transcriptions", true, false, false, true, null, "TRacaffdf107da4dc3926e37bddfff44ee", "TRacaffdf107da4dc3926e37bddfff44ed"), NOTIFICATIONS("Notifications", true, false, false, false, null, "NO8927433ce9514b70ac0a76cd36601b9e", "NO8927433ce9514b70ac0a76cd36601b9d"); String name; boolean get; boolean postList; boolean postElement; boolean delete; HashMap<String, String> postParams; String elementSameAccount; String elementSubaccount; Endpoint(String name, boolean get, boolean postList, boolean postElement, boolean delete, HashMap<String,String> postParams, String elementSameAccount, String elementSubaccount){ this.name = name; this.get = get; this.postList = postList; this.postElement = postElement; this.delete = delete; this.postParams = postParams; this.elementSameAccount = elementSameAccount; this.elementSubaccount = elementSubaccount; } } @Test public void getListParentAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + adminAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.get) { String url = baseUrl + endpoint.name + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().get(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (getListParentAccount). Status code = " + statusCode); } } } @Test public void getListSameLevelAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + secondaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.get) { String url = baseUrl + endpoint.name + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().get(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (getListSameLevelAccount). Status code = " + statusCode); } } } @Test public void postListParentAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + adminAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.postList) { String url = baseUrl + endpoint.name + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().post(url, primaryUsername, accountsPassword, endpoint.postParams); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (postListParentAccount). Status code = " + statusCode); } } } @Test public void postListSameLevelAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + secondaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.postList) { String url = baseUrl + endpoint.name + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().post(url, primaryUsername, accountsPassword, endpoint.postParams); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (postListSameLevelAccount). Status code = " + statusCode); } } } @Test public void getElementParentAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + adminAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.get) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSameAccount + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().get(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (getElementParentAccount). Status code = " + statusCode); } } } @Test public void getElementSameLevelAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + secondaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.get) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSubaccount + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().get(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (getElementSameLevelAccount). Status code = " + statusCode); } } } @Test public void postElementParentAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + adminAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.postElement) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSameAccount; int statusCode = RestcommMultitenancyTool.getInstance().post(url, primaryUsername, accountsPassword, endpoint.postParams); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (postElementParentAccount). Status code = " + statusCode); } } } @Test public void postElementSameLevelAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + secondaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.postElement) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSubaccount + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().post(url, primaryUsername, accountsPassword, endpoint.postParams); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (postElementSameLevelAccount). Status code = " + statusCode); } } } @Test public void deleteElementParentAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + adminAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.delete) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSameAccount; int statusCode = RestcommMultitenancyTool.getInstance().delete(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (deleteElementParentAccount). Status code = " + statusCode); } } } @Test public void deleteElementSameLevelAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + secondaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.delete) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSubaccount; int statusCode = RestcommMultitenancyTool.getInstance().delete(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); logger.info("Tested endpoint " + endpoint.name + " (deleteElementSameLevelAccount). Status code = " + statusCode); } } } @Test public void accountsApi() throws ClientProtocolException, IOException { // Parent account String baseUrl = deploymentUrl.toString() + apiPath.substring(0, apiPath.length()-1); int statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + jsonExtension + "/" + adminAccountSid, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + jsonExtension + "/" + adminAccountSid, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("EmailAddress","[email protected]"); put("Password","RestComm");}}); assertTrue(statusCode == httpUnauthorized); Map<String,String> updateParams = new HashMap<String,String>(); updateParams.put("Status", "closed"); statusCode = RestcommMultitenancyTool.getInstance().update(baseUrl + jsonExtension + "/" + adminAccountSid, primaryUsername, accountsPassword, updateParams); Assert.assertEquals(httpUnauthorized, statusCode); // Same level account statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + jsonExtension + "/" + secondaryAccountSid, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + jsonExtension+ "/" + secondaryAccountSid, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("EmailAddress","[email protected]"); put("Password","RestComm");}}); assertTrue(statusCode == httpUnauthorized); updateParams = new HashMap<String,String>(); updateParams.put("Status", "closed"); statusCode = RestcommMultitenancyTool.getInstance().update(baseUrl + jsonExtension + "/" + secondaryAccountSid, primaryUsername, accountsPassword,updateParams); assertTrue(statusCode == httpUnauthorized); } @Test public void applicationsApi() throws ClientProtocolException, IOException { // Parent account String baseUrl = deploymentUrl.toString() + apiPath + adminAccountSid + "/Applications"; int statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + jsonExtension, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + jsonExtension, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("FriendlyName","TESTABC"); }}); assertTrue(statusCode == httpUnauthorized); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + "/" + adminApplicationSid + jsonExtension, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("FriendlyName","TESTABC"); }}); assertTrue(statusCode == httpUnauthorized); Map<String,String> updateParams = new HashMap<String,String>(); updateParams.put("Status", "closed"); statusCode = RestcommMultitenancyTool.getInstance().update(baseUrl + "/" + adminApplicationSid + jsonExtension, primaryUsername, accountsPassword, updateParams ); assertTrue(statusCode == httpUnauthorized); // Same level account baseUrl = deploymentUrl.toString() + apiPath + secondaryAccountSid + "/Applications"; statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + jsonExtension, primaryUsername, accountsPassword); assertTrue(statusCode == httpUnauthorized); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + jsonExtension, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("FriendlyName","TESTABC"); }}); assertTrue(statusCode == httpUnauthorized); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + "/" + secondaryApplicationSid + jsonExtension, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("FriendlyName","TESTABC"); }}); assertTrue(statusCode == httpUnauthorized); updateParams = new HashMap<String,String>(); updateParams.put("Status", "closed"); statusCode = RestcommMultitenancyTool.getInstance().update(baseUrl + "/" + secondaryApplicationSid + jsonExtension, primaryUsername, accountsPassword, updateParams); assertTrue(statusCode == httpUnauthorized); } @Deployment(name = "MultitenancyDenyAccessApiTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_multitenancyTest", "data/hsql/restcomm.script"); return archive; } }
18,178
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GeolocationEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/GeolocationEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.testsuite.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.equalTo; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Locale; import javax.ws.rs.core.MultivaluedMap; import com.github.tomakehurst.wiremock.junit.WireMockRule; import org.apache.http.client.ClientProtocolException; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.dao.entities.Geolocation; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.dao.Sid; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.sun.jersey.core.util.MultivaluedMapImpl; /** * @author <a href="mailto:[email protected]"> Fernando Mendioroz </a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class GeolocationEndpointTest { private static final Logger logger = Logger.getLogger(GeolocationEndpointTest.class); private static final String version = Version.getVersion(); private static final String ImmediateGT = Geolocation.GeolocationType.Immediate.toString(); private static final String NotificationGT = Geolocation.GeolocationType.Notification.toString(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @After public void after() throws InterruptedException { wireMockRule.resetRequests(); Thread.sleep(1000); } String gmlcResponse = "mcc=598,mnc=1,lac=320,cellid=521,aol=0,vlrNumber=598001,latitude=35.349781,longitude=87.754320,civicAddress=Avenue2501"; @Test public void testCreateAndGetImmediateGeolocation() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Immediate Geolocation attributes for this method String deviceIdentifier; // Test create Immediate type of Geolocation via POST (only mandatory parameters) // Parameter values Assignment MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); // HTTP POST Geolocation creation with given parameters values and those returned via GMLC stub JsonObject geolocationJson = RestcommGeolocationsTool.getInstance().createImmediateGeolocation(deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); Sid geolocationSid = new Sid(geolocationJson.get("sid").getAsString()); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(ImmediateGT)); assertTrue(geolocationJson.get("response_status") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals("521")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString().equals("320")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString().equals("598")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString().equals("1")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString().equals("598001")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString().equals("0")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString().equals("35.349781")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString().equals("87.754320")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString().equals("Avenue2501")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type") == null); assertTrue(geolocationJson.get("last_geolocation_response") == null); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Test asserts via GET to a Geolocation list JsonArray immediateGeolocationsListJson = RestcommGeolocationsTool.getInstance() .getGeolocations(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid); geolocationJson = immediateGeolocationsListJson.get(0).getAsJsonObject(); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(ImmediateGT)); assertTrue(geolocationJson.get("response_status") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals("521")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString().equals("320")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString().equals("598")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString().equals("1")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString().equals("598001")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString().equals("0")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString().equals("35.349781")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString().equals("87.754320")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString().equals("Avenue2501")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type") == null); assertTrue(geolocationJson.get("last_geolocation_response") == null); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Remove created Geolocation via HTTP DELETE RestcommGeolocationsTool.getInstance().deleteImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); } @Test @Category(FeatureAltTests.class) public void testCreateNotApiCompliantImmediateGeolocation() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Immediate Geolocation attributes for this method String deviceIdentifier; // Test create Immediate type of Geolocation via POST with one missing mandatory parameter // Parameter values Assignment, StatusCallback missing MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); Sid rejectedGeolocationSid = null; // HTTP POST Geolocation creation with given parameters values try { JsonObject missingParamGeolocationJson = RestcommGeolocationsTool.getInstance().createImmediateGeolocation( deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); rejectedGeolocationSid = new Sid(missingParamGeolocationJson.get("sid").getAsString()); JsonObject rejectedGeolocationJson = RestcommGeolocationsTool.getInstance().getImmediateGeolocation( deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, rejectedGeolocationSid.toString()); assertTrue(rejectedGeolocationJson == null); } catch (Exception exception) { // Checking Test asserts via HTTP GET (no record found as POST returned a response status of 400 Bad Request) assertTrue(rejectedGeolocationSid == null); logger.info("Exception during HTTP POST: " + exception.getMessage()); } // Test create Immediate type of Geolocation via POST with one prohibited parameter @SuppressWarnings("unused") String eventGeofenceLatitude = null; geolocationParams.add("EventGeofenceLatitude", eventGeofenceLatitude = "45.426280"); // "EventGeofenceLatitude" // applicable only for Notification // type of Geolocation // HTTP POST Geolocation creation with given parameters values try { JsonObject prohibitedParamGeolocationJson = RestcommGeolocationsTool.getInstance().createImmediateGeolocation( deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); rejectedGeolocationSid = new Sid(prohibitedParamGeolocationJson.get("sid").getAsString()); JsonObject rejectedGeolocationJson = RestcommGeolocationsTool.getInstance().getImmediateGeolocation( deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, rejectedGeolocationSid.toString()); assertTrue(rejectedGeolocationJson == null); } catch (Exception exception) { // Checking Test asserts via HTTP GET (no record found as POST is rejected) assertTrue(rejectedGeolocationSid == null); logger.info("Exception during HTTP POST: " + exception.getMessage()); } } @Test public void testUpdateImmediateGeolocation() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Geolocation attributes String deviceIdentifier, responseStatus, cellId, locationAreaCode, mobileCountryCode, mobileNetworkCode, networkEntityAddress, ageOfLocationInfo, deviceLatitude, deviceLongitude, accuracy, internetAddress, physicalAddress, formattedAddress, locationTimestamp, geolocationPositioningType, lastGeolocationResponse; // Create Immediate type of Geolocation via POST // Parameter values Assignment MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); // HTTP POST Geolocation creation with given parameters values and those returned via GMLC stub JsonObject geolocationJson = RestcommGeolocationsTool.getInstance().createImmediateGeolocation(deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); Sid geolocationSid = new Sid(geolocationJson.get("sid").getAsString()); // Define new values to the application attributes (POST test) MultivaluedMap<String, String> geolocationParamsUpdate = new MultivaluedMapImpl(); geolocationParamsUpdate.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParamsUpdate.add("DesiredAccuracy", "Low"); geolocationParamsUpdate.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); geolocationParamsUpdate.add("ResponseStatus", responseStatus = "successfull"); geolocationParamsUpdate.add("CellId", cellId = "12345"); geolocationParamsUpdate.add("LocationAreaCode", locationAreaCode = "321"); geolocationParamsUpdate.add("MobileCountryCode", mobileCountryCode = "749"); geolocationParamsUpdate.add("MobileNetworkCode", mobileNetworkCode = "01"); geolocationParamsUpdate.add("NetworkEntityAddress", networkEntityAddress = "5980042343201"); geolocationParamsUpdate.add("LocationAge", ageOfLocationInfo = "0"); geolocationParamsUpdate.add("DeviceLatitude", deviceLatitude = "-34.908134"); geolocationParamsUpdate.add("DeviceLongitude", deviceLongitude = "-55.908134"); geolocationParamsUpdate.add("Accuracy", accuracy = "75"); geolocationParamsUpdate.add("InternetAddress", internetAddress = "2001:0:9d38:6ab8:30a5:1c9d:58c6:5898"); geolocationParamsUpdate.add("PhysicalAddress", physicalAddress = "D8-97-BA-19-02-D8"); geolocationParamsUpdate.add("FormattedAddress", formattedAddress = "Avenida Brasil 2681, 11500, Montevideo, Uruguay"); geolocationParamsUpdate.add("LocationTimestamp", locationTimestamp = "2016-04-17T20:28:40.690-03:00"); geolocationParamsUpdate.add("Radius", "200"); geolocationParamsUpdate.add("GeolocationPositioningType", geolocationPositioningType = "Network"); geolocationParamsUpdate.add("LastGeolocationResponse", lastGeolocationResponse = "false"); geolocationParamsUpdate.add("Cause", "Not API Compliant"); // Update Geolocation via POST RestcommGeolocationsTool.getInstance().updateImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString(), geolocationParamsUpdate, false); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); DateTime dateTime = dtf.parseDateTime(locationTimestamp); SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); locationTimestamp = df.format(dateTime.toDate()); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equalsIgnoreCase(ImmediateGT)); assertTrue(geolocationJson.get("response_status").getAsString().equals(responseStatus)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals(cellId)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString() .equals(locationAreaCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString() .equals(mobileCountryCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString() .equals(mobileNetworkCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString() .equals(networkEntityAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString() .equals(ageOfLocationInfo)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString() .equals(deviceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString() .equals(deviceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy").getAsString().equals(accuracy)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address").getAsString() .equals(internetAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address").getAsString() .equals(physicalAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString() .equals(formattedAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp").getAsString() .equals(locationTimestamp)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type").getAsString().equals(geolocationPositioningType)); assertTrue(geolocationJson.get("last_geolocation_response").getAsString().equals(lastGeolocationResponse)); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Define new values for the Geolocation attributes (PUT test) geolocationParamsUpdate = new MultivaluedMapImpl(); geolocationParamsUpdate.add("DesiredAccuracy", "Average"); geolocationParamsUpdate.add("StatusCallback", "http://192.1.2.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); geolocationParamsUpdate.add("ResponseStatus", responseStatus = "successfull"); geolocationParamsUpdate.add("CellId", cellId = "55777"); geolocationParamsUpdate.add("LocationAreaCode", locationAreaCode = "707"); geolocationParamsUpdate.add("MobileCountryCode", mobileCountryCode = "748"); geolocationParamsUpdate.add("MobileNetworkCode", mobileNetworkCode = "03"); geolocationParamsUpdate.add("NetworkEntityAddress", networkEntityAddress = "598003245701"); geolocationParamsUpdate.add("LocationAge", ageOfLocationInfo = "1"); geolocationParamsUpdate.add("DeviceLatitude", deviceLatitude = "43 38 19.39"); geolocationParamsUpdate.add("DeviceLongitude", deviceLongitude = "-170 21 10.02"); geolocationParamsUpdate.add("Accuracy", accuracy = "25"); geolocationParamsUpdate.add("InternetAddress", internetAddress = "180.7.2.141"); geolocationParamsUpdate.add("PhysicalAddress", physicalAddress = "A8-77-CA-29-32-D1"); geolocationParamsUpdate.add("FormattedAddress", formattedAddress = "Avenida Italia 2681, 11100, Montevideo, Uruguay"); geolocationParamsUpdate.add("LocationTimestamp", locationTimestamp = "2016-04-17T20:31:27.790-08:00"); geolocationParamsUpdate.add("Radius", "100"); geolocationParamsUpdate.add("GeolocationPositioningType", geolocationPositioningType = "Network"); geolocationParamsUpdate.add("LastGeolocationResponse", lastGeolocationResponse = "true"); geolocationParamsUpdate.add("Cause", "API Not Compliant"); // Update Geolocation via PUT RestcommGeolocationsTool.getInstance().updateImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString(), geolocationParamsUpdate, true); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); dateTime = dtf.parseDateTime(locationTimestamp); locationTimestamp = df.format(dateTime.toDate()); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(ImmediateGT)); assertTrue(geolocationJson.get("response_status").getAsString().equals(responseStatus)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals(cellId)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString() .equals(locationAreaCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString() .equals(mobileCountryCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString() .equals(mobileNetworkCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString() .equals(networkEntityAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString() .equals(ageOfLocationInfo)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString() .equals(deviceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString() .equals(deviceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy").getAsString().equals(accuracy)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address").getAsString() .equals(internetAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address").getAsString() .equals(physicalAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString() .equals(formattedAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp").getAsString() .equals(locationTimestamp)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type").getAsString().equals(geolocationPositioningType)); assertTrue(geolocationJson.get("last_geolocation_response").getAsString().equals(lastGeolocationResponse)); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Remove created & updated Geolocation via HTTP DELETE RestcommGeolocationsTool.getInstance().deleteImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); } @Test @Category(FeatureAltTests.class) public void testNotApiCompliantUpdateImmediateGeolocation() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Geolocation attributes String deviceIdentifier, responseStatus, cellId, locationAreaCode, mobileCountryCode, mobileNetworkCode, networkEntityAddress, ageOfLocationInfo, deviceLatitude, deviceLongitude, accuracy, internetAddress, physicalAddress, formattedAddress, locationTimestamp = "2016-04-17T20:28:40.690-03:00", geolocationPositioningType, lastGeolocationResponse; // Create Immediate type of Geolocation via POST // Parameter values Assignment MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); // HTTP POST Geolocation creation with given parameters values and those returned via GMLC stub JsonObject geolocationJson = RestcommGeolocationsTool.getInstance().createImmediateGeolocation(deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); Sid geolocationSid = new Sid(geolocationJson.get("sid").getAsString()); DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); DateTime dateTime = dtf.parseDateTime(locationTimestamp); SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); locationTimestamp = df.format(dateTime.toDate()); // Define malformed values for the Geolocation attributes (PUT test to fail) MultivaluedMap<String, String> geolocationParamsUpdate = new MultivaluedMapImpl(); geolocationParamsUpdate.add("DeviceLatitude", deviceLatitude = "North 72.908134"); // WGS84 not compliant geolocationParamsUpdate.add("DeviceLongitude", deviceLongitude = "170.908134"); // Update failed Geolocation via PUT RestcommGeolocationsTool.getInstance().updateImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString(), geolocationParamsUpdate, true); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("source") == null); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(ImmediateGT)); assertTrue(geolocationJson.get("response_status").getAsString().equalsIgnoreCase("failed")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type") == null); assertTrue(geolocationJson.get("last_geolocation_response") == null); assertTrue(geolocationJson.get("cause") != null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Define new values for the Geolocation attributes (PUT test) geolocationParamsUpdate = new MultivaluedMapImpl(); geolocationParamsUpdate.add("DesiredAccuracy", "High"); geolocationParamsUpdate.add("StatusCallback", "http://192.1.2.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); geolocationParamsUpdate.add("ResponseStatus", responseStatus = "successfull"); geolocationParamsUpdate.add("CellId", cellId = "34580"); geolocationParamsUpdate.add("LocationAreaCode", locationAreaCode = "709"); geolocationParamsUpdate.add("MobileCountryCode", mobileCountryCode = "748"); geolocationParamsUpdate.add("MobileNetworkCode", mobileNetworkCode = "01"); geolocationParamsUpdate.add("NetworkEntityAddress", networkEntityAddress = "598003245702"); geolocationParamsUpdate.add("LocationAge", ageOfLocationInfo = "1"); geolocationParamsUpdate.add("DeviceLatitude", deviceLatitude = "S43\u00b038'19.39''"); geolocationParamsUpdate.add("DeviceLongitude", deviceLongitude = "E169\u00b028'49.07''"); geolocationParamsUpdate.add("Accuracy", accuracy = "25"); geolocationParamsUpdate.add("InternetAddress", internetAddress = "180.7.2.141"); geolocationParamsUpdate.add("PhysicalAddress", physicalAddress = "A8-77-CA-29-32-D1"); geolocationParamsUpdate.add("FormattedAddress", formattedAddress = "Avenida Italia 2681, 11100, Montevideo, Uruguay"); geolocationParamsUpdate.add("LocationTimestamp", locationTimestamp = "2016-04-17T20:31:28.388-05:00"); geolocationParamsUpdate.add("Radius", "5"); geolocationParamsUpdate.add("GeolocationPositioningType", geolocationPositioningType = "GPS"); geolocationParamsUpdate.add("LastGeolocationResponse", lastGeolocationResponse = "true"); geolocationParamsUpdate.add("Cause", "API Not Compliant"); // Update Geolocation via PUT // previous failed location is composed again with new proper geolocation data values RestcommGeolocationsTool.getInstance().updateImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString(), geolocationParamsUpdate, true); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); dateTime = dtf.parseDateTime(locationTimestamp); locationTimestamp = df.format(dateTime.toDate()); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(ImmediateGT)); assertTrue(geolocationJson.get("response_status").getAsString().equals(responseStatus)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals(cellId)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString() .equals(locationAreaCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString() .equals(mobileCountryCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString() .equals(mobileNetworkCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString() .equals(networkEntityAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString() .equals(ageOfLocationInfo)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString() .equals(deviceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString() .equals(deviceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy").getAsString().equals(accuracy)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address").getAsString() .equals(internetAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address").getAsString() .equals(physicalAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString() .equals(formattedAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp").getAsString() .equals(locationTimestamp)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type").getAsString().equals(geolocationPositioningType)); assertTrue(geolocationJson.get("last_geolocation_response").getAsString().equals(lastGeolocationResponse)); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Remove created & updated Geolocation via HTTP DELETE RestcommGeolocationsTool.getInstance().deleteImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); } @Test public void testDeleteImmediateGeolocation() throws IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Immediate Geolocation attributes for this method String deviceIdentifier; // Create Immediate type of Geolocation via POST // Parameter values Assignment MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParams.add("DesiredAccuracy", "High"); geolocationParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); geolocationParams.add("ResponseStatus", "successfull"); geolocationParams.add("Accuracy", "5"); geolocationParams.add("InternetAddress", "194.87.1.127"); geolocationParams.add("PhysicalAddress", "D8-97-BA-19-02-D8"); geolocationParams.add("LocationTimestamp", "2016-04-15"); geolocationParams.add("Radius", "200"); geolocationParams.add("GeolocationPositioningType", "GPS"); geolocationParams.add("LastGeolocationResponse", "true"); geolocationParams.add("Cause", "Not API Compliant"); // HTTP POST Geolocation creation with given parameters values and those returned via GMLC stub JsonObject geolocationJson = RestcommGeolocationsTool.getInstance().createImmediateGeolocation(deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); Sid geolocationSid = new Sid(geolocationJson.get("sid").getAsString()); // Remove created Geolocation via HTTP DELETE RestcommGeolocationsTool.getInstance().deleteImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); // Remove checking Test asserts via HTTP GET geolocationJson = RestcommGeolocationsTool.getInstance().getImmediateGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); assertTrue(geolocationJson == null); } @Test public void testCreateAndGetNotificationGeolocation() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Geolocation attributes for this test method String deviceIdentifier, eventGeofenceLatitude, eventGeofenceLongitude; // Test create Notification type of Geolocation via POST (only mandatory parameters) // Parameter values Assignment MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParams.add("EventGeofenceLatitude", eventGeofenceLatitude = "45.426280"); geolocationParams.add("EventGeofenceLongitude", eventGeofenceLongitude = "-80.566560"); geolocationParams.add("GeofenceRange", "300"); geolocationParams.add("GeofenceEvent", "in"); geolocationParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); // HTTP POST Geolocation creation with given parameters values and those returned via GMLC stub JsonObject geolocationJson = RestcommGeolocationsTool.getInstance().createNotificationGeolocation( deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); Sid geolocationSid = new Sid(geolocationJson.get("sid").getAsString()); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(NotificationGT)); assertTrue(geolocationJson.get("response_status") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals("521")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString().equals("320")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString().equals("598")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString().equals("1")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString().equals("598001")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString().equals("0")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString().equals("35.349781")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString().equals("87.754320")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString().equals("Avenue2501")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude").getAsString() .equals(eventGeofenceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude").getAsString() .equals(eventGeofenceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type") == null); assertTrue(geolocationJson.get("last_geolocation_response") == null); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Test asserts via GET to a Geolocation list JsonArray notificationGeolocationsListJson = RestcommGeolocationsTool.getInstance() .getGeolocations(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid); geolocationJson = notificationGeolocationsListJson.get(0).getAsJsonObject(); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("source") == null); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(NotificationGT)); assertTrue(geolocationJson.get("response_status") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals("521")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString().equals("320")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString().equals("598")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString().equals("1")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString().equals("598001")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString().equals("0")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString().equals("35.349781")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString().equals("87.754320")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString().equals("Avenue2501")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude").getAsString() .equals(eventGeofenceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude").getAsString() .equals(eventGeofenceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type") == null); assertTrue(geolocationJson.get("last_geolocation_response") == null); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Remove created Geolocation via HTTP DELETE RestcommGeolocationsTool.getInstance().deleteNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); } @Test @Category(FeatureAltTests.class) public void testCreateNotApiCompliantNotificationGeolocation() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Geolocation attributes for this test method String deviceIdentifier, eventGeofenceLatitude, eventGeofenceLongitude; // Test create Notification type of Geolocation via POST with one missing mandatory parameter // Parameter values Assignment, GeofenceEvent missing MultivaluedMap<String, String> geolocationNewParams = new MultivaluedMapImpl(); geolocationNewParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationNewParams.add("EventGeofenceLatitude", eventGeofenceLatitude = "-43.426280"); geolocationNewParams.add("EventGeofenceLongitude", eventGeofenceLongitude = "170.566560"); geolocationNewParams.add("GeofenceRange", "200"); geolocationNewParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); Sid rejectedGeolocationSid = null; // HTTP POST Geolocation creation with given parameters values try { JsonObject missingParamGeolocationJson = RestcommGeolocationsTool.getInstance().createNotificationGeolocation( deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationNewParams); rejectedGeolocationSid = new Sid(missingParamGeolocationJson.get("sid").getAsString()); JsonObject rejectedGeolocationJson = RestcommGeolocationsTool.getInstance().getNotificationGeolocation( deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, rejectedGeolocationSid.toString()); assertTrue(rejectedGeolocationJson == null); } catch (Exception exception) { // Checking Test asserts via HTTP GET (no record found as POST returned a response status of 400 Bad Request) assertTrue(rejectedGeolocationSid == null); logger.info("Exception during HTTP POST: " + exception.getMessage()); } } @Test public void testUpdateNotificationGeolocation() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Notification Geolocation attributes String deviceIdentifier, responseStatus, cellId, locationAreaCode, mobileCountryCode, mobileNetworkCode, networkEntityAddress, ageOfLocationInfo, deviceLatitude, deviceLongitude, accuracy, internetAddress, physicalAddress, formattedAddress, locationTimestamp, eventGeofenceLatitude, eventGeofenceLongitude, radius, geolocationPositioningType, lastGeolocationResponse; // Create Notification type of Geolocation via POST // Parameter values Assignment MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParams.add("EventGeofenceLatitude", "-33.426280"); geolocationParams.add("EventGeofenceLongitude", "-70.566560"); geolocationParams.add("GeofenceRange", "300"); geolocationParams.add("GeofenceEvent", "in"); geolocationParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); // HTTP POST Geolocation creation with given parameters values and those returned via GMLC stub JsonObject geolocationJson = RestcommGeolocationsTool.getInstance().createNotificationGeolocation( deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); Sid geolocationSid = new Sid(geolocationJson.get("sid").getAsString()); // Define new values to the application attributes (POST test) MultivaluedMap<String, String> geolocationParamsUpdate = new MultivaluedMapImpl(); geolocationParamsUpdate.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParamsUpdate.add("EventGeofenceLatitude", eventGeofenceLatitude = "34\u00b038'19.39''N"); geolocationParamsUpdate.add("EventGeofenceLongitude", eventGeofenceLongitude = "55\u00b028'59.33''E"); geolocationParamsUpdate.add("GeofenceRange", "200"); geolocationParamsUpdate.add("GeofenceEvent", "in-out"); geolocationParamsUpdate.add("DesiredAccuracy", "High"); geolocationParamsUpdate.add("StatusCallback", "http://192.1.1.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); geolocationParamsUpdate.add("ResponseStatus", responseStatus = "successfull"); geolocationParamsUpdate.add("CellId", cellId = "12345"); geolocationParamsUpdate.add("LocationAreaCode", locationAreaCode = "321"); geolocationParamsUpdate.add("MobileCountryCode", mobileCountryCode = "749"); geolocationParamsUpdate.add("MobileNetworkCode", mobileNetworkCode = "01"); geolocationParamsUpdate.add("NetworkEntityAddress", networkEntityAddress = "5980042343201"); geolocationParamsUpdate.add("LocationAge", ageOfLocationInfo = "0"); geolocationParamsUpdate.add("DeviceLatitude", deviceLatitude = "34.908134"); geolocationParamsUpdate.add("DeviceLongitude", deviceLongitude = "-55.087134"); geolocationParamsUpdate.add("Accuracy", accuracy = "75"); geolocationParamsUpdate.add("InternetAddress", internetAddress = "2001:0:9d38:6ab8:30a5:1c9d:58c6:5898"); geolocationParamsUpdate.add("PhysicalAddress", physicalAddress = "D8-97-BA-19-02-D8"); geolocationParamsUpdate.add("FormattedAddress", formattedAddress = "Avenida Brasil 2681, 11500, Montevideo, Uruguay"); geolocationParamsUpdate.add("LocationTimestamp", locationTimestamp = "2016-04-17T20:28:40.690-03:00"); geolocationParamsUpdate.add("Radius", radius = "200"); geolocationParamsUpdate.add("GeolocationPositioningType", geolocationPositioningType = "Network"); geolocationParamsUpdate.add("LastGeolocationResponse", lastGeolocationResponse = "false"); geolocationParamsUpdate.add("Cause", "Not API Compliant"); // Update Geolocation via POST RestcommGeolocationsTool.getInstance().updateNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString(), geolocationParamsUpdate, false); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); DateTime dateTime = dtf.parseDateTime(locationTimestamp); SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); locationTimestamp = df.format(dateTime.toDate()); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(NotificationGT)); assertTrue(geolocationJson.get("response_status").getAsString().equals(responseStatus)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals(cellId)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString() .equals(locationAreaCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString() .equals(mobileCountryCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString() .equals(mobileNetworkCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString() .equals(networkEntityAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString() .equals(ageOfLocationInfo)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString() .equals(deviceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString() .equals(deviceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy").getAsString().equals(accuracy)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address").getAsString() .equals(internetAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address").getAsString() .equals(physicalAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString() .equals(formattedAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp").getAsString() .equals(locationTimestamp)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude").getAsString() .equals(eventGeofenceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude").getAsString() .equals(eventGeofenceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius").getAsString().equals(radius)); assertTrue(geolocationJson.get("geolocation_positioning_type").getAsString().equals(geolocationPositioningType)); assertTrue(geolocationJson.get("last_geolocation_response").getAsString().equals(lastGeolocationResponse)); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Define new values for the Geolocation attributes (PUT test) geolocationParamsUpdate = new MultivaluedMapImpl(); geolocationParamsUpdate.add("EventGeofenceLatitude", eventGeofenceLatitude = "N172 42 62.80"); geolocationParamsUpdate.add("EventGeofenceLongitude", eventGeofenceLongitude = "W170 56 65.60"); geolocationParamsUpdate.add("GeofenceRange", "50"); geolocationParamsUpdate.add("GeofenceEvent", "in"); geolocationParamsUpdate.add("DesiredAccuracy", "Average"); geolocationParamsUpdate.add("StatusCallback", "http://192.1.2.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); geolocationParamsUpdate.add("ResponseStatus", responseStatus = "partially-successfull"); geolocationParamsUpdate.add("CellId", cellId = "55777"); geolocationParamsUpdate.add("LocationAreaCode", locationAreaCode = "707"); geolocationParamsUpdate.add("MobileCountryCode", mobileCountryCode = "748"); geolocationParamsUpdate.add("MobileNetworkCode", mobileNetworkCode = "03"); geolocationParamsUpdate.add("NetworkEntityAddress", networkEntityAddress = "598003245701"); geolocationParamsUpdate.add("LocationAge", ageOfLocationInfo = "1"); geolocationParamsUpdate.add("DeviceLatitude", deviceLatitude = "172.908134"); geolocationParamsUpdate.add("DeviceLongitude", deviceLongitude = "170.908134"); geolocationParamsUpdate.add("Accuracy", accuracy = "25"); geolocationParamsUpdate.add("InternetAddress", internetAddress = "180.7.2.141"); geolocationParamsUpdate.add("PhysicalAddress", physicalAddress = "A8-77-CA-29-32-D1"); geolocationParamsUpdate.add("FormattedAddress", formattedAddress = "Avenida Italia 2681, 11100, Montevideo, Uruguay"); geolocationParamsUpdate.add("LocationTimestamp", locationTimestamp = "2016-04-17T20:28:42.771-03:00"); geolocationParamsUpdate.add("Radius", radius = "100"); geolocationParamsUpdate.add("GeolocationPositioningType", geolocationPositioningType = "GPS"); geolocationParamsUpdate.add("LastGeolocationResponse", lastGeolocationResponse = "true"); geolocationParamsUpdate.add("Cause", "API Not Compliant"); // Update Geolocation via PUT RestcommGeolocationsTool.getInstance().updateNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString(), geolocationParamsUpdate, true); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); dateTime = dtf.parseDateTime(locationTimestamp); locationTimestamp = df.format(dateTime.toDate()); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(NotificationGT)); assertTrue(geolocationJson.get("response_status").getAsString().equals(responseStatus)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals(cellId)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString() .equals(locationAreaCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString() .equals(mobileCountryCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString() .equals(mobileNetworkCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString() .equals(networkEntityAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString() .equals(ageOfLocationInfo)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString() .equals(deviceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString() .equals(deviceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy").getAsString().equals(accuracy)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address").getAsString() .equals(internetAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address").getAsString() .equals(physicalAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString() .equals(formattedAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp").getAsString() .equals(locationTimestamp)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude").getAsString() .equals(eventGeofenceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude").getAsString() .equals(eventGeofenceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius").getAsString().equals(radius)); assertTrue(geolocationJson.get("geolocation_positioning_type").getAsString().equals(geolocationPositioningType)); assertTrue(geolocationJson.get("last_geolocation_response").getAsString().equals(lastGeolocationResponse)); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Remove created & updated Geolocation via HTTP DELETE RestcommGeolocationsTool.getInstance().deleteNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); } @Test @Category(FeatureAltTests.class) public void testNotApiCompliantUpdateNotificationGeolocation() throws ParseException, IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); // Define Notification Geolocation attributes String deviceIdentifier, responseStatus, cellId, locationAreaCode, mobileCountryCode, mobileNetworkCode, networkEntityAddress, ageOfLocationInfo, deviceLatitude, deviceLongitude, accuracy, internetAddress, physicalAddress, formattedAddress, locationTimestamp = "2016-04-17T20:28:40.690-03:00", eventGeofenceLatitude, eventGeofenceLongitude, radius, geolocationPositioningType, lastGeolocationResponse; // Create Notification type of Geolocation via POST // Parameter values Assignment MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParams.add("EventGeofenceLatitude", "-33.426280"); geolocationParams.add("EventGeofenceLongitude", "-70.566560"); geolocationParams.add("GeofenceRange", "300"); geolocationParams.add("GeofenceEvent", "in"); geolocationParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); // HTTP POST Geolocation creation with given parameters values and those returned via GMLC stub JsonObject geolocationJson = RestcommGeolocationsTool.getInstance().createNotificationGeolocation( deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); Sid geolocationSid = new Sid(geolocationJson.get("sid").getAsString()); DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); DateTime dateTime = dtf.parseDateTime(locationTimestamp); SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US); locationTimestamp = df.format(dateTime.toDate()); // Define malformed values for the Geolocation attributes (PUT test to fail) MultivaluedMap<String, String> geolocationParamsUpdate = new MultivaluedMapImpl(); geolocationParamsUpdate.add("DeviceLatitude", deviceLatitude = "72.908134"); geolocationParamsUpdate.add("DeviceLongitude", deviceLongitude = "South 170.908134"); // WGS84 not compliant // Update failed Geolocation via PUT RestcommGeolocationsTool.getInstance().updateNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString(), geolocationParamsUpdate, true); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("source") == null); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(NotificationGT)); assertTrue(geolocationJson.get("response_status").getAsString().equalsIgnoreCase("failed")); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude") == null); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius") == null); assertTrue(geolocationJson.get("geolocation_positioning_type") == null); assertTrue(geolocationJson.get("last_geolocation_response") == null); assertTrue(geolocationJson.get("cause") != null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Define new values for the Geolocation attributes (PUT test) geolocationParamsUpdate = new MultivaluedMapImpl(); geolocationParamsUpdate.add("EventGeofenceLatitude", eventGeofenceLatitude = "172 42 62.80N"); geolocationParamsUpdate.add("EventGeofenceLongitude", eventGeofenceLongitude = "170 56 65.60E"); geolocationParamsUpdate.add("GeofenceRange", "50"); geolocationParamsUpdate.add("GeofenceEvent", "out"); geolocationParamsUpdate.add("DesiredAccuracy", "High"); geolocationParamsUpdate.add("StatusCallback", "http://192.1.2.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); geolocationParamsUpdate.add("ResponseStatus", responseStatus = "successfull"); geolocationParamsUpdate.add("CellId", cellId = "34580"); geolocationParamsUpdate.add("LocationAreaCode", locationAreaCode = "709"); geolocationParamsUpdate.add("MobileCountryCode", mobileCountryCode = "747"); geolocationParamsUpdate.add("MobileNetworkCode", mobileNetworkCode = "05"); geolocationParamsUpdate.add("NetworkEntityAddress", networkEntityAddress = "598003245703"); geolocationParamsUpdate.add("LocationAge", ageOfLocationInfo = "0"); geolocationParamsUpdate.add("DeviceLatitude", deviceLatitude = "172\u00b038'19.39''N"); geolocationParamsUpdate.add("DeviceLongitude", deviceLongitude = "169\u00b028'44.07''E"); geolocationParamsUpdate.add("Accuracy", accuracy = "25"); geolocationParamsUpdate.add("InternetAddress", internetAddress = "180.7.2.141"); geolocationParamsUpdate.add("PhysicalAddress", physicalAddress = "A8-77-CA-29-32-D1"); geolocationParamsUpdate.add("FormattedAddress", formattedAddress = "Avenida Brasil 2681, 11300, Montevideo, Uruguay"); geolocationParamsUpdate.add("LocationTimestamp", locationTimestamp = "2016-04-17T20:32:29.488-07:00"); geolocationParamsUpdate.add("Radius", radius = "5"); geolocationParamsUpdate.add("GeolocationPositioningType", geolocationPositioningType = "GPS"); geolocationParamsUpdate.add("LastGeolocationResponse", lastGeolocationResponse = "true"); geolocationParamsUpdate.add("Cause", "API Not Compliant"); // Update Geolocation via PUT // previous failed location is composed again with new proper geolocation data values RestcommGeolocationsTool.getInstance().updateNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString(), geolocationParamsUpdate, true); // Test asserts via GET to a single Geolocation geolocationJson = RestcommGeolocationsTool.getInstance().getNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); dateTime = dtf.parseDateTime(locationTimestamp); locationTimestamp = df.format(dateTime.toDate()); assertTrue(df.parse(geolocationJson.get("date_created").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_updated").getAsString()) != null); assertTrue(df.parse(geolocationJson.get("date_executed").getAsString()) != null); assertTrue(geolocationJson.get("account_sid").getAsString().equals(adminAccountSid)); assertTrue(geolocationJson.get("device_identifier").getAsString().equals(deviceIdentifier)); assertTrue(geolocationJson.get("geolocation_type").getAsString().equals(NotificationGT)); assertTrue(geolocationJson.get("response_status").getAsString().equals(responseStatus)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("cell_id").getAsString().equals(cellId)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_area_code").getAsString() .equals(locationAreaCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_country_code").getAsString() .equals(mobileCountryCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("mobile_network_code").getAsString() .equals(mobileNetworkCode)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("network_entity_address").getAsString() .equals(networkEntityAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_age").getAsString() .equals(ageOfLocationInfo)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_latitude").getAsString() .equals(deviceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("device_longitude").getAsString() .equals(deviceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("accuracy").getAsString().equals(accuracy)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("internet_address").getAsString() .equals(internetAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("physical_address").getAsString() .equals(physicalAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("formatted_address").getAsString() .equals(formattedAddress)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("location_timestamp").getAsString() .equals(locationTimestamp)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_latitude").getAsString() .equals(eventGeofenceLatitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("event_geofence_longitude").getAsString() .equals(eventGeofenceLongitude)); assertTrue(geolocationJson.get("geolocation_data").getAsJsonObject().get("radius").getAsString().equals(radius)); assertTrue(geolocationJson.get("geolocation_positioning_type").getAsString().equals(geolocationPositioningType)); assertTrue(geolocationJson.get("last_geolocation_response").getAsString().equals(lastGeolocationResponse)); assertTrue(geolocationJson.get("cause") == null); assertTrue(geolocationJson.get("api_version").getAsString().equals("2012-04-24")); // Remove created & updated Geolocation via HTTP DELETE RestcommGeolocationsTool.getInstance().deleteNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); } @Test public void testDeleteNotificationGeolocation() throws IllegalArgumentException, ClientProtocolException, IOException { String msisdn = "5989738292"; //This is for POST requests stubFor(post(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); //This is for GET requests - REMOVE if not needed stubFor(get(urlPathEqualTo("/restcomm/gmlc/rest")) .withQueryParam("msisdn", equalTo(msisdn)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(gmlcResponse))); String deviceIdentifier; // Create Notification type of Geolocation via POST // Parameter values Assignment MultivaluedMap<String, String> geolocationParams = new MultivaluedMapImpl(); geolocationParams.add("DeviceIdentifier", deviceIdentifier = msisdn); geolocationParams.add("EventGeofenceLatitude", "-33.426280"); geolocationParams.add("EventGeofenceLongitude", "-70.566560"); geolocationParams.add("GeofenceRange", "300"); geolocationParams.add("GeofenceEvent", "in"); geolocationParams.add("DesiredAccuracy", "High"); geolocationParams.add("StatusCallback", "http://192.1.0.19:8080/ACae6e420f425248d6a26948c17a9e2acf"); geolocationParams.add("ResponseStatus", "successfull"); geolocationParams.add("Accuracy", "5"); geolocationParams.add("InternetAddress", "194.87.1.127"); geolocationParams.add("PhysicalAddress", "D8-97-BA-19-02-D8"); geolocationParams.add("LocationTimestamp", "2016-04-17T20:28:40.690-03:00"); geolocationParams.add("Radius", "200"); geolocationParams.add("GeolocationPositioningType", "GPS"); geolocationParams.add("LastGeolocationResponse", "true"); geolocationParams.add("Cause", "Not API Compliant"); // HTTP POST Geolocation creation with given parameters values and those returned via GMLC stub JsonObject geolocationJson = RestcommGeolocationsTool.getInstance().createNotificationGeolocation( deploymentUrl.toString(), adminAccountSid, adminUsername, adminAuthToken, geolocationParams); Sid geolocationSid = new Sid(geolocationJson.get("sid").getAsString()); // Remove created Geolocation via HTTP DELETE RestcommGeolocationsTool.getInstance().deleteNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); // Remove checking Test asserts via HTTP GET geolocationJson = RestcommGeolocationsTool.getInstance().getNotificationGeolocation(deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, geolocationSid.toString()); assertTrue(geolocationJson == null); } @Deployment(name = "GeolocationsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
91,000
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SupervisorEndpointAccessControlTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/SupervisorEndpointAccessControlTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2016, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Assert; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.google.gson.JsonObject; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; /** * SupervisorEndpointAccessControlTest Supervisor metrices should be accessible to only Super Admin role. * * @author Maria Farooq <dam dam nak nak> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SupervisorEndpointAccessControlTest extends EndpointTest { protected final static Logger logger = Logger.getLogger(SupervisorEndpointAccessControlTest.class); private String superAdminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String superAdminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; static String adminAccountSid = "AC22222222222222222222222222222222"; static String userUsername = "[email protected]"; static String adminAccountAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; static String developerSid = "AC11111111111111111111111111111111"; static String developerUsername = "[email protected]"; static String developerAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String superAdmin2AccountSid = "AC00000000000000000000000000000000"; private String superAdmin2AuthToken = "77f8c12cc7b8f8423e5c38b035249166"; /** * Super Admin should be able to access supervisor metrics */ @Test public void testSuperAdminPermissionTest() { JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken); Assert.assertNotNull(metrics); } /** * Super Admins (but not ancestors) SHOULD be able to access supervisor metrics */ @Test @Category(FeatureAltTests.class) public void testSuperAdmin2PermissionTest() { JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(), superAdmin2AccountSid, superAdmin2AuthToken); Assert.assertNotNull(metrics); } /** * Admin should NOT be able to access supervisor metrics */ @Test @Category(FeatureExpTests.class) public void testAdminPermissionTest() { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminAccountSid, adminAccountAuthToken)); String url = MonitoringServiceTool.getInstance().getAccountsUrl(deploymentUrl.toString(), adminAccountSid); WebResource webResource = jerseyClient.resource(url+"/metrics"); ClientResponse response = webResource.get(ClientResponse.class); Assert.assertEquals(403, response.getStatus()); } /** * Developer should NOT be able to access supervisor metrics */ @Test @Category(FeatureExpTests.class) public void testDeveloperPermissionTest() { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(developerSid, developerAuthToken)); String url = MonitoringServiceTool.getInstance().getAccountsUrl(deploymentUrl.toString(), developerSid); WebResource webResource = jerseyClient.resource(url+"/metrics"); ClientResponse response = webResource.get(ClientResponse.class); Assert.assertEquals(403, response.getStatus()); } @Deployment(name = "RoleSensitiveTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_roles_permissions.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_supervisor_permission_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
6,031
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NotificationEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/NotificationEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.HashMap; import java.util.Map; import com.sun.jersey.api.client.UniformInterfaceException; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.FeatureAltTests; /** * @author <a href="mailto:[email protected]">vunguyen</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class NotificationEndpointTest extends EndpointTest{ private static Logger logger = Logger.getLogger(NotificationEndpointTest.class); private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test public void getNotificationList() { JsonObject firstPage = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageNotificationsArray = firstPage.get("notifications").getAsJsonArray(); int firstPageNotificationsArraySize = firstPageNotificationsArray.size(); assertEquals(34, firstPageNotificationsArraySize); assertEquals(0, firstPage.get("start").getAsInt()); assertEquals(34, firstPage.get("end").getAsInt()); assertEquals(34, totalSize); } @Test @Category(FeatureAltTests.class) public void getNotificationListUsingPageSize() { JsonObject firstPage = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, null, 10, null, true); JsonArray firstPageNotificationsArray = firstPage.get("notifications").getAsJsonArray(); assertEquals(10, firstPageNotificationsArray.size()); assertEquals(0, firstPage.get("start").getAsInt()); assertEquals(9, firstPage.get("end").getAsInt()); JsonObject secondPage = (JsonObject) NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 2, 10, null, true); JsonArray secondPageNotificationsArray = secondPage.get("notifications").getAsJsonArray(); assertEquals(10, secondPageNotificationsArray.size()); assertEquals(20, secondPage.get("start").getAsInt()); assertEquals(29, secondPage.get("end").getAsInt()); JsonObject lastPage = (JsonObject) NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, firstPage.get("num_pages").getAsInt(), 10, null, true); JsonArray lastPageNotificationsArray = lastPage.get("notifications").getAsJsonArray(); assertEquals(4, lastPageNotificationsArray.size()); assertEquals(30, lastPage.get("start").getAsInt()); assertEquals(34, lastPage.get("end").getAsInt()); } @Test @Category(FeatureAltTests.class) public void getNotificationListFilteredByStartTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("StartTime", "2013-09-30 16:28:33.403000000"); JsonObject filteredNotificationsByStartTime = NotificationEndpointTool.getInstance().getNotificationListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(14, filteredNotificationsByStartTime.get("notifications").getAsJsonArray().size()); assertEquals(0, filteredNotificationsByStartTime.get("start").getAsInt()); assertEquals(14, filteredNotificationsByStartTime.get("end").getAsInt()); } @Test @Category(FeatureAltTests.class) public void getNotificationListFilteredByEndTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("EndTime", "2013-09-30 16:28:33.403000000"); JsonObject filteredNotificationsByEndTime = NotificationEndpointTool.getInstance().getNotificationListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(30, filteredNotificationsByEndTime.get("notifications").getAsJsonArray().size()); assertEquals(0, filteredNotificationsByEndTime.get("start").getAsInt()); assertEquals(30, filteredNotificationsByEndTime.get("end").getAsInt()); } @Test @Category(FeatureAltTests.class) public void getNotificationListFilteredByErrorCode() { Map<String, String> filters = new HashMap<String, String>(); filters.put("ErrorCode", "1"); JsonObject filteredNotificationsByErrorCode = NotificationEndpointTool.getInstance().getNotificationListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(9, filteredNotificationsByErrorCode.get("notifications").getAsJsonArray().size()); assertEquals(0, filteredNotificationsByErrorCode.get("start").getAsInt()); assertEquals(9, filteredNotificationsByErrorCode.get("end").getAsInt()); } @Test @Category(FeatureAltTests.class) public void getNotificationListFilteredByRequestUrl() { Map<String, String> filters = new HashMap<String, String>(); filters.put("RequestUrl", "http://instance1.restcomm.com:8080/restcomm/recordings/RE50675909d9c94acda36f0e119b6cb432.wav"); JsonObject filteredNotificationsByRequestUrl = NotificationEndpointTool.getInstance().getNotificationListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(20, filteredNotificationsByRequestUrl.get("notifications").getAsJsonArray().size()); assertEquals(0, filteredNotificationsByRequestUrl.get("start").getAsInt()); assertEquals(20, filteredNotificationsByRequestUrl.get("end").getAsInt()); } @Test @Category(FeatureAltTests.class) public void getNotificationListFilteredByMessageText() { Map<String, String> filters = new HashMap<String, String>(); filters.put("MessageText", "Restcomm"); JsonObject filteredNotificationsByMessageText = NotificationEndpointTool.getInstance().getNotificationListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertEquals(17, filteredNotificationsByMessageText.get("notifications").getAsJsonArray().size()); assertEquals(0, filteredNotificationsByMessageText.get("start").getAsInt()); assertEquals(17, filteredNotificationsByMessageText.get("end").getAsInt()); } @Test public void getNotificationListUsingSorting() { int pageSize = 30; // Provide both sort field and direction // Provide ascending sorting and verify that the first row is indeed the earliest one JsonObject response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:asc", true); // Remember there is a discrepancy between the sort parameters and the result attribute in the .json response. For example DateCreated:asc, means // to sort based of DateCreated field, but in the response the field is called 'date_created', not DateCreated. This only happens only for .json; in // .xml the naming seems to be respected. // Notice that we are removing the timezone part from the end of the string, because CI potentially uses different timezone that messes the test up assertEquals("Fri, 30 Aug 2013 16:28:33", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); // Provide only sort field; all fields default to ascending response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated", true); assertEquals("Fri, 30 Aug 2013 16:28:33", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:desc", true); assertEquals("Wed, 30 Oct 2013 16:28:33", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); try { // provide only direction, should cause an exception NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, ":asc", true); } catch (UniformInterfaceException e) { assertEquals(BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); } try { // provide sort field and direction, but direction is invalid (neither of asc or desc) NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:invalid", true); } catch (UniformInterfaceException e) { assertEquals(BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); } // Log response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Log:asc", true); assertEquals("0", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("log").getAsString()); response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Log:desc", true); assertEquals("1", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("log").getAsString()); // Error Code response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "ErrorCode:asc", true); assertEquals("0", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("error_code").getAsString()); response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "ErrorCode:desc", true); assertEquals("100", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("error_code").getAsString()); // CallSid response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "CallSid:asc", true); assertEquals("CA5EB00000000000000000000000000002", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("call_sid").getAsString()); response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "CallSid:desc", true); assertEquals("CA5EB00000000000000000000000000009", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("call_sid").getAsString()); // Message Text response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "MessageText:asc", true); assertEquals("Another fictitious message for testing", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("message_text").getAsString()); response = NotificationEndpointTool.getInstance().getNotificationList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "MessageText:desc", true); assertEquals("Workspace migration skipped in 2016-12-28 21:12:25.758", ((JsonObject)response.get("notifications").getAsJsonArray().get(0)).get("message_text").getAsString()); } @Deployment(name = "NotificationEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
14,707
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountsEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/AccountsEndpointTest.java
package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.net.URL; import javax.sip.address.SipURI; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; import org.apache.shiro.crypto.hash.Md5Hash; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.junit.FixMethodOrder; import org.junit.experimental.categories.Category; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.UnstableTests; /** * @author <a href="mailto:[email protected]">gvagenas</a> * @author <a href="mailto:[email protected]">Jean Deruelle</a> * @author <a href="mailto:[email protected]">Thinh Ly</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AccountsEndpointTest extends EndpointTest { private final static Logger logger = Logger.getLogger(AccountsEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminUsername = "[email protected]"; private String adminFriendlyName = "Default Administrator Account"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String adminPassword = "RestComm"; private String childUsername = "[email protected]"; private String childSid = "AC574d775522c96f9aacacc5ca60c8c74f"; private String childAuthToken ="77f8c12cc7b8f8423e5c38b035249166"; private String createdUsernanme = "[email protected]"; private String createdUsernanme2 = "[email protected]"; private String createdUsernanme3 = "[email protected]"; private String createdAccountSid = "AC5ee3b351401804c2d064a33f762146fb"; private String createdPassword = "RestComm12"; private String createdAuthToken = "28f96b0fea1f9e33646f42026abdf305"; private String updatedUsername = "[email protected]"; private String updatedAccountSid = "AC6b53c6ffa9fa7c4682dbcf4dec73012f"; private String userEmailAddress = "[email protected]"; private String userPassword = "1234"; private String unprivilegedSid = "AC00000000000000000000000000000000"; private String unprivilegedUsername = "[email protected]"; private String unprivilegedAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String guestSid = "AC11111111111111111111111111111111"; private String guestUsername = "[email protected]"; private String guestAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String removedSid = "AC22222222222222222222222222222222"; private String removedUsername = "[email protected]"; private String removedAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String updatedRoleUsername = "[email protected]"; private String updatedRoleAccountSid = "AC33333333333333333333333333333333"; private String updateRoleAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String nonSubAccountSid = "AC44444444444444444444444444444444"; private String commonAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String organizationSid1 = "ORafbe225ad37541eba518a74248f0ac4c"; private String organizationSid2 = "ORafbe225ad37541eba518a74248f0ac4d"; private String organizationSid3 = "ORafbe225ad37541eba518a74248f0ac4e"; private String organization1DomainName = "127.0.0.1"; private String organization2DomainName = "org1.restcomm.com"; private String organization3DomainName = "org2.restcomm.com"; static SipStackTool tool1; SipStack thinhSipStack; SipPhone thinhPhone; //String thinhContact = "sip:[email protected]:5090"; @BeforeClass public static void beforeClass() { tool1 = new SipStackTool("AccountsEndpointTest"); } public void startSipStack(String thinhContact) throws Exception { thinhSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); thinhPhone = thinhSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, thinhContact); } @After public void stopSipStack() throws InterruptedException { if (thinhPhone != null) { thinhPhone.dispose(); } if (thinhSipStack != null && thinhSipStack.getSipProvider().getListeningPoints().length>0) { thinhSipStack.dispose(); } Thread.sleep(1000); } @Test public void testGetAccount() { // Get Account using admin email address and user email address JsonObject adminAccount = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, adminUsername); assertTrue(adminAccount.get("sid").getAsString().equals(adminAccountSid)); } @Test @Category(FeatureExpTests.class) public void testGetAccountAccess(){ // check non-existent user receives a 401 ClientResponse response = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), "[email protected]", "badpassword", adminAccountSid); assertEquals("Non-existing user should get a 401", 401, response.getStatus()); // check InsufficientPerimssion errors- 403. Try to get administrator account with unprivileged accoutn creds response = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(), unprivilegedUsername, unprivilegedAuthToken, adminAccountSid); assertEquals("Unpriveleged access to account did not return 403", 403, response.getStatus()); } @Test @Category(FeatureExpTests.class) public void testGetAccountByFriendlyName() { // Try to get Account using admin friendly name and user email address int code = 0; try { JsonObject adminAccount = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminFriendlyName, adminAuthToken, adminUsername); } catch (UniformInterfaceException e) { code = e.getResponse().getStatus(); } // Logins using friendly name are not allowed anymore assertTrue(code == 401); } @Test public void testCreateAccount() { JsonObject createAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, createdUsernanme, createdPassword); JsonObject getAccountResponse = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, createdUsernanme); assertTrue(getAccountResponse.get("sid").getAsString().equals(createdAccountSid)); assertEquals(createdAuthToken, getAccountResponse.get("auth_token").getAsString()); logger.info("createAccountResponse: "+createAccountResponse); assertTrue(createAccountResponse.get("sid").getAsString().equals(createdAccountSid)); assertEquals(createdAuthToken, createAccountResponse.get("auth_token").getAsString()); } @Test @Category(FeatureExpTests.class) public void testCreateAccountWithInvalidChars() { String username1 = "[email protected]"; String username2 = "my@[email protected]"; String username3 = "[email protected]"; String password = "RestCom1233@"; JsonObject createAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, username1, password); assertNull(createAccountResponse); createAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, username2, password); assertNull(createAccountResponse); createAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, username3, password); assertNull(createAccountResponse); } @Test @Category(UnstableTests.class) public void testCreateAccountWithJapaneseChars() { String friendlyName = "NTTアドバンステクノロジ"; String userName = "[email protected]"; JsonObject createAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, userName, createdPassword, friendlyName); String createdsid = createAccountResponse.get("sid").getAsString(); JsonObject getAccountResponse = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, createdsid); assertEquals(getAccountResponse.get("auth_token").getAsString(), createAccountResponse.get("auth_token").getAsString()); assertEquals(getAccountResponse.get("friendly_name").getAsString(), createAccountResponse.get("friendly_name").getAsString()); } @Test public void testUpdateAccount() { //update friendlyname and role, no password, no status update!! JsonObject updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedAccountSid, "updated2", null, null, "Developer", null ); JsonObject getAccountResponse = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedUsername); assertEquals("FriendlyName field is not updated", "updated2", updateAccountResponse.get("friendly_name").getAsString()); assertEquals("Status field should remain uninitialized", "uninitialized", updateAccountResponse.get("status").getAsString()); assertEquals("Role field is not updated", "Developer", updateAccountResponse.get("role").getAsString()); assertEquals("FriendlyName field is not updated", "updated2", getAccountResponse.get("friendly_name").getAsString()); assertEquals("Status field should remain uninitialized", "uninitialized", getAccountResponse.get("status").getAsString()); assertEquals("Role field is not updated", "Developer", updateAccountResponse.get("role").getAsString()); // role update test revert it back to Administrator //update friendlyname, role, and authtoken, no status update!! updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedAccountSid, "updated3", "Restcomm2", "Restcomm2", "Administrator", null ); getAccountResponse = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedUsername); assertEquals("FriendlyName field is not updated", "updated3", updateAccountResponse.get("friendly_name").getAsString()); assertEquals("AuthToken field is not updated", new Md5Hash("Restcomm2").toString(), updateAccountResponse.get("auth_token").getAsString()); assertEquals("Changing password must activate account", "active", updateAccountResponse.get("status").getAsString()); assertEquals("Role field is not updated", "Administrator", updateAccountResponse.get("role").getAsString()); assertEquals("FriendlyName field is not updated", "updated3", getAccountResponse.get("friendly_name").getAsString()); assertEquals("AuthToken field is not updated", new Md5Hash("Restcomm2").toString(), getAccountResponse.get("auth_token").getAsString()); assertEquals("Changing password must activate account", "active",getAccountResponse.get("status").getAsString()); assertEquals("Role field is not updated", "Administrator", getAccountResponse.get("role").getAsString()); // role update test revert it back to Administrator } @Test public void testUpdateAuthTokenIgnored() { // try to update directly the AuthToken JsonObject updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, childSid, null, null, "RestComm12", null, null ); // make sure the AuthToken has not changed assertEquals("77f8c12cc7b8f8423e5c38b035249166", updateAccountResponse.get("auth_token").getAsString()); } @Test @Category(FeatureAltTests.class) public void testUpdateAccountStatusAllCapital() { JsonObject updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedAccountSid, null, null, null, null, "ACTIVE" ); JsonObject getAccountResponse = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedUsername); assertEquals("Status field is not updated", "active", updateAccountResponse.get("status").getAsString()); assertEquals("Status field is not updated", "active", getAccountResponse.get("status").getAsString()); // role update test revert it back to Administrator updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedAccountSid, "updated3", "Restcomm2", null, "Administrator", null ); getAccountResponse = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedUsername); assertEquals("FriendlyName field is not updated", "updated3", updateAccountResponse.get("friendly_name").getAsString()); assertEquals("AuthToken field is not updated", new Md5Hash("Restcomm2").toString(), updateAccountResponse.get("auth_token").getAsString()); assertEquals("Role field is not updated", "Administrator", updateAccountResponse.get("role").getAsString()); assertEquals("FriendlyName field is not updated", "updated3", getAccountResponse.get("friendly_name").getAsString()); assertEquals("AuthToken field is not updated", new Md5Hash("Restcomm2").toString(), getAccountResponse.get("auth_token").getAsString()); assertEquals("Role field is not updated", "Administrator", getAccountResponse.get("role").getAsString()); } @Test public void testUpdateAccountByEmail() { JsonObject updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedUsername, "updated2", "Restcomm2", null, "Developer", null ); JsonObject getAccountResponse = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedUsername); assertEquals("FriendlyName field is not updated", "updated2", updateAccountResponse.get("friendly_name").getAsString()); assertEquals("AuthToken field is not updated", new Md5Hash("Restcomm2").toString(), updateAccountResponse.get("auth_token").getAsString()); assertEquals("Role field is not updated", "Developer", updateAccountResponse.get("role").getAsString()); assertEquals("FriendlyName field is not updated", "updated2", getAccountResponse.get("friendly_name").getAsString()); assertEquals("AuthToken field is not updated", new Md5Hash("Restcomm2").toString(), getAccountResponse.get("auth_token").getAsString()); assertEquals("Role field is not updated", "Developer", updateAccountResponse.get("role").getAsString()); // role update test revert it back to Administrator updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedAccountSid, "updated3", "Restcomm2", null, "Administrator", null ); getAccountResponse = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedUsername); assertEquals("FriendlyName field is not updated", "updated3", updateAccountResponse.get("friendly_name").getAsString()); assertEquals("AuthToken field is not updated", new Md5Hash("Restcomm2").toString(), updateAccountResponse.get("auth_token").getAsString()); assertEquals("Role field is not updated", "Administrator", updateAccountResponse.get("role").getAsString()); assertEquals("FriendlyName field is not updated", "updated3", getAccountResponse.get("friendly_name").getAsString()); assertEquals("AuthToken field is not updated", new Md5Hash("Restcomm2").toString(), getAccountResponse.get("auth_token").getAsString()); assertEquals("Role field is not updated", "Administrator", getAccountResponse.get("role").getAsString()); } // special account-update policy when updating roles @Test @Category(FeatureExpTests.class) public void testUpdateAccountRoleAccessControl() { // non-admins should not be able to change their role ClientResponse response = RestcommAccountsTool.getInstance().updateAccountResponse(deploymentUrl.toString(), updatedRoleUsername, updateRoleAuthToken, updatedRoleAccountSid, null, null, null, "Administrator", null ); assertEquals("Should return a 403 when non-admin tries to update role", 403, response.getStatus() ); // admin, should be able to change their sub-account role response = RestcommAccountsTool.getInstance().updateAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, updatedRoleAccountSid, null, null, null, "Administrator", null ); assertEquals("Should return a 200 when admin tries to update role of sub-account", 200, response.getStatus() ); // admin, should not be able to change role of other account that is not their sub-account response = RestcommAccountsTool.getInstance().updateAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, nonSubAccountSid, null, null, null, "Administrator", null ); assertEquals("Should get a 403 when admin tries to modify role of non-sub-accounts", 403, response.getStatus() ); } @Test @Category(FeatureExpTests.class) public void testCreateAccountAccess(){ // 'unprivilaged should not be able to create accounts and receive a 403 ClientResponse response = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), unprivilegedUsername, unprivilegedAuthToken, "[email protected]", "not-created-password"); assertEquals("403 not returned", 403, response.getStatus()); } @Test @Category(FeatureExpTests.class) public void testCreateAdministratorAccountFails() { JsonObject createAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, "[email protected]", "RestComm12"); assertNull(createAccountResponse); } @Test @Category(FeatureExpTests.class) public void testCreateAccountTwiceFails() { ClientResponse createResponse1 = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, "[email protected]", "RestComm12"); assertEquals("Account [email protected] could not be created even once", 200, createResponse1.getStatus()); ClientResponse createResponse2 = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, "[email protected]", "RestComm12"); assertEquals("Did not retrieve a conflict HTTP status (409) while creating accounts with same email address", 409, createResponse2.getStatus()); } /** * When creating a new account and the client with the same name is already there * TODO [...] * * @throws Exception */ @Test @Category(UnstableTests.class) public void testCreateAccountCheckClientExisted() throws Exception { try { String thinhContact = "sip:[email protected]:5090"; startSipStack(thinhContact); String subAccountPassword = "mynewpassword12"; String subAccountEmail = "[email protected]"; JsonObject subAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, subAccountEmail, subAccountPassword); JsonObject clientOfAccount = CreateClientsTool.getInstance().getClientOfAccount(deploymentUrl.toString(), subAccountResponse, adminUsername, adminPassword); assertNotNull(clientOfAccount); CreateClientsTool.getInstance().updateClientVoiceUrl(deploymentUrl.toString(), subAccountResponse, clientOfAccount.get("sid").getAsString(), deploymentUrl.toString() + "/demos/welcome.xml", adminUsername, adminPassword); JsonObject clientOfAccountUpdated = CreateClientsTool.getInstance().getClientOfAccount(deploymentUrl.toString(), subAccountResponse, adminUsername, adminPassword); System.out.println(clientOfAccountUpdated); // Use the new client to register with Restcomm SipURI reqUri = thinhSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(thinhPhone.register(reqUri, "lyhungthinh", subAccountPassword, thinhContact, 1800, 1800)); assertTrue(thinhPhone.unregister(thinhContact, 0)); //RestcommAccountsTool.getInstance().removeAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, // subAccountResponse.get("sid").getAsString()); } finally { stopSipStack(); } } @Test @Category(FeatureExpTests.class) public void testCreateAccountFourthLevelFails() { ClientResponse response = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), "[email protected]", commonAuthToken, "[email protected]", "RestComm12"); assertEquals(400, response.getStatus()); //Assert.assertTrue(response.getEntity(String.class).contains("")) } @Test @Category(UnstableTests.class) public void testUpdateAccountCheckClient() throws Exception { try { String thinhContact = "sip:[email protected]:5090"; startSipStack(thinhContact); String subAccountPassword = "mynewpassword12"; String subAccountEmail = "[email protected]"; String subAccountNewPassword = "latestpassword12"; String subAccountNewAuthToken = "81eb94645c485fc39eedc5d46522e5ba"; JsonObject subAccountResponse; SipURI reqUri = thinhSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); subAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, subAccountEmail, subAccountPassword); assertNotNull(subAccountResponse); JsonObject clientOfAccount = CreateClientsTool.getInstance().getClientOfAccount(deploymentUrl.toString(), subAccountResponse, adminUsername, adminPassword); assertNotNull(clientOfAccount); // Use the new client to register with Restcomm assertTrue(thinhPhone.register(reqUri, "lyhungthinh2", subAccountPassword, thinhContact, 1800, 1800)); assertTrue(thinhPhone.unregister(thinhContact, 0)); subAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken,subAccountResponse.get("sid").getAsString(), null, subAccountNewPassword, null, null, null); assertTrue(subAccountResponse.get("auth_token").getAsString().equals(subAccountNewAuthToken)); assertTrue(thinhPhone.register(reqUri, "lyhungthinh2", subAccountNewPassword, thinhContact, 1800, 1800)); assertTrue(thinhPhone.unregister(thinhContact, 0)); clientOfAccount = CreateClientsTool.getInstance().getClientOfAccount(deploymentUrl.toString(), subAccountResponse, adminUsername, adminPassword); assertTrue(clientOfAccount.get("password").getAsString().equals(subAccountNewPassword)); //RestcommAccountsTool.getInstance().removeAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, // subAccountResponse.get("sid").getAsString()); } finally { stopSipStack(); } } @Test @Category(UnstableTests.class) public void testCloseAccountCheckClient() throws Exception { try { String thinhContact = "sip:[email protected]:5090"; startSipStack(thinhContact); String subAccountPassword = "mynewpassword12"; String subAccountEmail = "[email protected]"; JsonObject subAccountResponse; SipURI reqUri = thinhSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); subAccountResponse = RestcommAccountsTool.getInstance().createAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, subAccountEmail, subAccountPassword); assertNotNull(subAccountResponse); JsonObject clientOfAccount = CreateClientsTool.getInstance().getClientOfAccount(deploymentUrl.toString(), subAccountResponse, adminUsername, adminPassword); assertNotNull(clientOfAccount); assertTrue(thinhPhone.register(reqUri, "lyhungthinh3", subAccountPassword, thinhContact, 1800, 1800)); assertTrue(thinhPhone.unregister(thinhContact, 0)); // close the account Client jersey = getClient(adminUsername, adminPassword); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/"+subAccountEmail) ); MultivaluedMap<String,String> params = new MultivaluedMapImpl(); params.add("Status","closed"); ClientResponse response = resource.put(ClientResponse.class,params); assertEquals(200, response.getStatus()); //RestcommAccountsTool.getInstance().removeAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, // subAccountResponse.get("sid").getAsString()); // and make sure the client is gone and can't register JsonObject clientOfAccount2 = CreateClientsTool.getInstance().getClientOfAccount(deploymentUrl.toString(), subAccountResponse, adminUsername, adminPassword); assertTrue(clientOfAccount2 == null); assertFalse(thinhPhone.register(reqUri, "lyhungthinh3", subAccountPassword, thinhContact, 1800, 1800)); } finally { stopSipStack(); } } @Test public void testCloseAccountNested() { String topLevelSid = "AC12300000000000000000000000000000"; String removed1Sid = "AC12300000000000000000000000000001"; String removed11Sid = "AC12300000000000000000000000000011"; Client jersey = getClient("[email protected]", commonAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/"+removed1Sid) ); MultivaluedMap<String,String> params = new MultivaluedMapImpl(); params.add("Status","closed"); ClientResponse response = resource.put(ClientResponse.class,params); // the closed account should be available assertEquals(200, response.getStatus()); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response.getEntity(String.class)).getAsJsonObject(); // make sure the account status is set to closed assertEquals("closed", jsonObject.get("status").getAsString()); // assert removed accounts children are closed too resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts.json/"+removed11Sid) ); response = resource.get(ClientResponse.class); assertEquals(200, response.getStatus()); parser = new JsonParser(); jsonObject = parser.parse(response.getEntity(String.class)).getAsJsonObject(); assertEquals("closed", jsonObject.get("status").getAsString()); // assert the applications of the account are removed resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/"+removed1Sid+"/Applications/AP00000000000000000000000000000001.json" ) ); assertEquals(404, resource.get(ClientResponse.class).getStatus()); // assert IncomingPhoneNumbers of the account are removed resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/"+removed1Sid+"/IncomingPhoneNumbers/PN00000000000000000000000000000001.json" ) ); assertEquals(404, resource.get(ClientResponse.class).getStatus()); // assert notification are removed resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/"+removed1Sid+"/Notifications/NO00000000000000000000000000000001.json" ) ); assertEquals(404, resource.get(ClientResponse.class).getStatus()); // assert recordings are removed resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/"+removed1Sid+"/Recordings/RE00000000000000000000000000000001.json" ) ); assertEquals(404, resource.get(ClientResponse.class).getStatus()); // assert transcriptions are removed resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/"+removed1Sid+"/Transcriptions/TR00000000000000000000000000000001.json" ) ); assertEquals(404, resource.get(ClientResponse.class).getStatus()); // assert outgoing caller ids are removed resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/"+removed1Sid+"/OutgoingCallerIds/PN00000000000000000000000000000001.json" ) ); assertEquals(404, resource.get(ClientResponse.class).getStatus()); // assert clients are removed resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/"+removed1Sid+"/Clients/CL00000000000000000000000000000001.json" ) ); assertEquals(404, resource.get(ClientResponse.class).getStatus()); // we won't test Announcements removal . There is no retrieval method yet. } @Test public void testGetAccounts() throws InterruptedException { // Get Account using admin email address and user email address JsonObject account1 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, childUsername); // Get Account using admin account sid and user sid JsonObject account2 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminAccountSid, adminAuthToken, account1.get("sid").getAsString()); assertTrue(account1.toString().equals(account2.toString())); } @Test @Category(FeatureExpTests.class) public void testGetAccountsAccess() { ClientResponse response = RestcommAccountsTool.getInstance().getAccountsResponse(deploymentUrl.toString(), guestUsername, guestAuthToken); assertEquals("Guest account should get get a 403 when retrieving accounts", 403, response.getStatus()); } @Ignore // ignored since account removal is disables as of #1270 @Test public void testRemoveAccountAccess(){ ClientResponse response = RestcommAccountsTool.getInstance().removeAccountResponse(deploymentUrl.toString(), unprivilegedUsername, unprivilegedAuthToken, removedSid + ".json" ); assertEquals("Unprivileged account should receive a 403 while removing an account", 403, response.getStatus()); response = RestcommAccountsTool.getInstance().removeAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, removedSid + ".json"); assertEquals("Administrator should receive a 200 OK when removing an account", 200, response.getStatus()); } /** * Test access without administrator type of access. Instead a common role and permissions is used. */ @Test public void testAccountAcccessUsingRoles() { ClientResponse response = RestcommAccountsTool.getInstance().getAccountResponse(deploymentUrl.toString(),unprivilegedUsername, unprivilegedAuthToken, unprivilegedSid); assertEquals(200,response.getStatus()); } @Test public void testPasswordStrengthForAccountCreate() { ClientResponse response = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, "[email protected]", "1234"); assertEquals("Weak password account creation should fail with 400", 400, response.getStatus()); Assert.assertTrue("Response error message should contain 'weak' term", response.getEntity(String.class).toLowerCase().contains("weak")); response = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, "[email protected]", "1234asdf!@#"); assertEquals(200, response.getStatus()); } @Test public void testPasswordStrengthForAccountUpdate() { // updating an account with weak password should fail ClientResponse response = RestcommAccountsTool.getInstance().updateAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, "[email protected]", null, "1234", null, null, null ); assertEquals(400, response.getStatus()); Assert.assertTrue("Response should contain 'weak' term", response.getEntity(String.class).toLowerCase().contains("weak")); // updating an account with strong password should succeed response = RestcommAccountsTool.getInstance().updateAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, "[email protected]", null, "RestComm12", null, null, null ); assertEquals(200, response.getStatus()); } @Test @Category(FeatureExpTests.class) public void createAccountInSpecificOrganizationPermissionTest() { // child should not be able to create account in specified org that it does not belong to ClientResponse clientResponse = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), childUsername, childAuthToken, createdUsernanme, createdPassword, null, organizationSid2); assertEquals(403, clientResponse.getStatus()); } @Test public void createAccountInSpecificOrganizationRoleTest() { // child should be able to create account in specified org that it belong to ClientResponse clientResponse = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), childUsername, childAuthToken, createdUsernanme2, createdPassword, null, organizationSid1); assertEquals(200, clientResponse.getStatus()); //super admin should be able to create account in specified org clientResponse = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, createdUsernanme3, createdPassword, null, organizationSid2); assertEquals(200, clientResponse.getStatus()); } @Test @Category(FeatureExpTests.class) public void createAccountInSpecificOrganizationInvalidRequestTest() { //super admin tries to create account with invalid organization Sid ClientResponse clientResponse = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, createdUsernanme3, createdPassword, null, "blabla"); assertEquals(400, clientResponse.getStatus()); //super admin tries to create account with organization Sid that does not exists clientResponse = RestcommAccountsTool.getInstance().createAccountResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, createdUsernanme3, createdPassword, null, "ORafbe225ad37541eba518a74248f01234"); assertEquals(400, clientResponse.getStatus()); } @Test @Category({UnstableTests.class, FeatureAltTests.class}) //Using aaa prefix to enforce order, so this can be executed under the assumptions //of initial db script, rather than depending on execution order of diff //test cases public void aaatestGetAccountsOfASpecificOrganization() { //getAccounts without any parameters ClientResponse response = RestcommAccountsTool.getInstance().getAccountsResponse(deploymentUrl.toString(), adminUsername, adminAuthToken); if(logger.isDebugEnabled()) logger.debug("getAccounts without filter Response: "+response); assertEquals(200, response.getStatus()); //getAccounts with null Filter JsonArray accountsArray = RestcommAccountsTool.getInstance().getAccountsWithFilterResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, null, null); if(logger.isDebugEnabled()) logger.debug("getAccounts With null Filter Response: "+accountsArray); assertEquals(8, accountsArray.size()); //getAccounts with organizationSid Filter accountsArray = RestcommAccountsTool.getInstance().getAccountsWithFilterResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, organizationSid1, null); if(logger.isDebugEnabled()) logger.debug("getAccounts With organizationSid Filter Response: "+accountsArray); assertEquals(24, accountsArray.size()); //getAccounts with organizationSid Filter accountsArray = RestcommAccountsTool.getInstance().getAccountsWithFilterResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, organizationSid2, null); if(logger.isDebugEnabled()) logger.debug("getAccounts With organizationSid Filter Response: "+accountsArray); //should be 1 account that belongs to this org assertEquals(1, accountsArray.size()); //getAccounts with organizationSid Filter accountsArray = RestcommAccountsTool.getInstance().getAccountsWithFilterResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, organizationSid3, null); if(logger.isDebugEnabled()) logger.debug("getAccounts With organizationSid Filter Response: "+accountsArray); //should be 0, as no account belongs to this org assertEquals(0, accountsArray.size()); //getAccounts with domainName Filter accountsArray = RestcommAccountsTool.getInstance().getAccountsWithFilterResponse(deploymentUrl.toString(), adminUsername, adminAuthToken, null, organization2DomainName); if(logger.isDebugEnabled()) logger.debug("getAccounts With domainName Filter Response: "+accountsArray); //should be 1 account assertEquals(1, accountsArray.size()); } @Test public void testUpdateAccountStatusSuspended() { final String sidMaster = "ACbdf00000000000000000000000000000"; final String sidChild1 = "ACbdf00000000000000000000000000001"; final String sidChild2 = "ACbdf00000000000000000000000000002"; final String sidGrandchild1 = "ACbdf00000000000000000000000000011"; final String sidGrandchild2 = "ACbdf00000000000000000000000000012"; //final String sidGreatGrandchild1 = "ACbdf00000000000000000000000000111"; //final String sidGreatGrandchild2 = "ACbdf00000000000000000000000000112"; //change master account status to suspended JsonObject updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidMaster, null, null, null, null, "suspended" ); //collect data from account tree to check status replication JsonObject getAccountResponse1 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidChild1); JsonObject getAccountResponse2 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidChild2); JsonObject getAccountResponse3 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidGrandchild1); JsonObject getAccountResponse4 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidGrandchild2); //JsonObject getAccountResponse5 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), // adminUsername, adminAuthToken, sidGreatGrandchild1); //JsonObject getAccountResponse6 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), // adminUsername, adminAuthToken, sidGreatGrandchild2); //check master account status assertEquals("Master account status is not updated", "suspended", updateAccountResponse.get("status").getAsString()); //check account tree status assertEquals("Child 1 account status is not updated", "suspended", getAccountResponse1.get("status").getAsString()); assertEquals("Child 2 account status is not updated", "suspended", getAccountResponse2.get("status").getAsString()); assertEquals("Grandchild 1 account status is not updated", "suspended", getAccountResponse3.get("status").getAsString()); assertEquals("Grandchild 2 account status is not updated", "suspended", getAccountResponse4.get("status").getAsString()); //assertEquals("Great-grandchild 1 account status is not updated", "suspended", getAccountResponse5.get("status").getAsString()); //assertEquals("Great-grandchild 2 account status is not updated", "suspended", getAccountResponse6.get("status").getAsString()); //revert master account status to active updateAccountResponse = RestcommAccountsTool.getInstance().updateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidMaster, null, null, null, null, "active" ); //collect data from account tree to check status replication getAccountResponse1 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidChild1); getAccountResponse2 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidChild2); getAccountResponse3 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidGrandchild1); getAccountResponse4 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, sidGrandchild2); //getAccountResponse5 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), // adminUsername, adminAuthToken, sidGreatGrandchild1); //getAccountResponse6 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), // adminUsername, adminAuthToken, sidGreatGrandchild2); //check master account status assertEquals("Master account status is not updated", "active", updateAccountResponse.get("status").getAsString()); //check account tree status assertEquals("Child 1 account status is not updated", "active", getAccountResponse1.get("status").getAsString()); assertEquals("Child 2 account status is not updated", "active", getAccountResponse2.get("status").getAsString()); assertEquals("Grandchild 1 account status is not updated", "active", getAccountResponse3.get("status").getAsString()); assertEquals("Grandchild 2 account status is not updated", "active", getAccountResponse4.get("status").getAsString()); //assertEquals("Great-grandchild 1 account status is not updated", "active", getAccountResponse5.get("status").getAsString()); //assertEquals("Great-grandchild 2 account status is not updated", "active", getAccountResponse6.get("status").getAsString()); } @Deployment(name = "ClientsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_accounts_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
47,152
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VersionTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/VersionTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2013, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; /** * Created by gvagenas on 1/19/16. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class VersionTest { private static Logger logger = Logger.getLogger(VersionTest.class); private static final String version = Version.getVersion(); private static final String revision = Version.getRevision(); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test public void testVersionJson() { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminAccountSid, adminAuthToken)); String url = deploymentUrl + "2012-04-24/Accounts/" + adminAccountSid + "/Version.json"; WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(response).getAsJsonObject(); assertTrue(version.equals(json.get("Version").getAsString())); assertTrue(revision.equals(json.get("Revision").getAsString())); } @Test public void testVersionXml() { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminAccountSid, adminAuthToken)); String url = deploymentUrl + "2012-04-24/Accounts/" + adminAccountSid + "/Version"; WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_XML).get(String.class); assertNotNull(response); assertTrue(response.contains(version)); assertTrue(response.contains(revision)); } @Deployment(name = "VersionTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script", "data/hsql/restcomm.script"); return archive; } }
4,615
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MultitenancyAllowAccessApiTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/MultitenancyAllowAccessApiTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.util.HashMap; import java.util.Map; import junit.framework.Assert; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.UnstableTests; import wiremock.org.apache.http.client.ClientProtocolException; /** * The aim of this scenario is to ensure that an account can manage its own information and the information from its sub * accounts. Accounts and Applications endpoints are tested separately due its particularities. * * @author [email protected] */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class MultitenancyAllowAccessApiTest { private final static Logger logger = Logger.getLogger(MultitenancyAllowAccessApiTest.class); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private final static String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private final static String primaryUsername = "[email protected]"; private final static String primaryAccountSid = "AC1ec5d14c34a421c7697e1ce5d4eac782"; private final static String subaccountaAccountSid = "AC5fa870789e95b7867a0fc0b85c5805e9"; private final static String subaccountbAccountSid = "AC5fa870789e95b7867a0fc0b85c5805e8"; private final static String primaryApplicationSid = "APcf92fc10ab384116bfe3df19ef741c7a"; private final static String accountsPassword = "RestComm"; private final static int httpOk = 200; private final static int httpDeleteOk = 204; private final static String apiPath = "2012-04-24/Accounts/"; private final static String jsonExtension = ".json"; private enum Endpoint { INCOMING_PHONE_NUMBERS("IncomingPhoneNumbers", true, false, true, true, new HashMap<String,String>(){{ put("PhoneNumber","1111"); put("AreaCode","100"); }}, "PNff22dc8d1cdf4d449d666ac09f0bb110", "PN9f9cf955aeb94ebb9d2e09cead5683a4"), CALLS("Calls", true, false, false, false, null, "CA9aa1b61e9b864477a820d5c1c9d9bb7d", "CAc6a057e16aa74cb0923c538725ffcf01"), SMS_MESSAGES("SMS/Messages", true, false, false, false, null, "SMa272937700b3461bb5d68a3569c61bf1", "SMa272937700b3461bb5d68a3569c61bf2"), CLIENTS("Clients", true, true, true, true, new HashMap<String,String>(){{ put("Login","test"); put("Password","Restcomm12"); }}, "CLe95ba029114147c9a9aa42becd0518c0", "CL9bfcb54ead2b44e6bae03f337967a249"), OUTGOING_CALLER_IDS("OutgoingCallerIds", true, true, false, true, new HashMap<String,String>(){{ put("PhoneNumber","1111"); }}, "PNfa413fdbf3944932b37bef4bd661c7f7", "PN5a33fa8232d84578af023b1e81e30f67"), RECORDINGS("Recordings", true, false, false, false, null, "REacaffdf107da4dc3926e37bddfff44ed", "REacaffdf107da4dc3926e37bddfff44ee"), TRANSCRIPTIONS("Transcriptions", true, false, false, true, null, "TRacaffdf107da4dc3926e37bddfff44ee", "TRacaffdf107da4dc3926e37bddfff44ed"), NOTIFICATIONS("Notifications", true, false, false, false, null, "NO8927433ce9514b70ac0a76cd36601b9e", "NO8927433ce9514b70ac0a76cd36601b9d"); String name; boolean get; boolean postList; boolean postElement; boolean delete; HashMap<String, String> postParams; String elementSameAccount; String elementSubaccount; Endpoint(String name, boolean get, boolean postList, boolean postElement, boolean delete, HashMap<String,String> postParams, String elementSameAccount, String elementSubaccount){ this.name = name; this.get = get; this.postList = postList; this.postElement = postElement; this.delete = delete; this.postParams = postParams; this.elementSameAccount = elementSameAccount; this.elementSubaccount = elementSubaccount; } } @Test public void getListSameAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + primaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.get) { String url = baseUrl + endpoint.name + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().get(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpOk); logger.info("Tested endpoint " + endpoint.name + " (getListSameAccount). Status code = " + statusCode); } } } @Test @Category(FeatureAltTests.class) public void getListSubaccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + subaccountaAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.get) { String url = baseUrl + endpoint.name + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().get(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpOk); logger.info("Tested endpoint " + endpoint.name + " (getListSubaccount). Status code = " + statusCode); } } } @Test @Category(UnstableTests.class) public void postListSameAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + primaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.postList) { String url = baseUrl + endpoint.name + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().post(url, primaryUsername, accountsPassword, endpoint.postParams); Assert.assertEquals(httpOk, statusCode); logger.info("Tested endpoint " + endpoint.name + " (postListSameAccount). Status code = " + statusCode); } } } @Test @Category(FeatureAltTests.class) public void postListSubaccount() throws ClientProtocolException, IOException { Endpoint endpoints[] = modifyPostParameters("2"); String baseUrl = deploymentUrl.toString() + apiPath + subaccountaAccountSid + "/"; for (Endpoint endpoint : endpoints) { if (endpoint.postList) { String url = baseUrl + endpoint.name + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().post(url, primaryUsername, accountsPassword, endpoint.postParams); Assert.assertEquals(httpOk, statusCode); logger.info("Tested endpoint " + endpoint.name + " (postListSubaccount). Status code = " + statusCode); } } } @Test @Category(UnstableTests.class) /** * using aaa prefix to ensure order and prevent sideeffects */ public void aaagetElementSameAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + primaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.get) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSameAccount + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().get(url, primaryUsername, accountsPassword); Assert.assertEquals(httpOk, statusCode); logger.info("Tested endpoint " + endpoint.name + " (getElementSameAccount). Status code = " + statusCode); } } } @Test @Category({UnstableTests.class, FeatureAltTests.class}) public void aaagetElementSubaccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + subaccountaAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.get) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSubaccount + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().get(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpOk); logger.info("Tested endpoint " + endpoint.name + " (getElementSubaccount). Status code = " + statusCode); } } } @Test @Category(UnstableTests.class) /** * using aaa prefix to ensure order and prevent sideeffects */ public void aaapostElementSameAccount() throws ClientProtocolException, IOException { Endpoint endpoints[] = modifyPostParameters("3"); String baseUrl = deploymentUrl.toString() + apiPath + primaryAccountSid + "/"; for (Endpoint endpoint : endpoints) { if (endpoint.postElement) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSameAccount; int statusCode = RestcommMultitenancyTool.getInstance().post(url, primaryUsername, accountsPassword, endpoint.postParams); Assert.assertEquals(httpOk, statusCode); logger.info("Tested endpoint " + endpoint.name + " (postElementSameAccount). Status code = " + statusCode); } } } @Test @Category(FeatureAltTests.class) /** * using aaa prefix to ensure order and prevent sideeffects */ public void aaapostElementSubaccount() throws ClientProtocolException, IOException { Endpoint endpoints[] = modifyPostParameters("4"); String baseUrl = deploymentUrl.toString() + apiPath + subaccountaAccountSid + "/"; for (Endpoint endpoint : endpoints) { if (endpoint.postElement) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSubaccount + jsonExtension; int statusCode = RestcommMultitenancyTool.getInstance().post(url, primaryUsername, accountsPassword, endpoint.postParams); Assert.assertEquals(httpOk, statusCode); logger.info("Tested endpoint " + endpoint.name + " (postElementSubaccount). Status code = " + statusCode); } } } @Test public void deleteElementSameAccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + primaryAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.delete) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSameAccount; int statusCode = RestcommMultitenancyTool.getInstance().delete(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpDeleteOk || statusCode == httpOk); logger.info("Tested endpoint " + endpoint.name + " (deleteElementSameAccount). Status code = " + statusCode); } } } @Test @Category(FeatureAltTests.class) public void deleteElementSubaccount() throws ClientProtocolException, IOException { String baseUrl = deploymentUrl.toString() + apiPath + subaccountaAccountSid + "/"; for (Endpoint endpoint : Endpoint.values()) { if (endpoint.delete) { String url = baseUrl + endpoint.name + "/" + endpoint.elementSubaccount; int statusCode = RestcommMultitenancyTool.getInstance().delete(url, primaryUsername, accountsPassword); assertTrue(statusCode == httpDeleteOk || statusCode == httpOk); logger.info("Tested endpoint " + endpoint.name + " (deleteElementSubaccount). Status code = " + statusCode); } } } @Test /** * using aaa prefix to ensure order and prevent sideeffects */ public void aaaaccountsApi() throws ClientProtocolException, IOException { // Same account String baseUrl = deploymentUrl.toString() + apiPath.substring(0, apiPath.length()-1); int statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + jsonExtension, primaryUsername, accountsPassword); Assert.assertEquals(httpOk, statusCode); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + jsonExtension, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("EmailAddress","[email protected]"); put("Password","RestComm12");}}); Assert.assertEquals(httpOk, statusCode); // Sub account baseUrl = deploymentUrl.toString() + apiPath.substring(0, apiPath.length()-1); statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + jsonExtension + "/" + subaccountbAccountSid, primaryUsername, accountsPassword); Assert.assertEquals(httpOk, statusCode); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + "/" + subaccountbAccountSid, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("EmailAddress","[email protected]"); put("Password","RestComm12");}}); Assert.assertEquals(httpOk, statusCode); Map<String,String> updateParams = new HashMap<String,String>(); updateParams.put("Status", "closed"); statusCode = RestcommMultitenancyTool.getInstance().update(baseUrl + jsonExtension + "/" + subaccountbAccountSid, primaryUsername, accountsPassword,updateParams); assertTrue(statusCode == httpDeleteOk || statusCode == httpOk); } @Test public void applicationsApi() throws ClientProtocolException, IOException { // access to account's own applications String baseUrl = deploymentUrl.toString() + apiPath + primaryAccountSid + "/Applications"; int statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + jsonExtension, primaryUsername, accountsPassword); assertTrue(statusCode == httpOk); statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + "/" + primaryApplicationSid + jsonExtension, primaryUsername, accountsPassword); assertTrue(statusCode == httpOk); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + jsonExtension, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("FriendlyName","TEST"); }}); assertTrue(statusCode == httpOk); statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + "/" + primaryApplicationSid + jsonExtension, primaryUsername, accountsPassword, new HashMap<String,String>(){{ put("FriendlyName","TEST123"); }}); assertTrue(statusCode == httpOk); // access to sub-account applications // list statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + jsonExtension, adminAccountSid, accountsPassword); Assert.assertEquals(httpOk, statusCode); // get single statusCode = RestcommMultitenancyTool.getInstance().get(baseUrl + "/" + primaryApplicationSid + jsonExtension, adminAccountSid, accountsPassword); assertTrue(statusCode == httpOk); // create statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + jsonExtension, adminAccountSid, accountsPassword, new HashMap<String,String>(){{ put("FriendlyName","TEST"); }}); assertTrue(statusCode == httpOk); // update statusCode = RestcommMultitenancyTool.getInstance().post(baseUrl + "/" + primaryApplicationSid + jsonExtension, adminAccountSid, accountsPassword, new HashMap<String,String>(){{ put("FriendlyName","TEST123"); }}); assertTrue(statusCode == httpOk); } private Endpoint[] modifyPostParameters(String suffix) { Endpoint endpoints[] = Endpoint.values(); for (Endpoint endpoint : endpoints) { if (endpoint.postElement || endpoint.postList) { for (String k : endpoint.postParams.keySet()) { endpoint.postParams.put(k, endpoint.postParams.get(k) + suffix); } } } return endpoints; } @Deployment(name = "MultitenancyAllowAccessApiTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_multitenancyTest", "data/hsql/restcomm.script"); return archive; } }
18,658
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UsageRecordsTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/UsageRecordsTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.*; import com.sun.jersey.api.client.UniformInterfaceException; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import java.net.URL; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.BrokenTests; import org.restcomm.connect.commons.annotations.UnstableTests; /** * @author <a href="mailto:[email protected]">abdulazizali77</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class UsageRecordsTest { private static Logger logger = Logger.getLogger(UsageRecordsTest.class); private static final String version = Version.getVersion(); private static final String revision = Version.getRevision(); @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test(expected = UniformInterfaceException.class) public void getUsageRecordsList() { // NB: currently unimplemented JsonElement firstPage = RestcommUsageRecordsTool.getInstance().getUsageRecords(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", "", true); logger.info(firstPage); } @Test(expected = UniformInterfaceException.class) public void getUsageRecordsListCategoryCalls() { JsonElement firstPage = RestcommUsageRecordsTool.getInstance().getUsageRecordsDaily(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "calls", true); logger.info(firstPage); } @Test(expected = UniformInterfaceException.class) public void getUsageRecordsListCategorySms() { JsonElement firstPage = RestcommUsageRecordsTool.getInstance().getUsageRecordsDaily(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "sms", true); logger.info(firstPage); } @Test @Category(BrokenTests.class) public void getUsageRecordsDaily() { JsonElement response = RestcommUsageRecordsTool.getInstance().getUsageRecordsDaily(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", true); assertNotNull(response); // 12 days assertTrue(response.getAsJsonArray().size() == 12); // TODO: write factory method to arbitrarily compare expectation and output JsonObject firstRecord = response.getAsJsonArray().get(0).getAsJsonObject(); String category = firstRecord.get("category").getAsString(); String description = firstRecord.get("description").getAsString(); String startDate = firstRecord.get("start_date").getAsString(); String endDate = firstRecord.get("end_date").getAsString(); String count = firstRecord.get("count").getAsString(); String usage = firstRecord.get("usage").getAsString(); String price = firstRecord.get("price").getAsString(); String count_unit = firstRecord.get("count_unit").getAsString(); String usage_unit = firstRecord.get("usage_unit").getAsString(); String price_unit = firstRecord.get("price_unit").getAsString(); String uri = firstRecord.get("uri").getAsString(); assertTrue(category.equals("calls")); assertTrue(description.equals("Total calls")); assertTrue(startDate.equals("2016-01-01")); assertTrue(endDate.equals("2016-01-01")); assertTrue(count.equals("3"));// 3 calls per day assertTrue(usage.equals("1"));// 20 seconds each assertTrue(price.equals("15.0"));// TODO: check if price per usage or count? assertTrue(count_unit.equals("calls")); assertTrue(usage_unit.equals("minutes")); assertTrue(price_unit.equals("USD")); //TODO: potential problem with order of query params assertTrue(uri.equals("/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Usage/Records/Daily.json?Category=Calls&EndDate=2016-01-01&StartDate=2016-01-01")); //TODO: test other categories } @Test @Category(BrokenTests.class) public void getUsageRecordsMonthly() { JsonElement response = RestcommUsageRecordsTool.getInstance().getUsageRecordsMonthly(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", true); // 4 months assertTrue(response.getAsJsonArray().size() == 4); // TODO: write factory method to arbitrarily compare expectation and output JsonObject firstRecord = response.getAsJsonArray().get(0).getAsJsonObject(); String category = firstRecord.get("category").getAsString(); String description = firstRecord.get("description").getAsString(); String startDate = firstRecord.get("start_date").getAsString(); String endDate = firstRecord.get("end_date").getAsString(); String count = firstRecord.get("count").getAsString(); String usage = firstRecord.get("usage").getAsString(); String price = firstRecord.get("price").getAsString(); String count_unit = firstRecord.get("count_unit").getAsString(); String usage_unit = firstRecord.get("usage_unit").getAsString(); String price_unit = firstRecord.get("price_unit").getAsString(); String uri = firstRecord.get("uri").getAsString(); assertTrue(category.equals("calls")); assertTrue(description.equals("Total Calls")); assertTrue(startDate.equals("2016-01-01")); assertTrue(endDate.equals("2016-01-31")); assertTrue(count.equals("9")); assertTrue(usage.equals("3"));// 3minutes assertTrue(price.equals("45.0")); assertTrue(count_unit.equals("calls")); assertTrue(usage_unit.equals("minutes")); assertTrue(price_unit.equals("USD")); assertTrue(uri.equals("/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Usage/Records/Monthly.json?Category=Calls&EndDate=2016-01-01&StartDate=2016-01-31")); //TODO: test other categories } @Test @Category(BrokenTests.class) public void getUsageRecordsYearly() { JsonElement response = RestcommUsageRecordsTool.getInstance().getUsageRecordsYearly(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", true); // 2 years assertTrue(response.getAsJsonArray().size() == 2); JsonObject firstRecord = response.getAsJsonArray().get(0).getAsJsonObject(); String category = firstRecord.get("category").getAsString(); String description = firstRecord.get("description").getAsString(); String startDate = firstRecord.get("start_date").getAsString(); String endDate = firstRecord.get("end_date").getAsString(); String count = firstRecord.get("count").getAsString(); String usage = firstRecord.get("usage").getAsString(); String price = firstRecord.get("price").getAsString(); String count_unit = firstRecord.get("count_unit").getAsString(); String usage_unit = firstRecord.get("usage_unit").getAsString(); String price_unit = firstRecord.get("price_unit").getAsString(); String uri = firstRecord.get("uri").getAsString(); assertTrue(category.equals("calls")); assertTrue(description.equals("Total Calls")); assertTrue(startDate.equals("2016-01-01")); assertTrue(endDate.equals("2016-12-31")); assertTrue(count.equals("18")); assertTrue(usage.equals("6"));// 6 minutes assertTrue(price.equals("90.0")); assertTrue(count_unit.equals("calls")); assertTrue(usage_unit.equals("minutes")); assertTrue(price_unit.equals("USD")); assertTrue(uri.equals("/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Usage/Records/Yearly.json?Category=Calls&EndDate=2016-01-01&StartDate=2016-12-31")); //TODO: test other categories } @Test @Category(BrokenTests.class) public void getUsageRecordsAlltime() { JsonElement response = RestcommUsageRecordsTool.getInstance().getUsageRecordsAllTime(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", true); assertTrue(response.getAsJsonArray().size() == 1); JsonObject firstRecord = response.getAsJsonArray().get(0).getAsJsonObject(); String category = firstRecord.get("category").getAsString(); String description = firstRecord.get("description").getAsString(); String startDate = firstRecord.get("start_date").getAsString(); String endDate = firstRecord.get("end_date").getAsString(); String count = firstRecord.get("count").getAsString(); String usage = firstRecord.get("usage").getAsString(); String price = firstRecord.get("price").getAsString(); String count_unit = firstRecord.get("count_unit").getAsString(); String usage_unit = firstRecord.get("usage_unit").getAsString(); String price_unit = firstRecord.get("price_unit").getAsString(); String uri = firstRecord.get("uri").getAsString(); assertTrue(category.equals("calls")); assertTrue(description.equals("Total Calls")); assertTrue(startDate.equals("2016-01-01")); assertTrue(endDate.equals("2017-12-31")); assertTrue(count.equals("36")); assertTrue(usage.equals("360")); assertTrue(price.equals("180.0")); assertTrue(count_unit.equals("calls")); assertTrue(usage_unit.equals("minutes")); assertTrue(price_unit.equals("USD")); //FIXME:start date should be start of epoch? assertTrue(uri.equals("/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Usage/Records/AllTime.json?Category=Calls&EndDate=2017-02-03&StartDate=2016-01-01")); //TODO: test other categories } @Test public void getUsageRecordsToday() { JsonElement firstPage = RestcommUsageRecordsTool.getInstance().getUsageRecordsToday(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", true); logger.info(firstPage); } @Test public void getUsageRecordsYesterday() { JsonElement firstPage = RestcommUsageRecordsTool.getInstance().getUsageRecordsYesterday(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", true); logger.info(firstPage); } @Test public void getUsageRecordsThisMonth() { JsonElement firstPage = RestcommUsageRecordsTool.getInstance().getUsageRecordsThisMonth(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", true); logger.info(firstPage); } @Test public void getUsageRecordsLastMonth() { JsonElement firstPage = RestcommUsageRecordsTool.getInstance().getUsageRecordsLastMonth(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "", true); logger.info(firstPage); } @Deployment(name = "UsageRecordsTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); // archive.delete("/WEB-INF/data/hsql/restcomm.properties"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data_UsageRecords.script", "data/hsql/restcomm.script"); // archive.addAsWebInfResource("restcomm.properties", "data/hsql/restcomm.properties"); return archive; } }
13,434
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmsMessagesEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/SmsMessagesEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import static javax.ws.rs.core.Response.Status.BAD_REQUEST; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import com.sun.jersey.api.client.UniformInterfaceException; import junit.framework.Assert; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.dao.MessageError; import org.restcomm.connect.dao.entities.SmsMessage; import org.restcomm.connect.testsuite.sms.SmsEndpointTool; import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * @author <a href="mailto:[email protected]">vunguyen</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SmsMessagesEndpointTest extends EndpointTest{ private static Logger logger = Logger.getLogger(SmsMessagesEndpointTest.class); private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test public void getSmsMessageList() { JsonObject firstPage = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageMessagesArray = firstPage.get("messages").getAsJsonArray(); int firstPageMessagesArraySize = firstPageMessagesArray.size(); assertTrue(firstPageMessagesArraySize == 34); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 34); assertTrue(totalSize == 34); } @Test @Category(FeatureAltTests.class) public void getSmsMessageListUsingPageSize() { JsonObject firstPage = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, null, 10, null, true); JsonArray firstPageMessagesArray = firstPage.get("messages").getAsJsonArray(); assertTrue(firstPageMessagesArray.size() == 10); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 9); JsonObject secondPage = (JsonObject) SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 2, 10, null, true); JsonArray secondPageMessagesArray = secondPage.get("messages").getAsJsonArray(); assertTrue(secondPageMessagesArray.size() == 10); assertTrue(secondPage.get("start").getAsInt() == 20); assertTrue(secondPage.get("end").getAsInt() == 29); JsonObject lastPage = (JsonObject) SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, firstPage.get("num_pages").getAsInt(), 10, null, true); JsonArray lastPageMessagesArray = lastPage.get("messages").getAsJsonArray(); assertTrue(lastPageMessagesArray.size() == 4); assertTrue(lastPage.get("start").getAsInt() == 30); assertTrue(lastPage.get("end").getAsInt() == 34); } @Test @Category(FeatureAltTests.class) public void getSmsMessageListFilteredBySender() { Map<String, String> filters = new HashMap<String, String>(); filters.put("From", "49376%"); JsonObject filteredMessagesBySender = SmsEndpointTool.getInstance().getSmsMessageListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredMessagesBySender.get("messages").getAsJsonArray().size() == 4); assertTrue(filteredMessagesBySender.get("start").getAsInt() == 0); assertTrue(filteredMessagesBySender.get("end").getAsInt() == 4); } @Test @Category(FeatureAltTests.class) public void getSmsMessageListFilteredByRecipent() { Map<String, String> filters = new HashMap<String, String>(); filters.put("To", "13557%"); JsonObject filteredMessagesByRecipent = SmsEndpointTool.getInstance().getSmsMessageListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredMessagesByRecipent.get("messages").getAsJsonArray().size() == 12); assertTrue(filteredMessagesByRecipent.get("start").getAsInt() == 0); assertTrue(filteredMessagesByRecipent.get("end").getAsInt() == 12); } @Test @Category(FeatureAltTests.class) public void getSmsMessageListFilteredByStartTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("StartTime", "2013-07-07 18:15:12.018000000"); JsonObject filteredMessagesByStartTime = SmsEndpointTool.getInstance().getSmsMessageListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredMessagesByStartTime.get("messages").getAsJsonArray().size() == 24); assertTrue(filteredMessagesByStartTime.get("start").getAsInt() == 0); assertTrue(filteredMessagesByStartTime.get("end").getAsInt() == 24); } @Test @Category(FeatureAltTests.class) public void getSmsMessageListFilteredByEndTime() { Map<String, String> filters = new HashMap<String, String>(); filters.put("EndTime", "2013-07-09 16:22:35.146000000"); JsonObject filteredMessagesByEndTime = SmsEndpointTool.getInstance().getSmsMessageListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredMessagesByEndTime.get("messages").getAsJsonArray().size() == 26); assertTrue(filteredMessagesByEndTime.get("start").getAsInt() == 0); assertTrue(filteredMessagesByEndTime.get("end").getAsInt() == 26); } @Test @Category(FeatureAltTests.class) public void getSmsMessageListFilteredByBody() { Map<String, String> filters = new HashMap<String, String>(); filters.put("Body", "Hello"); JsonObject filteredMessagesByBody = SmsEndpointTool.getInstance().getSmsMessageListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertTrue(filteredMessagesByBody.get("messages").getAsJsonArray().size() == 6); assertTrue(filteredMessagesByBody.get("start").getAsInt() == 0); assertTrue(filteredMessagesByBody.get("end").getAsInt() == 6); } @Test @Category(FeatureAltTests.class) public void getSmsMessageBySidVerifyError() { JsonObject smsMessageJson = SmsEndpointTool.getInstance().getSmsMessage(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "SMfe8a9e566f4544eab21c2ec94ae9e790"); assertNotNull(smsMessageJson); assertEquals(SmsMessage.Status.SENT.toString(), smsMessageJson.get("status").getAsString()); assertEquals(MessageError.UNKNOWN_ERROR.getErrorCode().intValue(), smsMessageJson.get("error_code").getAsInt()); assertEquals(MessageError.UNKNOWN_ERROR.getErrorMessage(), smsMessageJson.get("error_message").getAsString()); } @Test public void getSmsMessageListUsingSorting() { int pageSize = 30; // Provide both sort field and direction // Provide ascending sorting and verify that the first row is indeed the earliest one JsonObject response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:asc", true); // Remember there is a discrepancy between the sort parameters and the result attribute in the .json response. For example DateCreated:asc, means // to sort based of DateCreated field, but in the response the field is called 'date_created', not DateCreated. This only happens only for .json; in // .xml the naming seems to be respected. // Notice that we are removing the timezone part from the end of the string, because CI potentially uses different timezone that messes the test up assertEquals("Fri, 5 Jul 2013 21:32:40", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); // Provide only sort field; all fields default to ascending response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated", true); assertEquals("Fri, 5 Jul 2013 21:32:40", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:desc", true); assertEquals("Thu, 11 Jul 2013 15:39:32", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("date_created").getAsString().replaceFirst("\\s*\\+.*", "")); try { // provide only direction, should cause an exception SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, ":asc", true); } catch (UniformInterfaceException e) { assertEquals(BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); } try { // provide sort field and direction, but direction is invalid (neither of asc or desc) SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "DateCreated:invalid", true); } catch (UniformInterfaceException e) { assertEquals(BAD_REQUEST.getStatusCode(), e.getResponse().getStatus()); } // From response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "From:asc", true); assertEquals("+13213557674", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("from").getAsString()); response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "From:desc", true); assertEquals("19549376176", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("from").getAsString()); // To response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "To:asc", true); assertEquals("+13213557674", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("to").getAsString()); response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "To:desc", true); assertEquals("19549376176", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("to").getAsString()); // Direction response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Direction:asc", true); assertEquals("inbound", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("direction").getAsString()); response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Direction:desc", true); assertEquals("outbound-reply", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("direction").getAsString()); // Status response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Status:asc", true); assertEquals("failed", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("status").getAsString()); response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Status:desc", true); assertEquals("sent", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("status").getAsString()); // Body response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, 34, "Body:asc", true); assertEquals("Hello", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("body").getAsString()); response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Body:desc", true); assertEquals("take 3", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("body").getAsString()); // Price response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Price:asc", true); assertEquals("0.00", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("price").getAsString()); response = SmsEndpointTool.getInstance().getSmsMessageList(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 0, pageSize, "Price:desc", true); assertEquals("120.00", ((JsonObject)response.get("messages").getAsJsonArray().get(0)).get("price").getAsString()); } @Deployment(name = "SmsMessagesEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_for_SMSEndpointTest.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
16,043
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UssdPushTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/UssdPushTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.text.ParseException; import javax.sip.RequestEvent; import javax.sip.ResponseEvent; import javax.sip.SipException; import javax.sip.address.Address; import javax.sip.header.ContentTypeHeader; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import com.google.gson.JsonObject; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class UssdPushTest { private final static Logger logger = Logger.getLogger(CreateCallsTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String ussdContentSubType = "vnd.3gpp.ussd+xml"; private static SipStackTool tool1; private static SipStackTool tool2; private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("CreateCalls1"); tool2 = new SipStackTool("CreaeCalls2"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } } @Test public void createUssdPushTestNotifyOnly() throws InterruptedException, SipException, ParseException { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = "bob"; String rcmlUrl = deploymentUrl.toString() + "/ussd-rcml.xml"; JsonObject callResult = RestcommUssdPushTool.getInstance().createUssdPush(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, null, "application", ussdContentSubType, null, null)); assertTrue(receivedBody.trim().equals(UssdPushTestMessages.ussdPushNotifyOnlyMessage)); bobCall.waitForAck(5000); Request infoRequest = bobCall.getDialog().createRequest(Request.INFO); ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml"); infoRequest.setContent(UssdPushTestMessages.ussdPushNotifyOnlyClientResponse.getBytes(), contentTypeHeader); SipTransaction sipTransaction = bobPhone.sendRequestWithTransaction(infoRequest, false, bobCall.getDialog()); assertNotNull(sipTransaction); ResponseEvent response = (ResponseEvent) bobPhone.waitResponse(sipTransaction, 5000); assertNotNull(response); assertTrue(response.getResponse().getStatusCode() == Response.OK); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(receivedBody.trim().equals(UssdPushTestMessages.ussdPushNotifyOnlyFinalResponse)); } @Test @Category(FeatureAltTests.class) public void createUssdPushTestNotifyOnlyFromIsRestcomm() throws InterruptedException, SipException, ParseException { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "Restcomm"; String to = "bob"; String rcmlUrl = deploymentUrl.toString() + "/ussd-rcml.xml"; JsonObject callResult = RestcommUssdPushTool.getInstance().createUssdPush(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, null, "application", ussdContentSubType, null, null)); assertTrue(receivedBody.trim().equals(UssdPushTestMessages.ussdPushNotifyOnlyMessage)); bobCall.waitForAck(5000); Request infoRequest = bobCall.getDialog().createRequest(Request.INFO); ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml"); infoRequest.setContent(UssdPushTestMessages.ussdPushNotifyOnlyClientResponse.getBytes(), contentTypeHeader); SipTransaction sipTransaction = bobPhone.sendRequestWithTransaction(infoRequest, false, bobCall.getDialog()); assertNotNull(sipTransaction); ResponseEvent response = (ResponseEvent) bobPhone.waitResponse(sipTransaction, 5000); assertNotNull(response); assertTrue(response.getResponse().getStatusCode() == Response.OK); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(receivedBody.trim().equals(UssdPushTestMessages.ussdPushNotifyOnlyFinalResponse)); } @Test public void createUssdPushTestCollect() throws InterruptedException, SipException, ParseException { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = "bob"; String rcmlUrl = deploymentUrl.toString() + "/ussd-rcml-collect.xml"; JsonObject callResult = RestcommUssdPushTool.getInstance().createUssdPush(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); //Wait for the USSD Push Tree Message assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, null, "application", ussdContentSubType, null, null)); assertTrue(receivedBody.equals(UssdPushTestMessages.ussdPushCollectMessage)); bobCall.waitForAck(5000); String toTag = bobCall.getDialog().getLocalTag(); Address bobAddress = bobPhone.getAddress(); //Prepare and send USSD Response "1" for the tree menu Request infoRequest = bobCall.getDialog().createRequest(Request.INFO); ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml"); infoRequest.setContent(UssdPushTestMessages.ussdPushCollectClientResponse.getBytes(), contentTypeHeader); SipTransaction sipTransaction = bobPhone.sendRequestWithTransaction(infoRequest, false, bobCall.getDialog()); assertNotNull(sipTransaction); ResponseEvent response = (ResponseEvent) bobPhone.waitResponse(sipTransaction, 5000); assertNotNull(response); assertTrue(response.getResponse().getStatusCode() == Response.OK); assertTrue(bobPhone.listenRequestMessage()); RequestEvent requestEvent = bobPhone.waitRequest(30*1000); assertNotNull(requestEvent); assertTrue(requestEvent.getRequest().getMethod().equalsIgnoreCase("INFO")); bobPhone.sendReply(requestEvent, 200, "OK", toTag, bobAddress, 0); String receivedUssdPayload = new String(requestEvent.getRequest().getRawContent()); assertTrue(receivedUssdPayload.equals(UssdPushTestMessages.ussdPushNotifyOnlyMessage)); //Prepare and send final "OK" USSD message to end the communication Request infoRequestFinal = bobCall.getDialog().createRequest(Request.INFO); infoRequestFinal.setContent(UssdPushTestMessages.ussdPushNotifyOnlyClientResponse.getBytes(), contentTypeHeader); SipTransaction sipTransactionFinal = bobPhone.sendRequestWithTransaction(infoRequestFinal, false, bobCall.getDialog()); assertNotNull(sipTransactionFinal); ResponseEvent responseFinal = (ResponseEvent) bobPhone.waitResponse(sipTransactionFinal, 5000); assertNotNull(responseFinal); assertTrue(responseFinal.getResponse().getStatusCode() == Response.OK); // Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(receivedBody.trim().equals(UssdPushTestMessages.ussdPushNotifyOnlyFinalResponse)); } @Deployment(name = "UssdPushTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("org/restcomm/connect/ussd/restcomm_conf_ussd_push.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("org/restcomm/connect/ussd/restcomm.script_ussdPullTest", "data/hsql/restcomm.script"); archive.addAsWebResource("org/restcomm/connect/ussd/ussd-rcml.xml"); archive.addAsWebResource("org/restcomm/connect/ussd/ussd-rcml-collect.xml"); logger.info("Packaged Test App"); return archive; } }
13,952
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientsEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/ClientsEndpointTest.java
package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.text.ParseException; import javax.sip.address.SipURI; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.http.client.ClientProtocolException; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.UnstableTests; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; /** * * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ClientsEndpointTest { private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static SipStackTool tool1; private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; String superadminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; //developer is account in Organization - default.restcomm.com String developerUsername = "[email protected]"; String developeerAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; String developerAccountSid = "AC11111111111111111111111111111111"; String removedClientSid = "CLb8838febabef4970a10dda1680506815"; //developerOrg2 is account in Organization - org2.restcomm.com String developerOrg2Username = "[email protected]"; String developeerOrg2AuthToken = "77f8c12cc7b8f8423e5c38b035249166"; String developerOrg2AccountSid = "AC11111111111111111111111111111112"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("ClientsEndpointTest"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } } // Issue 109: https://bitbucket.org/telestax/telscale-restcomm/issue/109 @Test public void createClientTest() throws ClientProtocolException, IOException, ParseException, InterruptedException { SipURI reqUri = bobSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); String clientSID = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "bob", "RestComm1234", deploymentUrl.toString() + "/demos/welcome.xml"); assertNotNull(clientSID); Thread.sleep(3000); String clientSID2 = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "bob", "RestComm1234", deploymentUrl.toString() + "/demos/welcome.xml"); assertNotNull(clientSID2); Thread.sleep(3000); assertTrue(clientSID.equalsIgnoreCase(clientSID2)); assertTrue(bobPhone.register(reqUri, "bob", "RestComm1234", bobContact, 1800, 1800)); bobContact = "sip:[email protected]:5090"; assertTrue(bobPhone.register(reqUri, "bob", "RestComm1234", bobContact, 1800, 1800)); assertTrue(bobPhone.unregister(bobContact, 0)); //update password and test register again Client jersey = getClient(superadminAccountSid, developeerAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + superadminAccountSid + "/Clients/" + clientSID2 ) ); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Password","RestComm1234RestComm1234"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, params); assertEquals(200, response.getStatus()); assertTrue(bobPhone.register(reqUri, "bob", "RestComm1234RestComm1234", bobContact, 1800, 1800)); assertTrue(bobPhone.unregister(bobContact, 0)); } @Test@Category(FeatureAltTests.class) public void createClientTestNoVoiceUrl() throws ClientProtocolException, IOException, ParseException, InterruptedException { SipURI reqUri = bobSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); String clientSID = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "bob", "RestComm1234", null); assertNotNull(clientSID); Thread.sleep(3000); String clientSID2 = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "bob", "RestComm1234", null); assertNotNull(clientSID2); Thread.sleep(3000); assertTrue(clientSID.equalsIgnoreCase(clientSID2)); assertTrue(bobPhone.register(reqUri, "bob", "RestComm1234", bobContact, 1800, 1800)); bobContact = "sip:[email protected]:5090"; assertTrue(bobPhone.register(reqUri, "bob", "RestComm1234", bobContact, 1800, 1800)); assertTrue(bobPhone.unregister(bobContact, 0)); } @Test public void clientRemovalBehaviour() { // A developer account should be able to remove his own client Client jersey = getClient(developerUsername, developeerAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients/" + removedClientSid ) ); ClientResponse response = resource.delete(ClientResponse.class); assertEquals("Developer account could not remove his client", 200, response.getStatus()); // re-removing the client should return a 404 (not a 200) response = resource.delete(ClientResponse.class); assertEquals("Removing a non-existing client did not return 404", 404, response.getStatus()); } @Test@Category(FeatureExpTests.class) public void createClientWithWeakPasswordShouldFail() throws IOException { Client jersey = getClient(developerUsername, developeerAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients.json" ) ); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Login","weakClient"); params.add("Password","1234"); // this is a very weak password ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); assertEquals(400, response.getStatus()); assertTrue("Response should contain 'weak' term", response.getEntity(String.class).toLowerCase().contains("weak")); } @Test@Category(FeatureExpTests.class) public void updateClientWithWeakPasswordShouldFail() { String updateClientSid = "CL00000000000000000000000000000001"; Client jersey = getClient(developerUsername, developeerAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients/" + updateClientSid ) ); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Password","1234"); // this is a very weak password ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, params); assertEquals(400, response.getStatus()); assertTrue("Response should contain 'weak' term", response.getEntity(String.class).toLowerCase().contains("weak")); } /** * createClientTestWithInvalidCharacters * https://github.com/RestComm/Restcomm-Connect/issues/1979 * @throws ClientProtocolException * @throws IOException * @throws ParseException * @throws InterruptedException */ @Test@Category(FeatureExpTests.class) public void createClientTestWithInvalidCharacters() throws ClientProtocolException, IOException, ParseException, InterruptedException { Client jersey = getClient(developerUsername, developeerAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients.json" ) ); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Login","[email protected]"); // login contains @ sign params.add("Password","RestComm1234!"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); assertEquals(400, response.getStatus()); assertTrue("Response should contain 'invalid' term", response.getEntity(String.class).toLowerCase().contains("invalid")); params = new MultivaluedMapImpl(); params.add("Login","maria.test?"); // login contains @ sign params.add("Password","RestComm1234!"); response = resource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); assertEquals(400, response.getStatus()); assertTrue("Response should contain 'invalid' term", response.getEntity(String.class).toLowerCase().contains("invalid")); params = new MultivaluedMapImpl(); params.add("Login","maria.test="); // login contains @ sign params.add("Password","RestComm1234!"); response = resource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); assertEquals(400, response.getStatus()); assertTrue("Response should contain 'invalid' term", response.getEntity(String.class).toLowerCase().contains("invalid")); } /** * addSameClientNameInDifferentOrganizations * https://github.com/RestComm/Restcomm-Connect/issues/2106 * We should be able to add same client in different organizations * */ @Test public void addSameClientNameInDifferentOrganizations() { /* * Add client maria in Organization - default.restcomm.com */ Client jersey = getClient(developerUsername, developeerAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients.json" ) ); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Login","maria"); params.add("Password","RestComm1234!"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); assertEquals(200, response.getStatus()); //try to add same client again in same organization - should not be allowed /*jersey = getClient(developerUsername, developeerAuthToken); resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients.json" ) ); params = new MultivaluedMapImpl(); params.add("Login","maria"); params.add("Password","RestComm1234!"); response = resource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); assertEquals(409, response.getStatus());*/ /* * Add client maria in Organization - org2.restcomm.com */ jersey = getClient(developerOrg2AccountSid, developeerOrg2AuthToken); resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + developerOrg2AccountSid + "/Clients.json" ) ); params = new MultivaluedMapImpl(); params.add("Login","maria"); params.add("Password","RestComm1234!"); response = resource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); assertEquals(200, response.getStatus()); } @Test@Category({FeatureAltTests.class, UnstableTests.class}) public void createClientTestWithIsPushEnabled() throws IOException, ParseException, InterruptedException { Client jersey = getClient(developerUsername, developeerAuthToken); WebResource resource = jersey.resource( getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients.json" ) ); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Login","bob"); // login contains @ sign params.add("Password","RestComm1234!"); params.add("IsPushEnabled", "true"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); assertEquals(200, response.getStatus()); assertTrue("Response should contain 'push_client_identity'", response.getEntity(String.class).contains("push_client_identity")); } @Test@Category(FeatureAltTests.class) public void updateClientTestWithIsPushEnabled() throws IOException, ParseException, InterruptedException { String sid = CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), developerAccountSid, developeerAuthToken, "agafox", "RestComm1234", null); // add push_client_identity Client jersey = getClient(developerUsername, developeerAuthToken); WebResource resource = jersey.resource(getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients/" + sid + ".json" )); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.putSingle("IsPushEnabled", "true"); ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, params); assertEquals(200, response.getStatus()); assertTrue("Response should contain 'push_client_identity'", response.getEntity(String.class).contains("push_client_identity")); // remove push_client_identity resource = jersey.resource(getResourceUrl("/2012-04-24/Accounts/" + developerAccountSid + "/Clients/" + sid + ".json")); params.putSingle("IsPushEnabled", "false"); response = resource.accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, params); assertEquals(200, response.getStatus()); assertFalse("Response shouldn't contain 'push_client_identity'", response.getEntity(String.class).contains("push_client_identity")); } protected String getResourceUrl(String suffix) { String urlString = deploymentUrl.toString(); if ( urlString.endsWith("/") ) urlString = urlString.substring(0,urlString.length()-1); if ( suffix != null && !suffix.isEmpty()) { if (!suffix.startsWith("/")) suffix = "/" + suffix; return urlString + suffix; } else return urlString; } protected Client getClient(String username, String password) { Client jersey = Client.create(); jersey.addFilter(new HTTPBasicAuthFilter(username, password)); return jersey; } @Deployment(name = "ClientsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_clients_test", "data/hsql/restcomm.script"); return archive; } }
16,936
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OrganizationsEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/OrganizationsEndpointTest.java
package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertTrue; import java.net.URL; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.UnstableTests; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.sun.jersey.api.client.ClientResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; /** * @author maria */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class OrganizationsEndpointTest extends EndpointTest { private final static Logger logger = Logger.getLogger(OrganizationsEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; //super admin account private String superAdminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String superAdminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; //admin account private String adminAccountSid = "AC574d775522c96f9aacacc5ca60c8c74g"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; //developer account private String devAccountSid = "AC574d775522c96f9aacacc5ca60c8c74f"; private String devAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private final String org1 = "ORafbe225ad37541eba518a74248f0ac4c"; private final String org2 = "ORafbe225ad37541eba518a74248f0ac4d"; @BeforeClass public static void beforeClass() { } /** * SuperAdmin is allowed to read any organization * this test will try to Read single organization and read list */ @Test @Category(UnstableTests.class) public void getOrganizationFromSuperAdminAccount(){ JsonObject organizationJsonObject = RestcommOrganizationsTool.getInstance().getOrganization(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken, org1); assertTrue(organizationJsonObject!=null); logger.info("organization: "+organizationJsonObject); // only superadmin can read an org that does not affiliate with its account organizationJsonObject = null; organizationJsonObject = RestcommOrganizationsTool.getInstance().getOrganization(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken, org2); assertTrue(organizationJsonObject!=null); //only superadmin can read the whole list of organizations JsonArray jsonArray = null; jsonArray = RestcommOrganizationsTool.getInstance().getOrganizationList(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken, null); logger.info("organization list: "+jsonArray); assertTrue(jsonArray!=null); assertTrue(jsonArray.size() == 3); } /** * Administrators can read only affiliated organization * this test will try to Read single organization and read list */ @Test public void getOrganizationFromAdministratorAccount(){ ClientResponse clientResponse = RestcommOrganizationsTool.getInstance().getOrganizationResponse(deploymentUrl.toString(), adminAccountSid, adminAuthToken, org1); assertNotNull(clientResponse); logger.info("organization: "+clientResponse); assertEquals(200 , clientResponse.getStatus()); // only superadmin can read an org that does not affiliate with its account clientResponse = null; clientResponse = RestcommOrganizationsTool.getInstance().getOrganizationResponse(deploymentUrl.toString(), adminAccountSid, adminAuthToken, org2); assertTrue(clientResponse!=null); logger.info("organization: "+clientResponse); assertEquals(403, 403); //only superadmin can read the whole list of organizations clientResponse = null; clientResponse = RestcommOrganizationsTool.getInstance().getOrganizationsResponse(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("organization list: "+clientResponse); assertTrue(clientResponse!=null); assertEquals(403, clientResponse.getStatus()); } /** * Developers can not read organization * this test will try to Read single organization and read list */ @Test @Category(FeatureExpTests.class) public void getOrganizationFromDeveloperAccount(){ ClientResponse clientResponse = RestcommOrganizationsTool.getInstance().getOrganizationResponse(deploymentUrl.toString(), devAccountSid, devAuthToken, org1); assertTrue(clientResponse!=null); logger.info("organization: "+clientResponse); assertTrue(clientResponse.getStatus() == 403); // only superadmin can read an org that does not affiliate with its account clientResponse = null; clientResponse = RestcommOrganizationsTool.getInstance().getOrganizationResponse(deploymentUrl.toString(), devAccountSid, devAuthToken, org2); assertTrue(clientResponse!=null); logger.info("organization: "+clientResponse); assertTrue(clientResponse.getStatus() == 403); //only superadmin can read the whole list of organizations clientResponse = null; clientResponse = RestcommOrganizationsTool.getInstance().getOrganizationsResponse(deploymentUrl.toString(), devAccountSid, devAuthToken); logger.info("organization list: "+clientResponse); assertTrue(clientResponse!=null); assertTrue(clientResponse.getStatus() == 403); } /** * getOrganizationListByStatus */ @Test @Category({UnstableTests.class}) public void getOrganizationListByStatus(){ JsonArray jsonArray = null; jsonArray = RestcommOrganizationsTool.getInstance().getOrganizationList(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken, "active"); logger.info("organization list: "+jsonArray); assertTrue(jsonArray!=null); assertTrue(jsonArray.size() == 2); jsonArray = null; jsonArray = RestcommOrganizationsTool.getInstance().getOrganizationList(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken, "closed"); logger.info("organization list: "+jsonArray); assertTrue(jsonArray!=null); assertTrue(jsonArray.size() == 1); } /** * createOrganizationTest * only super admin can create a new organization */ @Test public void createOrganizationTest(){ //super admin tries to create org ClientResponse clientResponse = RestcommOrganizationsTool.getInstance().createOrganizationResponse(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken, "newdomain"); logger.info("clientResponse: "+clientResponse); assertTrue(clientResponse.getStatus() == 200); // create an org that domain name already exists //super admin tries to create org that already exists clientResponse = RestcommOrganizationsTool.getInstance().createOrganizationResponse(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken, "newdomain"); logger.info("clientResponse: "+clientResponse); assertTrue(clientResponse.getStatus() == 409); //admin tries to create org clientResponse = RestcommOrganizationsTool.getInstance().createOrganizationResponse(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "newdomain"); logger.info("clientResponse: "+clientResponse); assertTrue(clientResponse.getStatus() == 403); //developer tries to create org clientResponse = RestcommOrganizationsTool.getInstance().createOrganizationResponse(deploymentUrl.toString(), devAccountSid, devAuthToken, "newdomain"); logger.info("clientResponse: "+clientResponse); assertTrue(clientResponse.getStatus() == 403); } @Deployment(name = "OrganizationsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_accounts_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
9,461
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CacheServletTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/CacheServletTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import junit.framework.Assert; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import java.net.URL; /** * Test the servlet serving the media cache content is working. * * The restcomm configuration will be filtered by maven to replace the cache path * to be in target/test-classes * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CacheServletTest extends EndpointTest { private final static Logger logger = Logger.getLogger(CacheServletTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Test public void testMediaDownloading() { Client jersey = Client.create(); WebResource resource = jersey.resource(getResourceUrl("/cache/ACae6e420f425248d6a26948c17a9e2acf/101cc31d1b07e8285c40d13d83f63da9caaaf21155a321f231980601bac555de.wav")); ClientResponse response = resource.get(ClientResponse.class); Assert.assertEquals(200, response.getStatus()); } @Deployment(name = "CacheServletTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); //this is the file maven filtered accordingly archive.addAsWebInfResource("restcomm-cache.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
3,748
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/EndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2016, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.test.api.ArquillianResource; import org.junit.After; import org.restcomm.connect.commons.Version; import java.net.URL; /** * Base class that hides some of the boilerplate code need to set-up a new automated test. You will need to extend * and provide your own 'logger' and createWebArchiveNoGw() method. * * @author Orestis Tsakiridis */ public class EndpointTest { protected static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @After public void after() throws InterruptedException { Thread.sleep(1000); } protected String getResourceUrl(String suffix) { String urlString = deploymentUrl.toString(); if ( urlString.endsWith("/") ) urlString = urlString.substring(0,urlString.length()-1); if ( suffix != null && !suffix.isEmpty()) { if (!suffix.startsWith("/")) suffix = "/" + suffix; return urlString + suffix; } else return urlString; } protected Client getClient(String username, String password) { Client jersey = Client.create(); jersey.addFilter(new HTTPBasicAuthFilter(username, password)); return jersey; } }
2,339
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
LiveCallModificationMuteUnMuteTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/LiveCallModificationMuteUnMuteTest.java
package org.restcomm.connect.testsuite.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * LiveCallModificationMuteUnMuteTest * @author mariafarooq * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class LiveCallModificationMuteUnMuteTest { private final static Logger logger = Logger.getLogger(CreateCallsTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static SipStackTool tool1; private static SipStackTool tool2; private SipStack mariaSipStack; private SipPhone mariaPhone; private String mariaContact = "sip:[email protected]:5090"; private SipStack buttSipStack; private SipPhone buttPhone; private String buttContact = "sip:[email protected]:5070"; String dialConference = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Response>\n" + "\t<Dial timeout=\"10\">\n" + "\t <Conference muted=\"true\" startConferenceOnEnter=\"false\" beep=\"false\">Conf1234</Conference>\n" + "\t</Dial>\n" + "</Response>"; private final String confRoom2 = "confRoom2"; private String dialConfernceRcml = "<Response><Dial><Conference>"+confRoom2+"</Conference></Dial></Response>"; private String dialRestcommConference = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("LiveCallModification1"); tool2 = new SipStackTool("LiveCallModification2"); } @Before public void before() throws Exception { mariaSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); mariaPhone = mariaSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, mariaContact); buttSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); buttPhone = buttSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, buttContact); } @After public void after() throws Exception { if (mariaPhone != null) { mariaPhone.dispose(); } if (mariaSipStack != null) { mariaSipStack.dispose(); } if (buttPhone != null) { buttPhone.dispose(); } if (buttSipStack != null) { buttSipStack.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } /** * muteUnmuteInProgressConferenceParticipant * this test will: * 1. start a conference with 2 participants * 2. mute one praticipant * 3. unmute it * @throws Exception */ @Test @Category(FeatureAltTests.class) public void muteUnmuteInProgressConferenceParticipant() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml))); // maria Dials the conference final SipCall mariaCall = mariaPhone.createSipCall(); mariaCall.initiateOutgoingCall(mariaContact, dialRestcommConference, null, body, "application", "sdp", null, null); assertLastOperationSuccess(mariaCall); assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); int responsemaria = mariaCall.getLastReceivedResponse().getStatusCode(); assertTrue(responsemaria == Response.TRYING || responsemaria == Response.RINGING); if (responsemaria == Response.TRYING) { assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, mariaCall.getLastReceivedResponse().getStatusCode()); } assertTrue(mariaCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, mariaCall.getLastReceivedResponse().getStatusCode()); mariaCall.sendInviteOkAck(); assertTrue(!(mariaCall.getLastReceivedResponse().getStatusCode() >= 400)); // butt Dials the conference final SipCall buttCall = buttPhone.createSipCall(); buttCall.initiateOutgoingCall(buttContact, dialRestcommConference, null, body, "application", "sdp", null, null); assertLastOperationSuccess(buttCall); assertTrue(buttCall.waitOutgoingCallResponse(5 * 1000)); int responsebutt = buttCall.getLastReceivedResponse().getStatusCode(); assertTrue(responsebutt == Response.TRYING || responsebutt == Response.RINGING); if (responsebutt == Response.TRYING) { assertTrue(buttCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, buttCall.getLastReceivedResponse().getStatusCode()); } assertTrue(buttCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, buttCall.getLastReceivedResponse().getStatusCode()); buttCall.sendInviteOkAck(); assertTrue(!(buttCall.getLastReceivedResponse().getStatusCode() >= 400)); Thread.sleep(2000); JsonObject confObject = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(confObject); JsonArray confArray = confObject.getAsJsonArray("conferences"); assertNotNull(confArray); String conferenceSid = confArray.get(0).getAsJsonObject().get("sid").getAsString(); assertNotNull(conferenceSid); JsonObject partObject = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, conferenceSid); assertNotNull(partObject); JsonArray callsArray = partObject.getAsJsonArray("calls"); int size = callsArray.size(); assertEquals(2, size); logger.info("callsArray: "+callsArray); //any call sid String firstCallSid = callsArray.get(0).getAsJsonObject().get("sid").getAsString(); //Going to mute : JsonObject muteResponse = RestcommConferenceParticipantsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, conferenceSid, adminAuthToken, firstCallSid, true); assertNotNull(muteResponse); JsonObject modifiedParticipant = RestcommConferenceParticipantsTool.getInstance().getParticipant(deploymentUrl.toString(), adminAccountSid, conferenceSid, adminAuthToken, firstCallSid); assertNotNull(modifiedParticipant); Boolean muted = modifiedParticipant.get("muted").getAsBoolean(); assertTrue(muted); //Going to unmute : JsonObject unmuteResponse = RestcommConferenceParticipantsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, conferenceSid, adminAuthToken, firstCallSid, false); assertNotNull(muteResponse); modifiedParticipant = RestcommConferenceParticipantsTool.getInstance().getParticipant(deploymentUrl.toString(), adminAccountSid, conferenceSid, adminAuthToken, firstCallSid); assertNotNull(modifiedParticipant); muted = modifiedParticipant.get("muted").getAsBoolean(); assertTrue(!muted); } @Deployment(name = "LiveCallModificationTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-number-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("hello-play.xml"); logger.info("Packaged Test App"); return archive; } }
11,055
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountsMigrationEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/AccountsMigrationEndpointTest.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import java.net.URL; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AccountsMigrationEndpointTest { final static Logger logger = Logger.getLogger(AccountsMigrationEndpointTest.class); private static final String version = Version.getVersion(); @ArquillianResource URL deploymentUrl; private String adminUsername = "[email protected]"; private String adminFriendlyName = "Default Administrator Account"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String adminPassword = "RestComm"; private String parentUsername = "[email protected]"; private String parentSid = "AC574d775522c96f9aacacc5ca60c8c74f"; private String parentAuthToken ="77f8c12cc7b8f8423e5c38b035249166"; @Test public void testMigrateParentAndChildAccount() { String childSid1 = "AC55555555555555555555555555555555"; String originalOrganizationSid = "ORafbe225ad37541eba518a74248f0ac4c"; String newOrganizationSid = "ORafbe225ad37541eba518a74248f0ac4d"; JsonObject currentParentAccout = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, parentSid); assertNotNull(currentParentAccout); String currentOrg = currentParentAccout.get("organization").getAsString(); assertEquals(originalOrganizationSid, currentOrg); JsonObject currentChildAccout = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, childSid1); assertNotNull(currentChildAccout); String currentChildOrg = currentChildAccout.get("organization").getAsString(); assertEquals(originalOrganizationSid, currentChildOrg); //Migrate Parent Account and child accounts RestcommAccountsTool.getInstance().migrateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, parentSid, newOrganizationSid); JsonObject migratedParentAccount = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, parentSid); assertNotNull(migratedParentAccount); String parentNewOrg = migratedParentAccount.getAsJsonObject().get("organization").getAsString(); assertEquals(newOrganizationSid, parentNewOrg); assertTrue(!currentOrg.equalsIgnoreCase(parentNewOrg)); JsonObject childAccount1 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, childSid1); assertNotNull(childAccount1); String childNewOrg = childAccount1.get("organization").getAsString(); assertEquals(newOrganizationSid, childNewOrg); //Migrate Parent Account and child accounts assertNotNull(RestcommAccountsTool.getInstance().migrateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, parentSid, originalOrganizationSid)); } @Test public void testAttemptToMigrateAchildAccountShouldFail() { String childSid1 = "AC55555555555555555555555555555555"; String originalOrganizationSid = "ORafbe225ad37541eba518a74248f0ac4c"; String newOrganizationSid = "ORafbe225ad37541eba518a74248f0ac4d"; JsonObject currentChildAccout = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, childSid1); assertNotNull(currentChildAccout); String currentChildOrg = currentChildAccout.get("organization").getAsString(); assertEquals(originalOrganizationSid, currentChildOrg); //Migrate Parent Account and child accounts JsonObject response = RestcommAccountsTool.getInstance().migrateAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, childSid1, newOrganizationSid); assertNull(response); JsonObject childAccount1 = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, childSid1); assertNotNull(childAccount1); String childNewOrg = childAccount1.get("organization").getAsString(); assertEquals(originalOrganizationSid, childNewOrg); } @Test public void testAttemptToMigrateAccountByNonSuperAdminShouldFail() { String childSid1 = "AC55555555555555555555555555555555"; String originalOrganizationSid = "ORafbe225ad37541eba518a74248f0ac4c"; String newOrganizationSid = "ORafbe225ad37541eba518a74248f0ac4d"; JsonObject currentParentAccout = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, parentSid); assertNotNull(currentParentAccout); String currentOrg = currentParentAccout.get("organization").getAsString(); assertEquals(originalOrganizationSid, currentOrg); JsonObject currentChildAccout = RestcommAccountsTool.getInstance().getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, childSid1); assertNotNull(currentChildAccout); String currentChildOrg = currentChildAccout.get("organization").getAsString(); assertEquals(originalOrganizationSid, currentChildOrg); //Migrate Parent Account and child accounts JsonObject response = RestcommAccountsTool.getInstance().migrateAccount(deploymentUrl.toString(), parentUsername, parentAuthToken, parentSid, newOrganizationSid); assertNull(response); assertEquals(originalOrganizationSid, RestcommAccountsTool.getInstance(). getAccount(deploymentUrl.toString(), adminUsername, adminAuthToken, parentSid).get("organization").getAsString()); } @Deployment(name = "AccountsMigrationEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_accounts_migration_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
7,648
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AccountsEndpointOrganizationsTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/AccountsEndpointOrganizationsTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2018, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.Version; import org.restcomm.connect.testsuite.http.util.CustomDnsResolver; import java.net.URL; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AccountsEndpointOrganizationsTest extends EndpointTest { private final static Logger logger = Logger.getLogger(AccountsEndpointOrganizationsTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String org1Username = "[email protected]"; private String adminFriendlyName = "Default Administrator Account"; private String org1AccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; private String org1AuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String org2Username = "[email protected]"; private String org2AccountSid = "ACae6e420f425248d6a26948c17a9e2ach"; private String org2AuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String org3Username = "[email protected]"; private String org3AccountSid = "ACae6e420f425248d6a26948c17a9e2acl"; private String org3AuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @BeforeClass public static void beforeClass() { Map<String, String> domainIpMap = new HashMap<>(); domainIpMap.put("org1.restcomm.com", "127.0.0.1"); domainIpMap.put("org2.restcomm.com", "127.0.0.1"); domainIpMap.put("org3.restcomm.com", "127.0.0.1"); CustomDnsResolver.setNameService(domainIpMap); } @Test public void testGetAccount() { // Get Account using admin email address and user email address String url = "http://org1.restcomm.com:8080/restcomm"; JsonObject adminAccount = RestcommAccountsTool.getInstance().getAccount(url, org1Username, org1AuthToken, org1Username); assertTrue(adminAccount.get("sid").getAsString().equals(org1AccountSid)); } @Test public void testGetAccountOrg2() { // Get Account using admin email address and user email address String org2Url = "http://org2.restcomm.com:8080/restcomm"; JsonObject org2account = RestcommAccountsTool.getInstance().getAccount(org2Url, org2Username, org2AuthToken, org2Username); assertTrue(org2account.get("sid").getAsString().equals(org2AccountSid)); } @Test public void testGetAccountOrg3() { // when(new InetSocketAddress(any(String.class),8080)).thenReturn(new InetSocketAddress("127.0.0.1",8080)); // Get Account using admin email address and user email address String org3Url = "http://org3.restcomm.com:8080/restcomm"; JsonObject org3account = RestcommAccountsTool.getInstance().getAccount(org3Url, org3Username, org3AuthToken, org3Username); assertTrue(org3account.get("sid").getAsString().equals(org3AccountSid)); } @Test @Ignore //TODO temporarely disable organization domain validation - https://telestax.atlassian.net/browse/BS-408 public void testGetAccountOrg3WithOrg2Url() { // Get Account using admin email address and user email address String org2Url = "http://org2.restcomm.com:8080/restcomm"; ClientResponse accountResponse = RestcommAccountsTool.getInstance().getAccountResponse(org2Url, org3Username, org3AuthToken, org3Username); assertEquals(403, accountResponse.getClientResponseStatus().getStatusCode()); } @Test public void testRemoveClientOfOrg2UsingOrg3Credentials() { String org2Url = "http://org2.restcomm.com:8080/restcomm"; String clientOfORg2 = "CLae6e420f425248d6a26948c17a9e2ach"; Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(org2Username, org3AuthToken)); WebResource resource = jerseyClient.resource(org2Url).path("/2012-04-24/Accounts/" + org3AccountSid+ "/Clients/" + clientOfORg2); ClientResponse response = resource.delete(ClientResponse.class); //This request will fail because Client is trying to access resources of ORG2 using credentials of ORG3 //and security filter will drop this request because ORG3.domainName != Request.host assertEquals(403, response.getStatus()); } @Deployment(name = "ClientsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script-accounts_organizations", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
7,387
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OutboundProxyEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/OutboundProxyEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertTrue; import java.net.URL; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import com.google.gson.JsonObject; import org.restcomm.connect.commons.Version; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class OutboundProxyEndpointTest { private final static Logger logger = Logger.getLogger(OutboundProxyEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; @Test public void getProxiesTest() { JsonObject proxiesJsonObject = OutboundProxyTool.getInstance().getProxies(deploymentUrl.toString(), adminAccountSid, adminAuthToken); String activeProxy = proxiesJsonObject.get("ActiveProxy").getAsString(); String primaryProxy = proxiesJsonObject.get("PrimaryProxy").getAsString(); String fallbackProxy = proxiesJsonObject.get("FallbackProxy").getAsString(); Boolean usingFallbackProxy = proxiesJsonObject.get("UsingFallBackProxy").getAsBoolean(); Boolean allowFallbackToPrimary = proxiesJsonObject.get("AllowFallbackToPrimary").getAsBoolean(); assertTrue(!usingFallbackProxy); assertTrue(allowFallbackToPrimary); assertTrue(activeProxy.equalsIgnoreCase(primaryProxy)); assertTrue(fallbackProxy.equalsIgnoreCase("127.0.0.1:5090")); } @Test public void switchProxyTest() { JsonObject proxiesJsonObject = OutboundProxyTool.getInstance().getProxies(deploymentUrl.toString(), adminAccountSid, adminAuthToken); String activeProxy = proxiesJsonObject.get("ActiveProxy").getAsString(); String primaryProxy = proxiesJsonObject.get("PrimaryProxy").getAsString(); String fallbackProxy = proxiesJsonObject.get("FallbackProxy").getAsString(); Boolean usingFallbackProxy = proxiesJsonObject.get("UsingFallBackProxy").getAsBoolean(); Boolean allowFallbackToPrimary = proxiesJsonObject.get("AllowFallbackToPrimary").getAsBoolean(); assertTrue(!usingFallbackProxy); assertTrue(allowFallbackToPrimary); assertTrue(activeProxy.equalsIgnoreCase(primaryProxy)); assertTrue(fallbackProxy.equalsIgnoreCase("127.0.0.1:5090")); //Switch to fallback JsonObject switchProxyJsonObject = OutboundProxyTool.getInstance().switchProxy(deploymentUrl.toString(), adminAccountSid, adminAuthToken); activeProxy = switchProxyJsonObject.get("ActiveProxy").getAsString(); assertTrue(activeProxy.equalsIgnoreCase(fallbackProxy)); JsonObject activeProxyJsonObject = OutboundProxyTool.getInstance().getActiveProxy(deploymentUrl.toString(), adminAccountSid, adminAuthToken); activeProxy = activeProxyJsonObject.get("ActiveProxy").getAsString(); assertTrue(activeProxy.equalsIgnoreCase(fallbackProxy)); //Switch back to primary switchProxyJsonObject = OutboundProxyTool.getInstance().switchProxy(deploymentUrl.toString(), adminAccountSid, adminAuthToken); activeProxy = switchProxyJsonObject.get("ActiveProxy").getAsString(); assertTrue(activeProxy.equalsIgnoreCase(primaryProxy)); activeProxyJsonObject = OutboundProxyTool.getInstance().getActiveProxy(deploymentUrl.toString(), adminAccountSid, adminAuthToken); activeProxy = activeProxyJsonObject.get("ActiveProxy").getAsString(); assertTrue(activeProxy.equalsIgnoreCase(primaryProxy)); } @Deployment(name = "OutboundProxyEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
6,208
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
LiveCallModificationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/LiveCallModificationTest.java
package org.restcomm.connect.testsuite.http; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.net.URL; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.cafesip.sipunit.SipTransaction; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.BrokenTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(UnstableTests.class) public class LiveCallModificationTest { private final static Logger logger = Logger.getLogger(CreateCallsTest.class.getName()); private static final String version = Version.getVersion(); private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53, 53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49, 13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65, 86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 }; private static final String body = new String(bytes); @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; private String dialRestcomm = "sip:[email protected]:5080"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("LiveCallModification1"); tool2 = new SipStackTool("LiveCallModification2"); tool3 = new SipStackTool("LiveCallModification3"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); aliceSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } Thread.sleep(1000); wireMockRule.resetRequests(); Thread.sleep(4000); } private int getConferencesSize() { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(),adminAccountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); return conferenceArray.size(); } private int getParticipantsSize(final String name) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), adminAccountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); String confSid = null; for (int i = 0; i < conferenceArray.size(); i++) { JsonObject confObj = conferenceArray.get(i).getAsJsonObject(); String confName = confObj.get("friendly_name").getAsString(); if (confName.equalsIgnoreCase(name)) { confSid = confObj.get("sid").getAsString(); break; } } // confSid = conferenceArray.get(conferenceArray.size()-1).getAsJsonObject().get("sid").getAsString(); JsonObject participants = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confSid); JsonArray participantsArray = participants.getAsJsonArray("calls"); return participantsArray.size(); } @Test // Terminate a call in-progress using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 public void terminateInProgressCall() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(1000); bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "completed", null); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); georgeCall.dispose(); bobCall.dispose(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private final String confRoom3 = "confRoom3"; private String dialConfernceRcml3 = "<Response><Dial><Conference>"+confRoom3+"</Conference></Dial></Response>"; @Test public synchronized void testDialConferenceTerminateWithLCM() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConfernceRcml3))); final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.initiateOutgoingCall(georgeContact, dialRestcomm, null, body, "application", "sdp", null, null); assertLastOperationSuccess(georgeCall); assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode(); assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING); if (responseGeorge == Response.TRYING) { assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode()); } assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode()); georgeCall.sendInviteOkAck(); assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400)); String callSid = georgeCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); Thread.sleep(3000); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(1,liveCalls); assertEquals(1, liveCallsArraySize); assertTrue(getConferencesSize()>=1); int numOfParticipants = getParticipantsSize(confRoom3); logger.info("Number of participants: "+numOfParticipants); assertTrue(numOfParticipants==1); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertTrue(mgcpEndpoints>0); assertTrue(mgcpConnections>0); Thread.sleep(3000); georgeCall.listenForDisconnect(); JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "completed", null); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); Thread.sleep(5000); liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(), adminAccountSid, adminAuthToken); liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(), adminAccountSid, adminAuthToken); logger.info("&&&&& LiveCalls: "+liveCalls); logger.info("&&&&& LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); assertTrue(getConferencesSize()>=1); int confRoom2Participants = getParticipantsSize(confRoom3); logger.info("&&&&& ConfRoom2Participants: "+confRoom2Participants); assertTrue(confRoom2Participants==0); metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test // Terminate a call in-progress using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 public void terminateInProgressCallAlreadyTerminated() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(1000); bobCall.listenForDisconnect(); georgeCall.listenForDisconnect(); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "completed", null); assertTrue(georgeCall.waitForDisconnect(5000)); assertTrue(georgeCall.respondToDisconnect()); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(1000); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "completed", null); assertNotNull(callResult); georgeCall.dispose(); bobCall.dispose(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test // Terminate a call that is ringing using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 public void terminateRingingCall() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry-lcm.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob1", 3600)); Thread.sleep(1000); bobCall.listenForDisconnect(); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "canceled", null); SipTransaction transaction = bobCall.waitForCancel(5000); assertNotNull(transaction); bobCall.respondToCancel(transaction, 200, "OK-2-Cancel-Bob", 3600); georgeCall.dispose(); bobCall.dispose(); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test // Redirect a call to a different URL using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 // TODO: This test is expected to fail because of issue https://bitbucket.org/telestax/telscale-restcomm/issue/192 public void redirectCall() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitForAck(5000)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to redirect the call\n ********************\n"); rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, rcmlUrl); georgeCall.listenForDisconnect(); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); // Restcomm now should execute the new RCML and create a call to Alice Restcomm client // TODO: This test is expected to fail because of issue https://bitbucket.org/telestax/telscale-restcomm/issue/192 assertTrue(aliceCall.waitForIncomingCall(5000)); receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(aliceCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } String dialConference = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Response>\n" + "\t<Dial timeout=\"10\">\n" + "\t <Conference muted=\"true\" startConferenceOnEnter=\"false\" beep=\"false\">Conf1234</Conference>\n" + "\t</Dial>\n" + "</Response>"; @Test // Redirect a call to a different URL using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 // TODO: This test is expected to fail because of issue https://bitbucket.org/telestax/telscale-restcomm/issue/192 public void redirectCallInConferenceMuted() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialConference))); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); Credential bobCredential = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(bobCredential); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertTrue(bobCall.waitForAuthorisation(5000)); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(bobCall.sendInviteOkAck()); // // // String from = "+15126002188"; // String to = bobContact; // String rcmlUrl = "http://127.0.0.1:8090/1111"; // // JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, // adminAuthToken, from, to, rcmlUrl); // assertNotNull(callResult); // String callSid = callResult.get("sid").getAsString(); // // assertTrue(bobCall.waitForIncomingCall(5000)); // String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); // assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); // assertTrue(bobCall // .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // // assertTrue(bobCall.waitForAck(5000)); // // // Restcomm now should execute RCML that will create a call to +131313 (george's phone) // // assertTrue(georgeCall.waitForIncomingCall(5000)); // receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); // assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); // assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", // null, null)); // // assertTrue(georgeCall.waitForAck(5000)); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to redirect the call\n ********************\n"); String rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, rcmlUrl); // georgeCall.listenForDisconnect(); // assertTrue(georgeCall.waitForDisconnect(10000)); // assertTrue(georgeCall.respondToDisconnect()); // Restcomm now should execute the new RCML and create a call to Alice Restcomm client // TODO: This test is expected to fail because of issue https://bitbucket.org/telestax/telscale-restcomm/issue/192 assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); aliceCall.listenForDisconnect(); bobCall.listenForDisconnect(); assertTrue(aliceCall.disconnect()); assertTrue(aliceCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialAlice = "<Response><Dial><Client>alice</Client></Dial></Response>"; private String confUnHold = "<Response>\n" + " <Dial>\n" + " <Conference startConferenceOnEnter=\"true\">HoldConf1234</Conference>\n" + " </Dial>\n" + "</Response>"; private String confHold = "<Response>\n" + "\t<Dial>\n" + "\t\t<Conference startConferenceOnEnter=\"false\" waitUrl=\"/restcomm/music/rock/nickleus_-_original_guitar_song_200907251723.wav\">HoldConf1234</Conference>\n" + "\t</Dial>\n" + "</Response>"; @Test @Category(BrokenTests.class) @Ignore public void holdCall() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialAlice))); stubFor(post(urlPathEqualTo("/hold")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(confHold))); stubFor(post(urlPathEqualTo("/unhold")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(confUnHold))); Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertTrue(bobCall.waitForAuthorisation(5000)); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); logger.info("Last response: "+response); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(bobCall.sendInviteOkAck()); assertTrue(aliceCall.waitForIncomingCall(5000)); String receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent()); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "OK-Alice", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to put call on hold\n ********************\n"); String rcmlUrl = "http://127.0.0.1:8090/hold"; JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, rcmlUrl, true); Thread.sleep(10000); JsonObject confObject = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), adminAccountSid, adminAuthToken); assertNotNull(confObject); JsonArray confArray = confObject.getAsJsonArray("conferences"); assertNotNull(confArray); String confSid = confArray.get(0).getAsJsonObject().get("sid").getAsString(); assertNotNull(confSid); JsonObject partObject = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confSid); assertNotNull(partObject); JsonArray callsArray = partObject.getAsJsonArray("calls"); int size = callsArray.size(); assertEquals(2, size); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to unhold calls\n ********************\n"); rcmlUrl = "http://127.0.0.1:8090/unhold"; callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, rcmlUrl, true); Thread.sleep(2000); partObject = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confSid); assertNotNull(partObject); callsArray = partObject.getAsJsonArray("calls"); size = callsArray.size(); assertEquals(2, size); Thread.sleep(2000); bobCall.disconnect(); aliceCall.disconnect(); Thread.sleep(1000); partObject = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, confSid); assertNotNull(partObject); callsArray = partObject.getAsJsonArray("calls"); size = callsArray.size(); assertEquals(0, size); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test // Redirect a call to a different URL using the Live Call Modification API. Non-regression test for issue: // https://bitbucket.org/telestax/telscale-restcomm/issue/139 public void redirectCallInvalidCallSid() throws Exception { SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); // Register Alice Restcomm client SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = deploymentUrl.toString() + "/dial-number-entry.xml"; JsonObject callResult = (JsonObject) RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); assertNotNull(callResult); String callSid = callResult.get("sid").getAsString(); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(bobCall.waitForAck(5000)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); assertTrue(georgeCall.waitForAck(5000)); Thread.sleep(10000); System.out.println("\n ******************** \nAbout to redirect the call\n ********************\n"); rcmlUrl = deploymentUrl.toString() + "/dial-client-entry.xml"; //String invalidCallSid = Sid.generate(Sid.Type.CALL).toString(); // restcomm-connect/1907 String invalidCallSid = "IDaaaaaaaaaaabbbbbbbbbbbcccccccddd-CAaaaaaabbbbbcccccdddddeeeeeffffgg"; callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, invalidCallSid, null, rcmlUrl); assertNotNull(callResult); String exc = callResult.get("Exception").getAsString(); assertTrue(callResult.get("Exception").getAsString().equals("406")); georgeCall.listenForDisconnect(); assertTrue(bobCall.disconnect()); assertTrue(georgeCall.waitForDisconnect(10000)); assertTrue(georgeCall.respondToDisconnect()); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String dialFork = "<Response><Dial record=\"true\" timeout=\"150\" action=\"/completed\"><Client>alice</Client><Number>+131313</Number></Dial></Response>"; @Test public void testTerminateDialForkCallWhileRinging_LCM_to_dial_branches() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); stubFor(post(urlPathEqualTo("/completed")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String georgeCallSid = georgeCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String aliceCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); georgeCall.listenForCancel(); aliceCall.listenForCancel(); //LCM request to terminate RINGING calls JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, aliceCallSid, "canceled", null); assertNotNull(callResult); callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, georgeCallSid, "canceled", null); assertNotNull(callResult); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(aliceCancelTransaction); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); bobCall.disconnect(); //Wait to cancel the other branches Thread.sleep(3000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Test public void testTerminateDialForkCallWhileRinging_LCM_to_initial_call() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); stubFor(post(urlPathEqualTo("/completed")) .willReturn(aResponse() .withStatus(200))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String georgeCallSid = georgeCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String aliceCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); georgeCall.listenForCancel(); aliceCall.listenForCancel(); //LCM request to terminate the initial call which is in-progress JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, "completed", null); assertNotNull(callResult); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(aliceCancelTransaction); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); //Wait to cancel the other branches Thread.sleep(3000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } private String hangupRcml = "<Response><Hangup></Hangup></Response>"; @Test public void testTerminateDialForkCallWhileRinging_LCM_to_move_initial_call_to_hangup_rcml() throws Exception { stubFor(get(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialFork))); stubFor(post(urlPathEqualTo("/completed")) .willReturn(aResponse() .withStatus(200))); stubFor(post(urlPathEqualTo("/hangupRcml")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(hangupRcml))); // Register Alice SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080"); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); // Prepare Alice to receive call final SipCall aliceCall = alicePhone.createSipCall(); aliceCall.listenForIncomingCall(); // Prepare George phone to receive call final SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); Credential c = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(c); // Initiate a call using Bob final SipCall bobCall = bobPhone.createSipCall(); bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null); assertLastOperationSuccess(bobCall); assertTrue(bobCall.waitForAuthorisation(5000)); assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); final int response = bobCall.getLastReceivedResponse().getStatusCode(); assertTrue(response == Response.TRYING || response == Response.RINGING); if (response == Response.TRYING) { assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode()); } assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000)); assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode()); bobCall.sendInviteOkAck(); String callSid = bobCall.getLastReceivedResponse().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400)); assertTrue(georgeCall.waitForIncomingCall(30 * 1000)); assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "Trying-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); String georgeCallSid = georgeCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); assertTrue(aliceCall.waitForIncomingCall(30 * 1000)); assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Trying-Alice", 3600)); assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Alice", 3600)); String aliceCallSid = aliceCall.getLastReceivedRequest().getMessage().getHeader("X-RestComm-CallSid").toString().split(":")[1].trim(); georgeCall.listenForCancel(); aliceCall.listenForCancel(); //LCM request to move initial call to Hangup RCML String hangupUrl = "http://127.0.0.1:8090/hangupRcml"; JsonObject callResult = RestcommCallsTool.getInstance().modifyCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid, null, hangupUrl); assertNotNull(callResult); SipTransaction georgeCancelTransaction = georgeCall.waitForCancel(30000); SipTransaction aliceCancelTransaction = aliceCall.waitForCancel(30000); assertNotNull(aliceCancelTransaction); assertNotNull(georgeCancelTransaction); georgeCall.respondToCancel(georgeCancelTransaction, 200, "OK-2-Cancel-George", 3600); aliceCall.respondToCancel(aliceCancelTransaction, 200, "OK-2-Cancel-Alice", 3600); //Wait to cancel the other branches Thread.sleep(3000); JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertNotNull(metrics); int liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt(); logger.info("LiveCalls: "+liveCalls); int liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size(); logger.info("LiveCallsArraySize: "+liveCallsArraySize); assertEquals(0,liveCalls); assertEquals(0, liveCallsArraySize); Map<String, Integer> mgcpResources = MonitoringServiceTool.getInstance().getMgcpResources(metrics); int mgcpEndpoints = mgcpResources.get("MgcpEndpoints"); int mgcpConnections = mgcpResources.get("MgcpConnections"); assertEquals(0, mgcpEndpoints); assertEquals(0, mgcpConnections); } @Deployment(name = "LiveCallModificationTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); archive.addAsWebResource("dial-number-entry.xml"); archive.addAsWebResource("dial-client-entry.xml"); archive.addAsWebResource("hello-play.xml"); logger.info("Packaged Test App"); return archive; } }
58,553
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientPasswordMigrationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/ClientPasswordMigrationTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2018, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.restcomm.connect.testsuite.http; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.ClientResponse; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.UnstableTests; import java.net.URL; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(Arquillian.class) public class ClientPasswordMigrationTest { private final static Logger logger = Logger.getLogger(OrganizationsEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; //super admin account private String superAdminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String superAdminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private final String org1 = "OR11111111111111111111111111111111"; private final String org2 = "OR22222222222222222222222222222222"; @BeforeClass public static void beforeClass() { } @Test public void migrateClientsOrg1Test() { JsonObject clientsMigratedJsonObj = RestcommOrganizationsTool.getInstance().migrateClientsOfOrganization(deploymentUrl.toString(), superAdminAccountSid, superAdminAuthToken, org1); assertNotNull(clientsMigratedJsonObj); Gson gson = new Gson(); Map<String,String> migratedClients = new HashMap<>(); migratedClients = (Map<String,String>) gson.fromJson(clientsMigratedJsonObj, migratedClients.getClass()); assertNotNull(migratedClients); assertEquals(4, migratedClients.size()); } @Deployment(name = "OrganizationsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_client_password_migration_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
4,449
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommAPIEndpointSecurityTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/RestcommAPIEndpointSecurityTest.java
package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureExpTests; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class RestcommAPIEndpointSecurityTest { private final static Logger logger = Logger.getLogger(RestcommAPIEndpointSecurityTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static final String SUPER_ADMIN_ACCOUNT_SID = "ACae6e420f425248d6a26948c17a9e2acf"; private static final String CLOSED_ACCOUNT_SID="ACA3000000000000000000000000000000"; private static final String SUSPENDED_ACCOUNT_SID="ACA4000000000000000000000000000000"; private static final String AUTH_TOKEN = "77f8c12cc7b8f8423e5c38b035249166"; private static final String RESOURCE_SID = "PRae6e420f425248d6a26948c17a9e2acf"; private static final String GENERIC_ENDPOINT = "/2012-04-24/"; private static final String PROFILE_ENDPOINT = "/2012-04-24/Profiles"; private static final String ACCOUNT_ENDPOINT = "/2012-04-24/Accounts"; private static final String ORGANIZATION_ENDPOINT = "/2012-04-24/Organizations"; private static final String CLIENTS_ENDPOINT = "/2012-04-24/Accounts/"+SUPER_ADMIN_ACCOUNT_SID+"/Clients"; private static final String RECORDINGS_ENDPOINT_FILE_PATH = "/2012-04-24/Accounts/"+SUPER_ADMIN_ACCOUNT_SID+"/Recordings/REc267d9cdcd0f4623a54abedf8e3d8835"; private static final String RECORDINGS_ENDPOINT = "/2012-04-24/Accounts/"+SUPER_ADMIN_ACCOUNT_SID+"/Recordings"; private static final String RECORDINGS_ENDPOINT_FILE_FULL_PATH = "http://127.0.0.1:8080/restcomm/2012-04-24/Accounts/"+SUPER_ADMIN_ACCOUNT_SID+"/Recordings/REc267d9cdcd0f4623a54abedf8e3d8835"; /** * this test will try to access generic EP Without Authentication or invalid token */ @Test public void genericSecurityTest(){ assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+GENERIC_ENDPOINT)); assertEquals(401, performRequestWithInvalidToken(deploymentUrl.toString()+GENERIC_ENDPOINT)); assertEquals(403, performApiRequest(deploymentUrl.toString()+GENERIC_ENDPOINT, CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(403, performApiRequest(deploymentUrl.toString()+GENERIC_ENDPOINT, SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); } /** * this test will try to access org EP Without Authentication or invalid token */ @Test @Category(FeatureExpTests.class) public void organizationSecurityTest(){ assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+ORGANIZATION_ENDPOINT+"/"+RESOURCE_SID)); assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+ORGANIZATION_ENDPOINT)); assertEquals(401, performRequestWithInvalidToken(deploymentUrl.toString()+ORGANIZATION_ENDPOINT)); assertEquals(403, performApiRequest(deploymentUrl.toString()+ORGANIZATION_ENDPOINT, CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(403, performApiRequest(deploymentUrl.toString()+ORGANIZATION_ENDPOINT, SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); } /** * this test will try to access acc EP Without Authentication or invalid token */ @Test @Category(FeatureExpTests.class) public void accountSecurityTest(){ assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+ACCOUNT_ENDPOINT+"/"+RESOURCE_SID)); assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+ACCOUNT_ENDPOINT)); assertEquals(401, performRequestWithInvalidToken(deploymentUrl.toString()+ACCOUNT_ENDPOINT)); assertEquals(403, performApiRequest(deploymentUrl.toString()+ACCOUNT_ENDPOINT, CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(403, performApiRequest(deploymentUrl.toString()+ACCOUNT_ENDPOINT, SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); } /** * this test will try to access profile EP Without Authentication or invalid token */ @Test @Category(FeatureExpTests.class) public void profileSecurityTest(){ assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+PROFILE_ENDPOINT+"/"+RESOURCE_SID)); assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+PROFILE_ENDPOINT)); assertEquals(401, performRequestWithInvalidToken(deploymentUrl.toString()+PROFILE_ENDPOINT)); assertEquals(403, performApiRequest(deploymentUrl.toString()+PROFILE_ENDPOINT, CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(403, performApiRequest(deploymentUrl.toString()+PROFILE_ENDPOINT, SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); } /** * this test will try to access client EP Without Authentication or invalid token */ @Test @Category(FeatureExpTests.class) public void clientSecurityTest(){ assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+CLIENTS_ENDPOINT+"/"+RESOURCE_SID)); assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+CLIENTS_ENDPOINT)); assertEquals(401, performRequestWithInvalidToken(deploymentUrl.toString()+CLIENTS_ENDPOINT)); assertEquals(403, performApiRequest(deploymentUrl.toString()+CLIENTS_ENDPOINT, CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(403, performApiRequest(deploymentUrl.toString()+CLIENTS_ENDPOINT, SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); } /** * this test will try to access recording endpoint * we allow audio video file to be accessed, but recording list and single resource description is protected * we will need to change this test if https://telestax.atlassian.net/browse/RESTCOMM-1736 is implemented * @throws IOException */ @Test public void recordingSecurityTest() throws IOException{ //recording list is protected assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT)); assertEquals(401, performRequestWithInvalidToken(deploymentUrl.toString()+RECORDINGS_ENDPOINT)); assertEquals(403, performApiRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT, CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(403, performApiRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT, SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); //recording resource is protected assertEquals(401, performUnautherizedRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH)); assertEquals(401, performRequestWithInvalidToken(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH)); assertEquals(403, performApiRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH, CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(403, performApiRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH, SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); //recording audio file is not protected, we consider 404 equivalent to 200 as that means we already bypassed 401 and 403 and the fact that file does not exists assertEquals(404, performUnautherizedRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH+".wav")); assertEquals(404, performRequestWithInvalidToken(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH+".wav")); assertEquals(404, performApiRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH+".wav", CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(404, performApiRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH+".wav", SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); //recording video file is not protected, we consider 404 equivalent to 200 as that means we already bypassed 401 and 403 and the fact that file does not exists assertEquals(404, performUnautherizedRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH+".mp4")); assertEquals(404, performRequestWithInvalidToken(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH+".mp4")); assertEquals(404, performApiRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH+".mp4", CLOSED_ACCOUNT_SID, AUTH_TOKEN)); assertEquals(404, performApiRequest(deploymentUrl.toString()+RECORDINGS_ENDPOINT_FILE_PATH+".mp4", SUSPENDED_ACCOUNT_SID, AUTH_TOKEN)); //access by simple http url connection URL url = new URL(RECORDINGS_ENDPOINT_FILE_FULL_PATH+".wav"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); assertEquals(404, connection.getResponseCode()); } /** * perform api Request with account * * @param endpointUrl * @return */ private int performApiRequest(String endpointUrl, String account, String auth){ Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(CLOSED_ACCOUNT_SID, AUTH_TOKEN)); WebResource webResource = jerseyClient.resource(endpointUrl); ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(ClientResponse.class); return clientResponse.getStatus(); } /** * performUnautherizedRequest with no authentication * * @param endpointUrl * @return */ private int performUnautherizedRequest(String endpointUrl){ Client jerseyClient = Client.create(); WebResource webResource = jerseyClient.resource(endpointUrl); ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(ClientResponse.class); return clientResponse.getStatus(); } /** * perform request with Invalid Token * @param endpointUrl * @return */ private int performRequestWithInvalidToken(String endpointUrl){ Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(SUPER_ADMIN_ACCOUNT_SID, "wrongauthtoken")); WebResource webResource = jerseyClient.resource(endpointUrl); ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(ClientResponse.class); return clientResponse.getStatus(); } @Deployment(name = "RestcommAPIEndpointSecurityTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_accounts_test", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
12,232
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConferenceParticipantsEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/ConferenceParticipantsEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import static org.junit.Assert.assertTrue; import java.net.URL; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Ignore; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.restcomm.connect.commons.Version; /** * @author maria */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ConferenceParticipantsEndpointTest { private final static Logger logger = Logger.getLogger(ConferenceParticipantsEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String runningConferenceSid = "CFfb336a6d5c364a57ab365d80dc24538f"; private String completedConferenceSid = "CF1e4a2e67ada54298a83b93818c0ea1e4"; @Test public void getParticipantsListRunningConference() { JsonObject page = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, runningConferenceSid); int totalSize = page.get("total").getAsInt(); JsonArray pageCallsArray = page.get("calls").getAsJsonArray(); int pageCallsArraySize = pageCallsArray.size(); assertTrue(pageCallsArraySize == 3); assertTrue(page.get("start").getAsInt() == 0); assertTrue(page.get("end").getAsInt() == 3); assertTrue(totalSize == 3); } @Test public void getParticipantsListCompletedConference() { JsonObject page = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, completedConferenceSid); int totalSize = page.get("total").getAsInt(); JsonArray pageCallsArray = page.get("calls").getAsJsonArray(); int pageCallsArraySize = pageCallsArray.size(); assertTrue(pageCallsArraySize == 0); assertTrue(page.get("start").getAsInt() == 0); assertTrue(page.get("end").getAsInt() == 0); assertTrue(totalSize == 0); } @Test @Ignore //Pending issue https://github.com/RestComm/Restcomm-Connect/issues/1135 public void muteParticipant() { JsonObject page = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), adminAccountSid, adminAuthToken, runningConferenceSid); int totalSize = page.get("total").getAsInt(); JsonArray pageCallsArray = page.get("calls").getAsJsonArray(); int pageCallsArraySize = pageCallsArray.size(); assertTrue(pageCallsArraySize == 0); assertTrue(page.get("start").getAsInt() == 0); assertTrue(page.get("end").getAsInt() == 0); assertTrue(totalSize == 0); } @Deployment(name = "ClientsEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm_with_Data.script", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
5,357
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateCallsWithStatusCallbackTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/http/CreateCallsWithStatusCallbackTest.java
package org.restcomm.connect.testsuite.http; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.github.tomakehurst.wiremock.verification.LoggedRequest; import com.google.gson.JsonElement; import org.apache.log4j.Logger; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.UnstableTests; import org.restcomm.connect.testsuite.tools.MonitoringServiceTool; import javax.sip.message.Response; import java.net.URL; import java.util.List; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.findAll; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(FeatureAltTests.class) public class CreateCallsWithStatusCallbackTest { private final static Logger logger = Logger.getLogger(CreateCallsWithStatusCallbackTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private static SipStackTool tool1; private static SipStackTool tool2; private static SipStackTool tool3; private static SipStackTool tool4; private SipStack bobSipStack; private SipPhone bobPhone; private String bobContact = "sip:[email protected]:5090"; private SipStack georgeSipStack; private SipPhone georgePhone; private String georgeContact = "sip:[email protected]:5070"; // Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML // of the VoiceURL will be executed. private SipStack aliceSipStack; private SipPhone alicePhone; private String aliceContact = "sip:[email protected]:5091"; private SipStack alice2SipStack; private SipPhone alice2Phone; private String alice2Contact = "sip:[email protected]:5092"; @BeforeClass public static void beforeClass() throws Exception { tool1 = new SipStackTool("CreateCalls1"); tool2 = new SipStackTool("CreateCalls2"); tool3 = new SipStackTool("CreateCalls3"); tool4 = new SipStackTool("CreateCalls4"); } @Before public void before() throws Exception { bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080"); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact); georgeSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080"); georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact); aliceSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080"); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact); alice2SipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080"); alice2Phone = alice2SipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, alice2Contact); } @After public void after() throws Exception { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (georgePhone != null) { georgePhone.dispose(); } if (georgeSipStack != null) { georgeSipStack.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (alice2SipStack != null) { alice2SipStack.dispose(); } if (alice2Phone != null) { alice2Phone.dispose(); } } private String dialNumber = "<Response><Dial><Number>+131313</Number></Dial></Response>"; @Test public void createCallNumberWithStatusCallback() throws InterruptedException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumber))); stubFor(get(urlPathMatching("/status.*")) .willReturn(aResponse() .withStatus(200))); SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = "http://127.0.0.1:8090/1111"; String statusCallback = "http://127.0.0.1:8090/status"; String statusCallbackMethod = "GET"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl, statusCallback, statusCallbackMethod, null); assertNotNull(callResult); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/status.*"))); assertEquals(4, requests.size()); String requestUrl = requests.get(0).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=0")); assertTrue(requestUrl.contains("CallStatus=initiated")); requestUrl = requests.get(1).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=1")); assertTrue(requestUrl.contains("CallStatus=ringing")); requestUrl = requests.get(2).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=2")); assertTrue(requestUrl.contains("CallStatus=answered")); requestUrl = requests.get(3).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=3")); assertTrue(requestUrl.contains("CallStatus=completed")); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } private String dialNumberWithStatusCallback = "<Response><Dial><Number statusCallback=\"http://127.0.0.1:8090/statusOfDialNumber\" statusCallbackMethod=\"GET\">+131313</Number></Dial></Response>"; @Test @Category(UnstableTests.class) public void createCallNumberWithStatusCallbackInBothTheRequestAndRCML() throws InterruptedException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberWithStatusCallback))); stubFor(get(urlPathMatching("/statusOfDialBob.*")) .willReturn(aResponse() .withStatus(200))); stubFor(get(urlPathMatching("/statusOfDialNumber.*")) .willReturn(aResponse() .withStatus(200))); SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = "http://127.0.0.1:8090/1111"; String statusCallback = "http://127.0.0.1:8090/statusOfDialBob"; String statusCallbackMethod = "GET"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl, statusCallback, statusCallbackMethod, null); assertNotNull(callResult); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/statusOfDialNumber.*"))); assertEquals(4, requests.size()); List<LoggedRequest> requests2 = findAll(getRequestedFor(urlPathMatching("/statusOfDialBob.*"))); assertEquals(4, requests2.size()); } private String dialNumberWithRecording = "<Response><Dial record=\"true\"><Number statusCallback=\"http://127.0.0.1:8090/statusOfDialNumber\" statusCallbackMethod=\"GET\">+131313</Number></Dial></Response>"; @Test public void createCallNumberWithStatusCallbackAndRecording() throws InterruptedException { stubFor(post(urlPathEqualTo("/1111")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(dialNumberWithRecording))); stubFor(get(urlPathMatching("/statusOfDialNumber.*")) .willReturn(aResponse() .withStatus(200))); SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForIncomingCall(); SipCall georgeCall = georgePhone.createSipCall(); georgeCall.listenForIncomingCall(); String from = "+15126002188"; String to = bobContact; String rcmlUrl = "http://127.0.0.1:8090/1111"; // String statusCallback = "http://127.0.0.1:8090/status"; // String statusCallbackMethod = "GET"; JsonElement callResult = RestcommCallsTool.getInstance().createCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, from, to, rcmlUrl); //, statusCallback, statusCallbackMethod, null); assertNotNull(callResult); assertTrue(bobCall.waitForIncomingCall(5000)); String receivedBody = new String(bobCall.getLastReceivedRequest().getRawContent()); assertTrue(bobCall.sendIncomingCallResponse(Response.RINGING, "Ringing-Bob", 3600)); assertTrue(bobCall .sendIncomingCallResponse(Response.OK, "OK-Bob", 3600, receivedBody, "application", "sdp", null, null)); // Restcomm now should execute RCML that will create a call to +131313 (george's phone) assertTrue(georgeCall.waitForIncomingCall(5000)); receivedBody = new String(georgeCall.getLastReceivedRequest().getRawContent()); assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "Ringing-George", 3600)); assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "OK-George", 3600, receivedBody, "application", "sdp", null, null)); Thread.sleep(3000); bobCall.listenForDisconnect(); assertTrue(georgeCall.disconnect()); assertTrue(georgeCall.waitForAck(5000)); assertTrue(bobCall.waitForDisconnect(5000)); assertTrue(bobCall.respondToDisconnect()); Thread.sleep(10000); logger.info("About to check the StatusCallback Requests"); List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/statusOfDialNumber.*"))); assertEquals(4, requests.size()); String requestUrl = requests.get(0).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=0")); assertTrue(requestUrl.contains("CallStatus=initiated")); requestUrl = requests.get(1).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=1")); assertTrue(requestUrl.contains("CallStatus=ringing")); requestUrl = requests.get(2).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=2")); assertTrue(requestUrl.contains("CallStatus=answered")); requestUrl = requests.get(3).getUrl(); assertTrue(requestUrl.contains("SequenceNumber=3")); assertTrue(requestUrl.contains("CallStatus=completed")); int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken); int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken); assertTrue(liveCalls==0); assertTrue(liveIncomingCalls==0); assertTrue(liveOutgoingCalls==0); assertTrue(liveCallsArraySize==0); } @Deployment(name = "CreateCallsTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialStatusCallbackTest", "data/hsql/restcomm.script"); archive.addAsWebInfResource("akka_application.conf", "classes/application.conf"); logger.info("Packaged Test App"); return archive; } }
18,353
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmppTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/smpp/SmppTest.java
package org.restcomm.connect.testsuite.smpp; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URL; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import javax.sip.address.SipURI; import javax.sip.message.Request; import javax.sip.message.Response; import org.apache.log4j.Logger; import org.cafesip.sipunit.Credential; import org.cafesip.sipunit.SipCall; import org.cafesip.sipunit.SipPhone; import org.cafesip.sipunit.SipStack; import org.jboss.arquillian.container.mss.extension.SipStackTool; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.BrokenTests; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.WithInSecsTests; import org.restcomm.connect.dao.entities.SmsMessage; import org.restcomm.connect.sms.smpp.SmppInboundMessageEntity; import org.restcomm.connect.testsuite.sms.SmsEndpointTool; import com.cloudhopper.commons.charset.Charset; import com.cloudhopper.commons.charset.CharsetUtil; import com.cloudhopper.smpp.type.SmppChannelException; import com.cloudhopper.smpp.type.SmppInvalidArgumentException; import static com.github.tomakehurst.wiremock.client.WireMock.matching; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.client.WireMock.verify; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.List; import org.restcomm.connect.commons.annotations.ParallelClassTests; import org.restcomm.connect.testsuite.NetworkPortAssigner; import org.restcomm.connect.testsuite.WebArchiveUtil; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (George Vagenas) */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) @Category(value = {ParallelClassTests.class, WithInSecsTests.class}) public class SmppTest { private final static Logger logger = Logger.getLogger(SmppTest.class); private static final String version = Version.getVersion(); private static String to = "7777"; private static String toPureSipProviderNumber = "7007"; private static String from = "9999"; private static String msgBody = "か~!@#$%^&*()-=\u263a\u00a1\u00a2\u00a3\u00a4\u00a5Message from SMPP Server to Restcomm"; private static String msgBodyResp = "か~!@#$%^&*()-=\u263a\u00a1\u00a2\u00a3\u00a4\u00a5Response from Restcomm to SMPP server"; private static String msgBodyRespUCS2 = "か~!@#$%^&*()-=\u263a\u00a1\u00a2\u00a3\u00a4\u00a5Response from Restcomm to SMPP server"; private static int wirePort = NetworkPortAssigner.retrieveNextPortByFile(); private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile(); @Rule public WireMockRule wireMockRule = new WireMockRule(wirePort); // No-args constructor defaults to port 8080 @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; private static MockSmppServer mockSmppServer; private static SipStackTool tool2; private SipStack aliceSipStack; private SipPhone alicePhone; private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String aliceContact = "sip:[email protected]:" + alicePort; //5092; private static SipStackTool tool3; private SipStack bobSipStack; private SipPhone bobPhone; private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String bobContact = "sip:[email protected]:" + bobPort; //5093; private static SipStackTool tool5; private SipStack mariaSipStack; private SipPhone mariaPhone; private static String mariaPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String mariaContact = "sip:[email protected]:" + mariaPort;//5095 private static SipStackTool tool6; private SipStack shoaibSipStack; private SipPhone shoaibPhone; private static String shoaibPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String shoaibContact = "sip:[email protected]:" + shoaibPort; //5096 private static SipStackTool tool4; private SipStack mariaOrg3SipStack; private SipPhone mariaOrg3Phone; private static String mariaOrg3Port = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile()); private String mariaOrg3Contact = "sip:[email protected]:" + mariaOrg3Port;//5094 private static int restcommPort = 5080; private static int restcommHTTPPort = 8080; private static String restcommContact = "127.0.0.1:" + restcommPort; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; public static void reconfigurePorts() { if (System.getProperty("arquillian_sip_port") != null) { restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port")); restcommContact = "127.0.0.1:" + restcommPort; } if (System.getProperty("arquillian_http_port") != null) { restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port")); } } @BeforeClass public static void prepare() throws SmppChannelException, InterruptedException { tool2 = new SipStackTool("SmppTest2"); tool3 = new SipStackTool("SmppTest3"); tool4 = new SipStackTool("SmppTest4"); tool5 = new SipStackTool("SmppTest5"); tool6 = new SipStackTool("SmppTest6"); mockSmppServer = new MockSmppServer(); logger.info("Will wait for the SMPP link to be established"); do { Thread.sleep(1000); } while (!mockSmppServer.isLinkEstablished()); logger.info("SMPP link is now established"); } @Before public void before() throws Exception { aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact); alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact); bobSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact); bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact); mariaSipStack = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", mariaPort, restcommContact); mariaPhone = mariaSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, mariaContact); shoaibSipStack = tool6.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", shoaibPort, restcommContact); shoaibPhone = shoaibSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, shoaibContact); mariaOrg3SipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", mariaOrg3Port, restcommContact); mariaOrg3Phone = mariaOrg3SipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, mariaOrg3Contact); mockSmppServer.cleanup(); //set submit_sm_resp to Pass by default mockSmppServer.setSendFailureOnSubmitSmResponse(false); Thread.sleep(5000); } @AfterClass public static void cleanup() { if (mockSmppServer != null) { mockSmppServer.stop(); } } @After public void after() throws InterruptedException { if (bobPhone != null) { bobPhone.dispose(); } if (bobSipStack != null) { bobSipStack.dispose(); } if (alicePhone != null) { alicePhone.dispose(); } if (aliceSipStack != null) { aliceSipStack.dispose(); } if (shoaibPhone != null) { shoaibPhone.dispose(); } if (shoaibSipStack != null) { shoaibSipStack.dispose(); } if (mariaPhone != null) { mariaPhone.dispose(); } if (mariaSipStack != null) { mariaSipStack.dispose(); } if (mariaOrg3Phone != null) { mariaOrg3Phone.dispose(); } if (mariaOrg3SipStack != null) { mariaOrg3SipStack.dispose(); } Thread.sleep(2000); wireMockRule.resetRequests(); Thread.sleep(2000); } @Test public void testSendMessageToRestcommUTF8() throws SmppInvalidArgumentException, IOException, InterruptedException { testSendMessageToRestcomm(msgBody, msgBodyResp, CharsetUtil.CHARSET_UTF_8); } @Test public void testSendMessageToRestcommUCS2() throws SmppInvalidArgumentException, IOException, InterruptedException { testSendMessageToRestcomm(msgBody, msgBodyRespUCS2, CharsetUtil.CHARSET_UCS_2); } public void testSendMessageToRestcomm(String msgBodySend, String msgBodyResp, Charset charset) throws SmppInvalidArgumentException, IOException, InterruptedException { String smsEchoRcml = "<Response><Sms to=\"" + from + "\" from=\"" + to + "\">" + msgBodyResp + "</Sms></Response>"; stubFor(get(urlPathEqualTo("/smsApp")).willReturn(aResponse() .withStatus(200).withHeader("Content-Type", "text/xml") .withBody(smsEchoRcml))); mockSmppServer.sendSmppMessageToRestcomm(msgBodySend, to, from, charset); Thread.sleep(2000); assertTrue(mockSmppServer.isMessageSent()); Thread.sleep(2000); assertTrue(mockSmppServer.isMessageReceived()); SmppInboundMessageEntity inboundMessageEntity = mockSmppServer.getSmppInboundMessageEntity(); assertNotNull(inboundMessageEntity); logger.info("msgBodyResp: " + msgBodyResp); logger.info("getSmppContent: " + inboundMessageEntity.getSmppContent()); assertTrue(inboundMessageEntity.getSmppTo().equals(from)); assertTrue(inboundMessageEntity.getSmppFrom().equals(to)); assertTrue(inboundMessageEntity.getSmppContent().equals(msgBodyResp)); } private String smsEchoRcmlPureSipProviderNumber = "<Response><Sms to=\"" + from + "\" from=\"" + toPureSipProviderNumber + "\">" + msgBodyResp + "</Sms></Response>"; @Test //https://telestax.atlassian.net/browse/RESTCOMM-1428, https://telestax.atlassian.net/browse/POSTMORTEM-13 public void testSendSMPPMessageToRestcommPureSipProviderNumber() throws SmppInvalidArgumentException, IOException, InterruptedException { stubFor(get(urlPathEqualTo("/smsApp")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(smsEchoRcmlPureSipProviderNumber))); mockSmppServer.sendSmppMessageToRestcomm(msgBody, toPureSipProviderNumber, from, CharsetUtil.CHARSET_GSM); Thread.sleep(2000); assertTrue(mockSmppServer.isMessageSent()); Thread.sleep(2000); assertTrue(mockSmppServer.isMessageReceived()); SmppInboundMessageEntity inboundMessageEntity = mockSmppServer.getSmppInboundMessageEntity(); assertNotNull(inboundMessageEntity); assertTrue(inboundMessageEntity.getSmppTo().equals(from)); assertTrue(inboundMessageEntity.getSmppFrom().equals(toPureSipProviderNumber)); assertTrue(inboundMessageEntity.getSmppContent().equals(msgBodyResp)); } private String dlrBody ="testSendSMPPMessageAndGetDeliveryReceipt"; private String callbackURL = "http://127.0.0.1:" + wirePort + "/statusCallback"; private String smsActionAtt = "<Response><Sms action= \"" + callbackURL + "\" to=\"" + from + "\" from=\"" + to + "\">" + dlrBody + "</Sms></Response>"; @Test public void testSendSMPPMessageAndGetDeliveryReceipt() throws SmppInvalidArgumentException, IOException, InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/smsApp")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(smsActionAtt))); stubFor(post(urlPathEqualTo("/statusCallback")) .willReturn(aResponse() .withStatus(200))); final String from = "alice"; // Send out SMS using SMPP final String body = "Test Message from Alice. " + System.currentTimeMillis(); SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, from, "1234", aliceContact, 3600, 3600)); Credential aliceCred = new Credential("127.0.0.1", from, "1234"); alicePhone.addUpdateCredential(aliceCred); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.initiateOutgoingMessage("sip:" + to + "@" + restcommContact, null, body); aliceCall.waitForAuthorisation(8000); Thread.sleep(5000); SmppInboundMessageEntity inboundMessageEntity = mockSmppServer.getSmppInboundMessageEntity(); assertNotNull(inboundMessageEntity); final String smppMessageId = mockSmppServer.getSmppMessageId(); // Verify SMS CDR Map<String, String> filters = new HashMap<String, String>(); filters.put("Body", dlrBody); JsonObject smsCdrResult = SmsEndpointTool.getInstance().getSmsMessageListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertNotNull(smsCdrResult); JsonElement msgs = smsCdrResult.get("messages"); JsonObject smsCDR = msgs.getAsJsonArray().get(0).getAsJsonObject(); assertNotNull(smsCDR); final String sid = smsCDR.get("sid").getAsString(); String status = smsCDR.get("status").getAsString(); String actualFrom = smsCDR.get("from").getAsString(); assertEquals(SmsMessage.Status.SENT.toString(), status); assertEquals(to, actualFrom); verify(postRequestedFor(urlMatching("/statusCallback")) .withRequestBody(matching(".*sent.*")) ); // Ask SMPP mock server to Send DLR to RC mockSmppServer.sendSmppDeliveryMessageToRestcomm(smppMessageId, MockSmppServer.SmppDeliveryStatus.DELIVRD); Thread.sleep(5000); // ReCheck CDR to make sure we get updated status smsCDR = SmsEndpointTool.getInstance().getSmsMessage(deploymentUrl.toString(), adminAccountSid, adminAuthToken, sid); assertNotNull(smsCdrResult); status = smsCDR.get("status").getAsString(); assertEquals(SmsMessage.Status.DELIVERED.toString(), status); verify(postRequestedFor(urlMatching("/statusCallback")) .withRequestBody(matching(".*delivered.*")) ); } @Test @Category(value = {FeatureExpTests.class}) public void testSendSMPPMessageViaAPIAndGetDeliveryReceipt() throws SmppInvalidArgumentException, IOException, InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/smsApp")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(smsEchoRcmlPureSipProviderNumber))); stubFor(post(urlPathEqualTo("/statusCallback")) .willReturn(aResponse() .withStatus(200))); final String from = "alice"; final String to = "9999"; // pstn (not a RC number) // Send out SMS using SMPP via rest api final String body = "Test Message from Alice. " + System.currentTimeMillis(); HashMap<String, String> statusCallback = new HashMap(); String callbackURL = "http://127.0.0.1:" + wireMockRule.port() + "/statusCallback"; statusCallback.put("StatusCallback", callbackURL); SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "alice", "9999", body, statusCallback); Thread.sleep(5000); SmppInboundMessageEntity inboundMessageEntity = mockSmppServer.getSmppInboundMessageEntity(); assertNotNull(inboundMessageEntity); assertTrue(inboundMessageEntity.getSmppTo().equals(to)); assertTrue(inboundMessageEntity.getSmppFrom().equals(from)); assertTrue(inboundMessageEntity.getSmppContent().equals(body)); final String smppMessageId = mockSmppServer.getSmppMessageId(); // Verify SMS CDR Map<String, String> filters = new HashMap<String, String>(); filters.put("From", from); filters.put("To", to); filters.put("Body", body); JsonObject smsCdrResult = SmsEndpointTool.getInstance().getSmsMessageListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertNotNull(smsCdrResult); JsonElement msgs = smsCdrResult.get("messages"); JsonObject smsCDR = msgs.getAsJsonArray().get(0).getAsJsonObject(); assertNotNull(smsCDR); final String sid = smsCDR.get("sid").getAsString(); String status = smsCDR.get("status").getAsString(); String actualFrom = smsCDR.get("from").getAsString(); String actualTo = smsCDR.get("to").getAsString(); assertEquals(SmsMessage.Status.SENT.toString(), status); assertEquals("alice", actualFrom); assertEquals("9999", actualTo); verify(postRequestedFor(urlMatching("/statusCallback")) .withRequestBody(matching(".*sent.*")) ); // Ask SMPP mock server to Send DLR to RC mockSmppServer.sendSmppDeliveryMessageToRestcomm(smppMessageId, MockSmppServer.SmppDeliveryStatus.DELIVRD); Thread.sleep(5000); // ReCheck CDR to make sure we get updated status smsCDR = SmsEndpointTool.getInstance().getSmsMessage(deploymentUrl.toString(), adminAccountSid, adminAuthToken, sid); assertNotNull(smsCdrResult); status = smsCDR.get("status").getAsString(); assertEquals(SmsMessage.Status.DELIVERED.toString(), status); verify(postRequestedFor(urlMatching("/statusCallback")) .withRequestBody(matching(".*delivered.*")) ); } private String smsEchoRcmlUCS2 = "<Response><Sms to=\"" + from + "\" from=\"" + to + "\">" + msgBodyRespUCS2 + "</Sms></Response>"; @Test @Category(value = {FeatureAltTests.class, BrokenTests.class}) public void testSendMessageToRestcommUCS2_2() throws SmppInvalidArgumentException, IOException, InterruptedException { stubFor(get(urlPathEqualTo("/smsApp")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(smsEchoRcmlUCS2))); mockSmppServer.sendSmppMessageToRestcomm(msgBody, to, from, CharsetUtil.CHARSET_UCS_2); Thread.sleep(2000); assertTrue(mockSmppServer.isMessageSent()); Thread.sleep(8000); assertTrue(mockSmppServer.isMessageReceived()); SmppInboundMessageEntity inboundMessageEntity = mockSmppServer.getSmppInboundMessageEntity(); assertNotNull(inboundMessageEntity); assertTrue(inboundMessageEntity.getSmppTo().equals(from)); assertTrue(inboundMessageEntity.getSmppFrom().equals(to)); logger.info("msgBodyResp: " + msgBodyRespUCS2); logger.info("getSmppContent: " + inboundMessageEntity.getSmppContent()); assertTrue(inboundMessageEntity.getSmppContent().equals(msgBodyRespUCS2)); } @Test @Category(value = {FeatureAltTests.class}) public void testClientSentToOtherClient() throws ParseException { SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Credential aliceCred = new Credential("127.0.0.1", "alice", "1234"); alicePhone.addUpdateCredential(aliceCred); assertTrue(bobPhone.register(uri, "bob", "1234", bobContact, 3600, 3600)); Credential bobCread = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(bobCread); SipCall bobCall = bobPhone.createSipCall(); bobCall.listenForMessage(); SipCall aliceCall = alicePhone.createSipCall(); assertTrue(aliceCall.initiateOutgoingMessage("sip:bob@" + restcommContact, null, "Test Message from Alice")); assertTrue(aliceCall.waitForAuthorisation(5000)); assertTrue(aliceCall.waitOutgoingMessageResponse(5000)); assertTrue(bobCall.waitForMessage(5000)); Request msgReceived = bobCall.getLastReceivedMessageRequest(); assertTrue(new String(msgReceived.getRawContent()).equals("Test Message from Alice")); } @Test public void testClientSentOutUsingSMPP() throws ParseException, InterruptedException { SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Credential aliceCred = new Credential("127.0.0.1", "alice", "1234"); alicePhone.addUpdateCredential(aliceCred); assertTrue(bobPhone.register(uri, "bob", "1234", bobContact, 3600, 3600)); Credential bobCread = new Credential("127.0.0.1", "bob", "1234"); bobPhone.addUpdateCredential(bobCread); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.initiateOutgoingMessage("sip:9999@" + restcommContact, null, "Test Message from Alice"); aliceCall.waitForAuthorisation(8000); Thread.sleep(5000); assertTrue(mockSmppServer.isMessageReceived()); SmppInboundMessageEntity inboundMessageEntity = mockSmppServer.getSmppInboundMessageEntity(); assertNotNull(inboundMessageEntity); assertTrue(inboundMessageEntity.getSmppTo().equals("9999")); assertTrue(inboundMessageEntity.getSmppFrom().equals("alice")); assertTrue(inboundMessageEntity.getSmppContent().equals("Test Message from Alice")); } @Test @Ignore public void testClientSentOutUsingSMPPDeliveryReceipt() throws ParseException, InterruptedException { final String msg = "Test Message from Alice with Delivery Receipt"; SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600)); Credential aliceCred = new Credential("127.0.0.1", "alice", "1234"); alicePhone.addUpdateCredential(aliceCred); SipCall aliceCall = alicePhone.createSipCall(); aliceCall.initiateOutgoingMessage("sip:9999@" + restcommContact, null, msg); aliceCall.waitForAuthorisation(8000); Thread.sleep(5000); assertTrue(mockSmppServer.isMessageReceived()); SmppInboundMessageEntity inboundMessageEntity = mockSmppServer.getSmppInboundMessageEntity(); assertNotNull(inboundMessageEntity); assertTrue(inboundMessageEntity.getSmppTo().equals("9999")); assertTrue(inboundMessageEntity.getSmppFrom().equals("alice")); assertTrue(inboundMessageEntity.getSmppContent().equals(msg)); assertTrue(inboundMessageEntity.getIsDeliveryReceipt()); } @Test @Category(value = {FeatureExpTests.class}) public void testClientSentToOtherClientDifferentOrganization() throws ParseException { SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", "qwerty1234RT", "sip:[email protected]:" + mariaPort, 3600, 3600)); Credential mariaCred = new Credential("org2.restcomm.com", "maria", "qwerty1234RT"); mariaPhone.addUpdateCredential(mariaCred); assertTrue(mariaOrg3Phone.register(uri, "maria", "1234", "sip:[email protected]:" + mariaOrg3Port, 3600, 3600)); Credential mariaOrg3Cread = new Credential("org3.restcomm.com", "maria", "1234"); mariaOrg3Phone.addUpdateCredential(mariaOrg3Cread); SipCall mariaOrg3Call = mariaOrg3Phone.createSipCall(); mariaOrg3Call.listenForMessage(); SipCall mariaCall = mariaPhone.createSipCall(); assertTrue(mariaCall.initiateOutgoingMessage(mariaOrg3Contact, null, "Test Message from maria")); assertTrue(mariaCall.waitForAuthorisation(5000)); assertTrue(mariaCall.waitOutgoingMessageResponse(5000)); int responseMariaCall = mariaCall.getLastReceivedResponse().getStatusCode(); logger.info("responseMariaCall: " + responseMariaCall); assertEquals(Response.NOT_FOUND, responseMariaCall); } @Test public void testClientSentToOtherClientSameOrganization() throws ParseException { SipURI uri = mariaSipStack.getAddressFactory().createSipURI(null, restcommContact); assertTrue(mariaPhone.register(uri, "maria", "qwerty1234RT", "sip:[email protected]:" + mariaPort, 3600, 3600)); Credential mariaCred = new Credential("org2.restcomm.com", "maria", "qwerty1234RT"); mariaPhone.addUpdateCredential(mariaCred); assertTrue(shoaibPhone.register(uri, "shoaib", "qwerty1234RT", "sip:[email protected]:" + shoaibPort, 3600, 3600)); Credential shoaibCread = new Credential("org2.restcomm.com", "shoaib", "qwerty1234RT"); shoaibPhone.addUpdateCredential(shoaibCread); SipCall shoaibCall = shoaibPhone.createSipCall(); shoaibCall.listenForMessage(); SipCall mariaCall = mariaPhone.createSipCall(); assertTrue(mariaCall.initiateOutgoingMessage(shoaibContact, null, "Test Message from maria")); assertTrue(mariaCall.waitForAuthorisation(5000)); assertTrue(mariaCall.waitOutgoingMessageResponse(5000)); assertTrue(shoaibCall.waitForMessage(5000)); Request msgReceived = shoaibCall.getLastReceivedMessageRequest(); assertTrue(new String(msgReceived.getRawContent()).equals("Test Message from maria")); } @Test @Category(value = {FeatureExpTests.class}) public void testSendSMPPMessageWithFailedStatus() throws SmppInvalidArgumentException, IOException, InterruptedException, ParseException { stubFor(get(urlPathEqualTo("/smsApp")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(smsEchoRcmlPureSipProviderNumber))); stubFor(post(urlPathEqualTo("/statusCallback")) .willReturn(aResponse() .withStatus(200))); //set submit_sm_resp to Failed mockSmppServer.setSendFailureOnSubmitSmResponse(true); HashMap<String, String> statusCallback = new HashMap(); String callbackURL = "http://127.0.0.1:" + wireMockRule.port() + "/statusCallback"; statusCallback.put("StatusCallback", callbackURL); final String from = "alice"; final String to = "9999"; // pstn (not a RC number) // Send out SMS using SMPP via rest api final String body = "Test Message from Alice. " + System.currentTimeMillis(); SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid, adminAuthToken, "alice", "9999", body, statusCallback); Thread.sleep(5000); SmppInboundMessageEntity inboundMessageEntity = mockSmppServer.getSmppInboundMessageEntity(); assertNotNull(inboundMessageEntity); assertTrue(inboundMessageEntity.getSmppTo().equals(to)); assertTrue(inboundMessageEntity.getSmppFrom().equals(from)); assertTrue(inboundMessageEntity.getSmppContent().equals(body)); final String smppMessageId = mockSmppServer.getSmppMessageId(); // Verify SMS CDR Map<String, String> filters = new HashMap<String, String>(); filters.put("From", from); filters.put("To", to); filters.put("Body", body); JsonObject smsCdrResult = SmsEndpointTool.getInstance().getSmsMessageListUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); assertNotNull(smsCdrResult); JsonElement msgs = smsCdrResult.get("messages"); JsonObject smsCDR = msgs.getAsJsonArray().get(0).getAsJsonObject(); assertNotNull(smsCDR); final String sid = smsCDR.get("sid").getAsString(); String status = smsCDR.get("status").getAsString(); String actualFrom = smsCDR.get("from").getAsString(); String actualTo = smsCDR.get("to").getAsString(); assertEquals(SmsMessage.Status.FAILED.toString(), status); assertEquals("alice", actualFrom); assertEquals("9999", actualTo); verify(postRequestedFor(urlMatching("/statusCallback")) .withRequestBody(matching(".*failed.*")) ); } @Deployment(name = "SmppTests", managed = true, testable = false) public static WebArchive createWebArchive() { logger.info("Packaging Test App"); reconfigurePorts(); Map<String, String> webInfResources = new HashMap(); webInfResources.put("restcomm-smpp.xml", "conf/restcomm.xml"); webInfResources.put("restcomm.script-smpp", "data/hsql/restcomm.script"); webInfResources.put("sip.xml", "sip.xml"); webInfResources.put("web.xml", "web.xml"); webInfResources.put("akka_application.conf", "classes/application.conf"); Map<String, String> replacements = new HashMap(); //replace mediaport 2727 replacements.put("2727", String.valueOf(mediaPort)); replacements.put("8080", String.valueOf(restcommHTTPPort)); replacements.put("8090", String.valueOf(wirePort)); replacements.put("5080", String.valueOf(restcommPort)); replacements.put("5092", String.valueOf(alicePort)); replacements.put("5093", String.valueOf(bobPort)); replacements.put("5094", String.valueOf(mariaOrg3Port)); replacements.put("5095", String.valueOf(mariaPort)); replacements.put("5096", String.valueOf(shoaibPort)); List<String> resources = new ArrayList(); return WebArchiveUtil.createWebArchiveNoGw(webInfResources, resources, replacements); } }
31,905
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ActorSupervisorStrategyTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/faultTolerance/ActorSupervisorStrategyTest.java
package org.restcomm.connect.testsuite.faultTolerance; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; import akka.util.Timeout; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; import java.util.concurrent.TimeUnit; import static akka.pattern.Patterns.ask; import static org.junit.Assert.assertTrue; /** * @author [email protected] (Oleg Agafonov) */ public class ActorSupervisorStrategyTest { static ActorSystem system; @BeforeClass public static void setup() { Config config = ConfigFactory.load("akka_fault_tolerance_application.conf"); system = ActorSystem.create("test", config); } @AfterClass public static void teardown() { system.shutdown(); } @Test public void parentActorThrowsExceptionTest() throws Exception { new JavaTestKit(system) {{ final ActorRef parent = system.actorOf(new Props(Parent.class)); parent.tell("check exception", getRef()); expectMsgEquals(duration("1 second"), false); parent.tell("throw exception", getRef()); Thread.sleep(5000); parent.tell("check exception", getRef()); expectMsgEquals(duration("1 second"), true); }}; } @Test public void childActorThrowsExceptionTest() throws Exception { new JavaTestKit(system) {{ final ActorRef parent = system.actorOf(new Props(Parent.class)); final Future<Object> future = ask(parent, "create child", new Timeout(Duration.create(5, TimeUnit.SECONDS))); final ActorRef child = (ActorRef) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); child.tell("check exception", getRef()); expectMsgEquals(duration("1 second"), false); child.tell("throw exception", getRef()); Thread.sleep(5000); child.tell("check exception", getRef()); expectMsgEquals(duration("1 second"), true); system.stop(parent); Thread.sleep(500); assertTrue(parent.isTerminated()); assertTrue(child.isTerminated()); }}; } public static class Parent extends RestcommUntypedActor { private boolean receivedThrowException; @SuppressWarnings("Duplicates") @Override public void onReceive(Object message) throws Exception { if ("create child".equals(message)) { ActorRef child = getContext().actorOf(new Props(Child.class)); sender().tell(child, self()); } else if ("throw exception".equals(message)) { this.receivedThrowException = true; throw new RuntimeException(); } else if ("check exception".equals(message)) { sender().tell(receivedThrowException, self()); } } } public static class Child extends RestcommUntypedActor { private boolean receivedThrowException; @SuppressWarnings("Duplicates") @Override public void onReceive(Object message) throws Exception { if ("throw exception".equals(message)) { this.receivedThrowException = true; throw new RuntimeException(); } else if ("check exception".equals(message)) { sender().tell(receivedThrowException, self()); } } } }
3,837
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z