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
Verbs.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/Verbs.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.interpreter.rcml; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (George Vagenas) */ @Immutable public final class Verbs { public static final String dial = "Dial"; public static final String enqueue = "Enqueue"; public static final String fax = "Fax"; public static final String gather = "Gather"; public static final String hangup = "Hangup"; public static final String leave = "Leave"; public static final String pause = "Pause"; public static final String play = "Play"; public static final String record = "Record"; public static final String redirect = "Redirect"; public static final String reject = "Reject"; public static final String say = "Say"; public static final String sms = "Sms"; public static final String email = "Email"; //USSD verbs public static final String ussdLanguage = "Language"; public static final String ussdMessage = "UssdMessage"; public static final String ussdCollect = "UssdCollect"; public Verbs() { super(); } public static boolean isVerb(final Tag tag) { final String name = tag.name(); if (dial.equals(name)) return true; if (enqueue.equals(name)) return true; if (fax.equals(name)) return true; if (gather.equals(name)) return true; if (hangup.equals(name)) return true; if (leave.equals(name)) return true; if (pause.equals(name)) return true; if (play.equals(name)) return true; if (record.equals(name)) return true; if (redirect.equals(name)) return true; if (reject.equals(name)) return true; if (say.equals(name)) return true; if (sms.equals(name)) return true; if (ussdLanguage.equals(name)) return true; if (ussdMessage.equals(name)) return true; if (ussdCollect.equals(name)) return true; return email.equals(name); } /** * if 200 ok delay is enabled we need to answer only the calls * which are having any further call enabler verbs in their RCML. * @return */ public static boolean isThisVerbCallEnabler(Tag verb){ if(Verbs.play.equals(verb.name()) || Verbs.say.equals(verb.name()) || Verbs.gather.equals(verb.name()) || Verbs.record.equals(verb.name()) || Verbs.redirect.equals(verb.name())) return true; return false; } }
3,526
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Tag.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/Tag.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.interpreter.rcml; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public class Tag { private final Map<String, Attribute> attributes; private final List<Tag> children; private final String name; private final Tag parent; private final String text; private final boolean iterable; private Tag(final String name, final Tag parent, final String text, final Map<String, Attribute> attributes, final List<Tag> children, final boolean iterable) { super(); this.attributes = attributes; this.children = children; this.name = name; this.parent = parent; this.text = text; this.iterable = iterable; } public static Builder builder() { return new Builder(); } public Attribute attribute(final String name) { return attributes.get(name); } public List<Attribute> attributes() { return new ArrayList<Attribute>(attributes.values()); } public List<Tag> children() { return children; } public boolean isIterable() { return iterable; } public boolean hasAttribute(final String name) { return attributes.containsKey(name); } public boolean hasAttributes() { return attributes.isEmpty() ? false : true; } public boolean hasChildren() { return children.isEmpty() ? false : true; } public Iterator<Tag> iterator() { return new TagIterator(this); } public String name() { return name; } public Tag parent() { return parent; } public String text() { return text; } @Override public final String toString() { return TagPrinter.print(this); } public static final class Builder { private final Map<String, Attribute> attributes; private final List<Tag> children; private String name; private Tag parent; private String text; private boolean iterable; private Builder() { super(); attributes = new HashMap<String, Attribute>(); children = new ArrayList<Tag>(); name = null; parent = null; text = null; iterable = false; } public void addAttribute(final Attribute attribute) { attributes.put(attribute.name(), attribute); } public void addChild(final Tag child) { children.add(child); } public Tag build() { return new Tag(name, parent, text, attributes, children, iterable); } public void setIterable(final boolean iterable) { this.iterable = iterable; } public void setName(final String name) { this.name = name; } public void setParent(final Tag parent) { this.parent = parent; } public void setText(final String text) { this.text = text; } } }
4,075
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmsVerb.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/SmsVerb.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.interpreter.rcml; import java.net.URI; import org.restcomm.connect.dao.entities.SmsMessage; public class SmsVerb { public static String ACTION_ATT = "action"; public static String TO_ATT = "to"; public static String FROM_ATT = "from"; public static String METHOD_ATT = "method"; public static void populateAttributes(Tag verb, SmsMessage.Builder builder) { if (verb.hasAttribute(SmsVerb.ACTION_ATT)) { final URI callback = URI.create(verb.attribute(SmsVerb.ACTION_ATT).value()); builder.setStatusCallback(callback); if (verb.hasAttribute(SmsVerb.METHOD_ATT)){ builder.setStatusCallbackMethod(verb.attribute(SmsVerb.METHOD_ATT).value()); } } } }
1,594
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GatherAttributes.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/domain/GatherAttributes.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.interpreter.rcml.domain; /** * Library class with all Gather attributes names. * * @author Dmitriy Nadolenko */ public class GatherAttributes { public static final String ATTRIBUTE_INPUT = "input"; public static final String ATTRIBUTE_ACTION = "action"; public static final String ATTRIBUTE_METHOD = "method"; public static final String ATTRIBUTE_FINISH_ON_KEY = "finishOnKey"; public static final String ATTRIBUTE_START_INPUT_KEY = "startInputKey"; public static final String ATTRIBUTE_NUM_DIGITS = "numDigits"; public static final String ATTRIBUTE_TIME_OUT = "timeout"; public static final String ATTRIBUTE_PARTIAL_RESULT_CALLBACK = "partialResultCallback"; public static final String ATTRIBUTE_PARTIAL_RESULT_CALLBACK_METHOD = "partialResultCallbackMethod"; public static final String ATTRIBUTE_LANGUAGE = "language"; public static final String ATTRIBUTE_HINTS = "hints"; }
1,769
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PlayRecordTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/test/java/org/restcomm/connect/mgcp/PlayRecordTest.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.mgcp; import static org.junit.Assert.assertTrue; import java.net.URI; import org.junit.Ignore; import org.junit.Test; /** * @author [email protected] (Thomas Quintana) */ public final class PlayRecordTest { public PlayRecordTest() { super(); } @Ignore @Test public void testFormatting() { // We will used the builder pattern to create this message. final PlayRecord.Builder builder = PlayRecord.builder(); builder.addPrompt(URI.create("hello.wav")); builder.setRecordingId(URI.create("recording.wav")); builder.setClearDigitBuffer(true); builder.setPreSpeechTimer(1000); builder.setPostSpeechTimer(1000); builder.setRecordingLength(1500); builder.setEndInputKey("#"); final PlayRecord playRecord = builder.build(); final String result = playRecord.toString(); System.out.println(result); assertTrue("ip=hello.wav ri=recording.wav cb=true prt=10 pst=10 rlt=150 eik=#".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } @Test public void testFormattingDefaults() { // We will used the builder pattern to create this message. final PlayRecord.Builder builder = PlayRecord.builder(); builder.addPrompt(URI.create("hello.wav")); builder.setRecordingId(URI.create("recording.wav")); final PlayRecord playRecord = builder.build(); final String result = playRecord.toString(); assertTrue("ip=hello.wav ri=recording.wav".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } @Ignore @Test public void testFormattingWithNoPrompts() { // We will used the builder pattern to create this message. final PlayRecord.Builder builder = PlayRecord.builder(); builder.setRecordingId(URI.create("recording.wav")); builder.setClearDigitBuffer(true); builder.setPreSpeechTimer(1000); builder.setPostSpeechTimer(1000); builder.setRecordingLength(1500); builder.setEndInputKey("#"); final PlayRecord playRecord = builder.build(); final String result = playRecord.toString(); assertTrue("ri=recording.wav cb=true prt=10 pst=10 rlt=150 eik=#".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } @Ignore @Test public void testFormattingWithMultiplePrompts() { // We will used the builder pattern to create this message. final PlayRecord.Builder builder = PlayRecord.builder(); builder.addPrompt(URI.create("hello.wav")); builder.addPrompt(URI.create("world.wav")); builder.setRecordingId(URI.create("recording.wav")); builder.setClearDigitBuffer(true); builder.setPreSpeechTimer(1000); builder.setPostSpeechTimer(1050); builder.setRecordingLength(1500); builder.setEndInputKey("#"); final PlayRecord playRecord = builder.build(); final String result = playRecord.toString(); assertTrue("ip=hello.wav;world.wav ri=recording.wav cb=true prt=10 pst=11 rlt=150 eik=#".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } }
4,115
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AbstractMockMediaGateway.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/test/java/org/restcomm/connect/mgcp/AbstractMockMediaGateway.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.mgcp; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import jain.protocol.ip.mgcp.JainMgcpCommandEvent; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.util.RevolvingCounter; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ public abstract class AbstractMockMediaGateway extends RestcommUntypedActor { // Call agent. protected NotifiedEntity agent; // Media gateway domain name. protected final String domain; // Timeout period to wait for a response from the media gateway. protected final long timeout; // Runtime stuff. protected RevolvingCounter requestIdPool; protected RevolvingCounter sessionIdPool; protected RevolvingCounter transactionIdPool; public AbstractMockMediaGateway() { super(); agent = new NotifiedEntity("restcomm", "192.168.1.1", 2427); domain = "192.168.1.1:2427"; timeout = 500; requestIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); sessionIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); transactionIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); } private ActorRef getConnection(final Object message) { final CreateConnection request = (CreateConnection) message; final ActorRef gateway = self(); final MediaSession session = request.session(); return getContext().actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Connection(gateway, session, agent, timeout); } })); } private ActorRef getLink(final Object message) { final CreateLink request = (CreateLink) message; final ActorRef gateway = self(); final MediaSession session = request.session(); return getContext().actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Link(gateway, session, agent, timeout); } })); } private ActorRef getBridgeEndpoint(final Object message) { final CreateBridgeEndpoint request = (CreateBridgeEndpoint) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final String endpointName = request.endpointName(); return getContext().actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new BridgeEndpoint(gateway, session, agent, domain, timeout, endpointName); } })); } private ActorRef getConferenceEndpoint(final Object message) { final CreateConferenceEndpoint request = (CreateConferenceEndpoint) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final String endpointName = request.endpointName(); return getContext().actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new ConferenceEndpoint(gateway, session, agent, domain, timeout, endpointName); } })); } private ActorRef getIvrEndpoint(final Object message) { final CreateIvrEndpoint request = (CreateIvrEndpoint) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final String endpointName = request.endpointName(); return getContext().actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new IvrEndpoint(gateway, session, agent, domain, timeout, endpointName); } })); } private ActorRef getPacketRelayEndpoint(final Object message) { final CreatePacketRelayEndpoint request = (CreatePacketRelayEndpoint) message; final ActorRef gateway = self(); final MediaSession session = request.session(); return getContext().actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new PacketRelayEndpoint(gateway, session, agent, domain, timeout); } })); } private MediaSession getSession() { return new MediaSession((int) sessionIdPool.get()); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (CreateConnection.class.equals(klass)) { sender.tell(new MediaGatewayResponse<ActorRef>(getConnection(message)), self); } else if (CreateLink.class.equals(klass)) { sender.tell(new MediaGatewayResponse<ActorRef>(getLink(message)), self); } else if (CreateMediaSession.class.equals(klass)) { sender.tell(new MediaGatewayResponse<MediaSession>(getSession()), self); } else if (CreateBridgeEndpoint.class.equals(klass)) { final ActorRef endpoint = getBridgeEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreatePacketRelayEndpoint.class.equals(klass)) { final ActorRef endpoint = getPacketRelayEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreateIvrEndpoint.class.equals(klass)) { final ActorRef endpoint = getIvrEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreateConferenceEndpoint.class.equals(klass)) { final ActorRef endpoint = getConferenceEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (message instanceof JainMgcpCommandEvent) { request(message, sender); } else if (message instanceof JainMgcpResponseEvent) { response(message, sender); } else { throw new IllegalArgumentException("Unsupported operation !!!"); } } private void request(final Object message, final ActorRef sender) { final JainMgcpCommandEvent command = (JainMgcpCommandEvent) message; final int transactionId = (int) transactionIdPool.get(); command.setTransactionHandle(transactionId); if (NotificationRequest.class.equals(command.getClass())) { final NotificationRequest request = (NotificationRequest) command; final String id = Long.toString(requestIdPool.get()); request.getRequestIdentifier().setRequestIdentifier(id); } event(message, sender); } private void response(final Object message, final ActorRef sender) { event(message, sender); } protected abstract void event(Object message, final ActorRef sender); }
8,630
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IvrAsrEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/test/java/org/restcomm/connect/mgcp/IvrAsrEndpointTest.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.mgcp; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.Collections; import org.apache.commons.codec.binary.Hex; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUPackage; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.NotificationRequestResponse; import jain.protocol.ip.mgcp.message.Notify; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import jain.protocol.ip.mgcp.pkg.MgcpEvent; /** * @author Dmitriy Nadolenko * @version 1.0 * @since 1.0 */ public class IvrAsrEndpointTest { private static final String ASR_RESULT_TEXT = "Super_text"; private static final String ASR_RESULT_TEXT_HEX = Hex.encodeHexString(ASR_RESULT_TEXT.getBytes()); private static final String HINTS = "hint 1, hint 2"; private static ActorSystem system; public IvrAsrEndpointTest() { super(); } @BeforeClass public static void before() throws Exception { system = ActorSystem.create(); } @AfterClass public static void after() throws Exception { system.shutdown(); } @Test @SuppressWarnings("unchecked") public void testSuccessfulAsrScenario() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(IvrAsrEndpointTest.MockAsrMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an IVR end point. gateway.tell(new CreateIvrEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Start observing events from the IVR end point. endpoint.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); AsrSignal asr = new AsrSignal("no_name_driver", "en-US", Collections.singletonList(URI.create("hello.wav")), "#", 10, 10, 10, HINTS, "dtmf_speech", 1, true); endpoint.tell(asr, observer); final IvrEndpointResponse ivrResponse = expectMsgClass(IvrEndpointResponse.class); assertTrue(ivrResponse.succeeded()); CollectedResult collectedResult = (CollectedResult)ivrResponse.get(); assertTrue(ASR_RESULT_TEXT.equals(collectedResult.getResult())); assertTrue(collectedResult.isAsr()); final IvrEndpointResponse ivrResponse2 = expectMsgClass(IvrEndpointResponse.class); assertTrue(ivrResponse2.succeeded()); collectedResult = (CollectedResult)ivrResponse2.get(); assertTrue(ASR_RESULT_TEXT.equals(collectedResult.getResult())); assertTrue(collectedResult.isAsr()); final IvrEndpointResponse ivrResponse3 = expectMsgClass(IvrEndpointResponse.class); collectedResult = (CollectedResult)ivrResponse3.get(); assertTrue(ivrResponse3.succeeded()); assertTrue(ASR_RESULT_TEXT.equals(collectedResult.getResult())); assertTrue(collectedResult.isAsr()); // Stop observing events from the IVR end point. endpoint.tell(new StopObserving(observer), observer); } }; } @Test @SuppressWarnings("unchecked") public void testFailureScenario() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(IvrAsrEndpointTest.FailingMockAsrMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an IVR end point. gateway.tell(new CreateIvrEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Start observing events from the IVR end point. endpoint.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); AsrSignal asr = new AsrSignal("no_name_driver", "en-US", Collections.singletonList(URI.create("hello.wav")), "#", 10, 10, 10, HINTS, "dtmf_speech", 1, true); endpoint.tell(asr, observer); final IvrEndpointResponse ivrResponse = expectMsgClass(IvrEndpointResponse.class); assertFalse(ivrResponse.succeeded()); String errorMessage = "jain.protocol.ip.mgcp.JainIPMgcpException: The IVR request failed with the following error code 300"; assertTrue(ivrResponse.cause().toString().equals(errorMessage)); assertTrue(ivrResponse.get() == null); } }; } @Test @SuppressWarnings("unchecked") public void testEndSignal() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockAsrWithEndSignal.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an IVR end point. gateway.tell(new CreateIvrEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Start observing events from the IVR end point. endpoint.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); AsrSignal asr = new AsrSignal("no_name_driver", "en-US", Collections.singletonList(URI.create("hello.wav")), "#", 10, 10, 10, ASR_RESULT_TEXT, "dtmf_speech", 1, true); endpoint.tell(asr, observer); final IvrEndpointResponse ivrResponse = expectMsgClass(IvrEndpointResponse.class); assertTrue(ivrResponse.succeeded()); CollectedResult collectedResult = (CollectedResult)ivrResponse.get(); assertTrue(ASR_RESULT_TEXT.equals(collectedResult.getResult())); assertTrue(collectedResult.isAsr()); // EndSignal to IVR endpoint.tell(new StopEndpoint(AsrSignal.REQUEST_ASR), observer); final IvrEndpointResponse ivrResponse2 = expectMsgClass(IvrEndpointResponse.class); assertTrue(ivrResponse2.succeeded()); // Stop observing events from the IVR end point. endpoint.tell(new StopObserving(observer), observer); } }; } private static final class MockAsrMediaGateway extends AuAbstractMockMediaGateway { @SuppressWarnings("unused") public MockAsrMediaGateway() { super(); } @Override protected void event(final Object message, final ActorRef sender) { final ActorRef self = self(); final Class<?> klass = message.getClass(); if (NotificationRequest.class.equals(klass)) { // Send a successful response for this request. final NotificationRequest request = (NotificationRequest) message; final JainMgcpResponseEvent response = new NotificationRequestResponse(this, ReturnCode.Transaction_Executed_Normally); sender.tell(response, self); // Send the notification. Notify notify = createNotify(request, (int) transactionIdPool.get(), AUMgcpEvent.auoc.withParm("rc=101 asrr=" + ASR_RESULT_TEXT_HEX)); sender.tell(notify, self); notify = createNotify(request, (int) transactionIdPool.get(), AUMgcpEvent.auoc.withParm("rc=101 asrr=" + ASR_RESULT_TEXT_HEX)); sender.tell(notify, self); notify = createNotify(request, (int) transactionIdPool.get(), AUMgcpEvent.auoc.withParm("rc=100 asrr=" + ASR_RESULT_TEXT_HEX)); sender.tell(notify, self); } } } private static final class FailingMockAsrMediaGateway extends AuAbstractMockMediaGateway { @SuppressWarnings("unused") public FailingMockAsrMediaGateway() { super(); } @Override protected void event(final Object message, final ActorRef sender) { final ActorRef self = self(); final Class<?> klass = message.getClass(); if (NotificationRequest.class.equals(klass)) { // Send a successful response for this request. final NotificationRequest request = (NotificationRequest) message; final JainMgcpResponseEvent response = new NotificationRequestResponse(this, ReturnCode.Transaction_Executed_Normally); response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); // Send the notification. final Notify notify = createNotify(request, (int) transactionIdPool.get(), AUMgcpEvent.auof.withParm("rc=300")); sender.tell(notify, self); } } } private static final class MockAsrWithEndSignal extends AuAbstractMockMediaGateway { @SuppressWarnings("unused") public MockAsrWithEndSignal() { super(); } @Override protected void event(final Object message, final ActorRef sender) { final ActorRef self = self(); final Class<?> klass = message.getClass(); if (NotificationRequest.class.equals(klass)) { // Send a successful response for this request. final NotificationRequest request = (NotificationRequest) message; if ("AU/es(sg=asr)".equals(request.getSignalRequests()[0].toString())) { //handle stop request final JainMgcpResponseEvent response = new NotificationRequestResponse(this, ReturnCode.Transaction_Executed_Normally); sender.tell(response, self); Notify notify = createNotify(request, (int) transactionIdPool.get(), AUMgcpEvent.auoc.withParm("rc=100")); sender.tell(notify, self); return; } final JainMgcpResponseEvent response = new NotificationRequestResponse(this, ReturnCode.Transaction_Executed_Normally); sender.tell(response, self); // Send the notification. Notify notify = createNotify(request, (int) transactionIdPool.get(), AUMgcpEvent.auoc.withParm("rc=101 asrr=" + ASR_RESULT_TEXT_HEX)); sender.tell(notify, self); } } } private static abstract class AuAbstractMockMediaGateway extends AbstractMockMediaGateway { protected Notify createNotify(final NotificationRequest request, int transactionId, final MgcpEvent event) { final EventName[] events = {new EventName(AUPackage.AU, event)}; Notify notify = new Notify(this, request.getEndpointIdentifier(), request.getRequestIdentifier(), events); notify.setTransactionHandle(transactionId); return notify; } } }
14,886
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AsrSignalTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/test/java/org/restcomm/connect/mgcp/AsrSignalTest.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.mgcp; import org.junit.Before; import org.junit.Test; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.Assert.assertEquals; /** * @author Dmitriy Nadolenko */ public class AsrSignalTest { public static final String DEFAULT_LANG = "en-US"; private String driver; private List<URI> initialPrompts; private String endInputKey; private int maximumRecTimer; private int waitingInputTimer; private int timeAfterSpeech; private String hotWords; private String input; private int numberOfDigits; private boolean partialResult; @Before public void init() { driver = "no_name_driver"; initialPrompts = Collections.singletonList(URI.create("hello.wav")); endInputKey = "#"; maximumRecTimer = 10; waitingInputTimer = 10; timeAfterSpeech = 5; hotWords = "Wait"; input = "dtmf_speech"; numberOfDigits = 1; partialResult = true; } @Test public void testFormatting() { String expectedResult = "ip=hello.wav dr=no_name_driver ln=en-US eik=# mrt=100 wit=100 pst=50 hw=57616974 in=dtmf_speech mn=1 mx=1 pr=true"; AsrSignal asrSignal = new AsrSignal(driver, DEFAULT_LANG, initialPrompts, endInputKey, maximumRecTimer, waitingInputTimer, timeAfterSpeech, hotWords, input, numberOfDigits, partialResult); String actualResult = asrSignal.toString(); assertEquals(expectedResult, actualResult); } @Test public void testFormattingWithMultiplePrompts() { initialPrompts = new ArrayList<URI>() {{ add(URI.create("hello.wav")); add(URI.create("world.wav")); }}; String expectedResult = "ip=hello.wav,world.wav dr=no_name_driver ln=en-US eik=# mrt=100 wit=100 pst=50 hw=57616974 in=dtmf_speech mn=1 mx=1 pr=true"; AsrSignal asrSignal = new AsrSignal(driver, DEFAULT_LANG, initialPrompts, endInputKey, maximumRecTimer, waitingInputTimer, timeAfterSpeech, hotWords, input, numberOfDigits, partialResult); String actualResult = asrSignal.toString(); assertEquals(expectedResult, actualResult); } }
3,091
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConnectionTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/test/java/org/restcomm/connect/mgcp/ConnectionTest.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.mgcp; import static org.junit.Assert.assertTrue; import jain.protocol.ip.mgcp.JainMgcpEvent; import jain.protocol.ip.mgcp.message.CreateConnection; import jain.protocol.ip.mgcp.message.CreateConnectionResponse; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.DeleteConnectionResponse; import jain.protocol.ip.mgcp.message.ModifyConnection; import jain.protocol.ip.mgcp.message.ModifyConnectionResponse; import jain.protocol.ip.mgcp.message.parms.ConnectionDescriptor; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import java.util.HashSet; import java.util.Set; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.restcomm.connect.commons.fsm.Action; import org.restcomm.connect.commons.fsm.FiniteStateMachine; import org.restcomm.connect.commons.fsm.State; import org.restcomm.connect.commons.fsm.Transition; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; /** * @author [email protected] (Thomas Quintana) */ public final class ConnectionTest { private static final String sdp = "v=0\n" + "o=- 1362546170756 1 IN IP4 192.168.1.100\n" + "s=Mobicents Media Server\n" + "c=IN IP4 192.168.1.100\n" + "t=0 0\n" + "m=audio 63044 RTP/AVP 97 8 0 101\n" + "a=rtpmap:97 l16/8000\n" + "a=rtpmap:8 pcma/8000\n" + "a=rtpmap:0 pcmu/8000\n" + "a=rtpmap:101 telephone-event/8000\n" + "a=fmtp:101 0-15\n"; private static ActorSystem system; public ConnectionTest() { super(); } @BeforeClass public static void before() throws Exception { system = ActorSystem.create(); } @AfterClass public static void after() throws Exception { system.shutdown(); } @SuppressWarnings("unchecked") @Test public void testSuccessfulScenarioWithOutInitialSdp() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an end point. gateway.tell(new CreatePacketRelayEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Create a connection. // The CreateConnection message collides with CreateConnection from JAIN MGCP so the full // class path is required to avoid confusing the JVM. gateway.tell(new org.restcomm.connect.mgcp.CreateConnection(session), observer); final MediaGatewayResponse<ActorRef> connectionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(connectionResponse.succeeded()); final ActorRef connection = connectionResponse.get(); // Start observing events from the connection. connection.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Initialize the connection. connection.tell(new InitializeConnection(endpoint), observer); ConnectionStateChanged event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.CLOSED == event.state()); // Open the connection half way by not passing an sdp. final OpenConnection open = new OpenConnection(ConnectionMode.SendRecv, false); connection.tell(open, observer); event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.HALF_OPEN == event.state()); assertTrue(event.descriptor() != null); // Open the connection by updating the sdp. final UpdateConnection update = new UpdateConnection(new ConnectionDescriptor(sdp)); connection.tell(update, observer); event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.OPEN == event.state()); assertTrue(event.descriptor() != null); // Close the connection. connection.tell(new CloseConnection(), observer); event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.CLOSED == event.state()); // Stop observing events from the connection. connection.tell(new StopObserving(observer), observer); } }; } @SuppressWarnings("unchecked") @Test public void testSuccessfulScenarioWithInitialSdp() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and links in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an end point. gateway.tell(new CreatePacketRelayEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Create a connection. // The CreateConnection message collides with CreateConnection from JAIN MGCP so the full // class path is required to avoid confusing the JVM. gateway.tell(new org.restcomm.connect.mgcp.CreateConnection(session), observer); final MediaGatewayResponse<ActorRef> connectionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(connectionResponse.succeeded()); final ActorRef connection = connectionResponse.get(); // Start observing events from the connection. connection.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Initialize the connection. connection.tell(new InitializeConnection(endpoint), observer); ConnectionStateChanged event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.CLOSED == event.state()); // Open the connection with an sdp. final ConnectionDescriptor descriptor = new ConnectionDescriptor(sdp); final OpenConnection open = new OpenConnection(descriptor, ConnectionMode.SendRecv); connection.tell(open, observer); event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.OPEN == event.state()); assertTrue(event.descriptor() != null); // Close the connection. connection.tell(new CloseConnection(), observer); event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.CLOSED == event.state()); // Stop observing events from the connection. connection.tell(new StopObserving(observer), observer); } }; } @SuppressWarnings("unchecked") @Test public void testSuccessfulScenarioWithInitialSdpWithModify() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and links in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an end point. gateway.tell(new CreatePacketRelayEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Create a connection. // The CreateConnection message collides with CreateConnection from JAIN MGCP so the full // class path is required to avoid confusing the JVM. gateway.tell(new org.restcomm.connect.mgcp.CreateConnection(session), observer); final MediaGatewayResponse<ActorRef> connectionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(connectionResponse.succeeded()); final ActorRef connection = connectionResponse.get(); // Start observing events from the connection. connection.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Initialize the connection. connection.tell(new InitializeConnection(endpoint), observer); ConnectionStateChanged event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.CLOSED == event.state()); // Open the connection with an sdp. final ConnectionDescriptor descriptor = new ConnectionDescriptor(sdp); final OpenConnection open = new OpenConnection(descriptor, ConnectionMode.SendRecv); connection.tell(open, observer); event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.OPEN == event.state()); assertTrue(event.descriptor() != null); // Modify the connection. final UpdateConnection update = new UpdateConnection(ConnectionMode.RecvOnly); connection.tell(update, observer); event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.OPEN == event.state()); assertTrue(event.descriptor() != null); // Close the connection. connection.tell(new CloseConnection(), observer); event = expectMsgClass(ConnectionStateChanged.class); assertTrue(ConnectionStateChanged.State.CLOSED == event.state()); // Stop observing events from the connection. connection.tell(new StopObserving(observer), observer); } }; } private static final class MockMediaGateway extends AbstractMockMediaGateway { private final State closed; private final State halfOpen; private final State open; private final FiniteStateMachine fsm; // Some necessary state. private ActorRef sender; @SuppressWarnings("unused") public MockMediaGateway() { super(); final ActorRef source = self(); closed = new State("closed", new Closed(), null); halfOpen = new State("half open", new Open(), null); open = new State("open", new Open(), null); final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(closed, halfOpen)); transitions.add(new Transition(closed, open)); transitions.add(new Transition(halfOpen, open)); transitions.add(new Transition(open, open)); transitions.add(new Transition(open, closed)); fsm = new FiniteStateMachine(closed, transitions); } @Override protected void event(final Object message, final ActorRef sender) { this.sender = sender; try { // Print the requests. if (message instanceof JainMgcpEvent) { System.out.println(message.toString()); } // FSM logic. final Class<?> klass = message.getClass(); if (CreateConnection.class.equals(klass)) { final CreateConnection request = (CreateConnection) message; if (request.getRemoteConnectionDescriptor() == null) { fsm.transition(message, halfOpen); } else { fsm.transition(message, open); } } else if (ModifyConnection.class.equals(klass)) { fsm.transition(message, open); } else if (DeleteConnection.class.equals(klass)) { fsm.transition(message, closed); } } catch (final Exception exception) { exception.printStackTrace(); } } private final class Closed implements Action { public Closed() { super(); } @Override public void execute(final Object message) throws Exception { final ActorRef self = self(); final DeleteConnection request = (DeleteConnection) message; DeleteConnectionResponse response = null; if (!request.getConnectionIdentifier().toString().equals("183")) { response = new DeleteConnectionResponse(this, ReturnCode.Incorrect_Connection_ID); } else if (!request.getEndpointIdentifier().toString().equals("mobicents/relay/[email protected]:2427")) { response = new DeleteConnectionResponse(this, ReturnCode.Endpoint_Unknown); } else { response = new DeleteConnectionResponse(this, ReturnCode.Transaction_Executed_Normally); } response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); System.out.println(response.toString()); } } private final class Open implements Action { public Open() { super(); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ConnectionDescriptor descriptor = new ConnectionDescriptor(sdp); // Handle transitions from closed and half open. if (CreateConnection.class.equals(klass)) { final CreateConnection request = (CreateConnection) message; CreateConnectionResponse response = null; // This is the new connection identifier and must be used to identify this connection. final ConnectionIdentifier connId = new ConnectionIdentifier("183"); // This is the specific end point identifier and must be used to identify the end point // being used by this connection for future communications. final EndpointIdentifier endpointId = new EndpointIdentifier("mobicents/relay/1", domain); response = new CreateConnectionResponse(this, ReturnCode.Transaction_Executed_Normally, connId); response.setSpecificEndpointIdentifier(endpointId); response.setLocalConnectionDescriptor(descriptor); response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); System.out.println(response.toString()); } else if (ModifyConnection.class.equals(klass)) { final ModifyConnection request = (ModifyConnection) message; ModifyConnectionResponse response = null; if (!request.getConnectionIdentifier().toString().equals("183")) { response = new ModifyConnectionResponse(this, ReturnCode.Incorrect_Connection_ID); } else if (!request.getEndpointIdentifier().toString().equals("mobicents/relay/[email protected]:2427")) { response = new ModifyConnectionResponse(this, ReturnCode.Endpoint_Unknown); } else { response = new ModifyConnectionResponse(this, ReturnCode.Transaction_Executed_Normally); response.setLocalConnectionDescriptor(descriptor); } response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); System.out.println(response.toString()); } } } } }
19,714
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.mgcp/src/test/java/org/restcomm/connect/mgcp/EndpointTest.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.mgcp; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; import jain.protocol.ip.mgcp.JainMgcpEvent; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.DeleteConnectionResponse; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.NotificationRequestResponse; import jain.protocol.ip.mgcp.message.Notify; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import jain.protocol.ip.mgcp.pkg.MgcpEvent; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUPackage; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import static org.junit.Assert.assertTrue; /** * @author [email protected] (Maria Farooq) */ public class EndpointTest { private static ActorSystem system; public EndpointTest() { super(); } @BeforeClass public static void before() throws Exception { system = ActorSystem.create(); } @AfterClass public static void after() throws Exception { system.shutdown(); } /** * https://github.com/RestComm/Restcomm-Connect/issues/2310 */ @Test public void testDeleteEnpointSuccessScenario() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an IVR end point. gateway.tell(new CreateIvrEndpoint(session, "mobicents/ivr/1"), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Start observing events from the IVR end point. endpoint.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Destroy Endpoint endpoint.tell(new DestroyEndpoint(), observer); final EndpointStateChanged endpointStateChanged = expectMsgClass(EndpointStateChanged.class); assertTrue(endpointStateChanged.getState().equals(EndpointState.DESTROYED)); // Stop observing events from the IVR end point. endpoint.tell(new StopObserving(observer), observer); } }; } /** * https://github.com/RestComm/Restcomm-Connect/issues/2310 */ @Test public void testDeleteEnpointFailureScenario() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(FailingMockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an IVR end point. gateway.tell(new CreateIvrEndpoint(session, "mobicents/ivr/1"), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Start observing events from the IVR end point. endpoint.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Destroy Endpoint endpoint.tell(new DestroyEndpoint(), observer); final EndpointStateChanged endpointStateChanged = expectMsgClass(EndpointStateChanged.class); assertTrue(endpointStateChanged.getState().equals(EndpointState.FAILED)); // Stop observing events from the IVR end point. endpoint.tell(new StopObserving(observer), observer); } }; } private static final class MockMediaGateway extends AbstractMockMediaGateway { @SuppressWarnings("unused") public MockMediaGateway() { super(); } @Override protected void event(final Object message, final ActorRef sender) { final ActorRef self = self(); if (message instanceof JainMgcpEvent) { System.out.println(message.toString()); } final Class<?> klass = message.getClass(); if (NotificationRequest.class.equals(klass)) { // Send a successful response for this request. final NotificationRequest request = (NotificationRequest) message; final JainMgcpResponseEvent response = new NotificationRequestResponse(this, ReturnCode.Transaction_Executed_Normally); sender.tell(response, self); System.out.println(response.toString()); // Send the notification. final MgcpEvent event = AUMgcpEvent.auoc.withParm("rc=100 dc=1"); final EventName[] events = { new EventName(AUPackage.AU, event) }; final Notify notify = new Notify(this, request.getEndpointIdentifier(), request.getRequestIdentifier(), events); notify.setTransactionHandle((int) transactionIdPool.get()); sender.tell(notify, self); System.out.println(notify.toString()); }else if(DeleteConnection.class.equals(klass)){ final JainMgcpResponseEvent response = new DeleteConnectionResponse(this, ReturnCode.Transaction_Executed_Normally); sender.tell(response, self); }else{ System.out.println("inside else"); } } } private static final class FailingMockMediaGateway extends AbstractMockMediaGateway { @SuppressWarnings("unused") public FailingMockMediaGateway() { super(); } @Override protected void event(final Object message, final ActorRef sender) { final ActorRef self = self(); if (message instanceof JainMgcpEvent) { System.out.println("event received: "+message.toString()); } final Class<?> klass = message.getClass(); if (NotificationRequest.class.equals(klass)) { // Send a successful response for this request. final NotificationRequest request = (NotificationRequest) message; final JainMgcpResponseEvent response = new NotificationRequestResponse(this, ReturnCode.Transaction_Executed_Normally); response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); System.out.println(response.toString()); // Send the notification. final MgcpEvent event = AUMgcpEvent.auoc.withParm("rc=300"); final EventName[] events = { new EventName(AUPackage.AU, event) }; final Notify notify = new Notify(this, request.getEndpointIdentifier(), request.getRequestIdentifier(), events); notify.setTransactionHandle((int) transactionIdPool.get()); sender.tell(notify, self); System.out.println(notify.toString()); } else if(DeleteConnection.class.equals(klass)){ final JainMgcpResponseEvent response = new DeleteConnectionResponse(this, ReturnCode.Endpoint_Unknown); sender.tell(response, self); }else{ System.out.println("inside else"); } } } }
10,151
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.mgcp/src/test/java/org/restcomm/connect/mgcp/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.mgcp; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.junit.Test; /** * @author [email protected] (Thomas Quintana) */ public final class PlayTest { public PlayTest() { super(); } @Test public void testFormatting() { final List<URI> announcements = new ArrayList<URI>(); announcements.add(URI.create("hello.wav")); final Play play = new Play(announcements, 1); final String result = play.toString(); assertTrue("an=hello.wav it=1".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } @Test public void testFormattingWithMultipleAnnouncements() { final List<URI> announcements = new ArrayList<URI>(); announcements.add(URI.create("hello.wav")); announcements.add(URI.create("world.wav")); final Play play = new Play(announcements, 1); final String result = play.toString(); assertTrue("an=hello.wav;world.wav it=1".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } @Test public void testFormattingWithNoAnnouncements() { final List<URI> announcements = new ArrayList<URI>(); final Play play = new Play(announcements, 1); final String result = play.toString(); assertTrue(result.isEmpty()); } }
2,272
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
LinkTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/test/java/org/restcomm/connect/mgcp/LinkTest.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.mgcp; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; import jain.protocol.ip.mgcp.JainMgcpEvent; import jain.protocol.ip.mgcp.message.CreateConnection; import jain.protocol.ip.mgcp.message.CreateConnectionResponse; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.DeleteConnectionResponse; import jain.protocol.ip.mgcp.message.ModifyConnection; import jain.protocol.ip.mgcp.message.ModifyConnectionResponse; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.*; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import org.restcomm.connect.commons.fsm.Action; import org.restcomm.connect.commons.fsm.FiniteStateMachine; import org.restcomm.connect.commons.fsm.State; import org.restcomm.connect.commons.fsm.Transition; /** * @author [email protected] (Thomas Quintana) */ public class LinkTest { private static ActorSystem system; public LinkTest() { super(); } @BeforeClass public static void before() throws Exception { system = ActorSystem.create(); } @AfterClass public static void after() throws Exception { system.shutdown(); } @SuppressWarnings("unchecked") @Test public void testSuccessfulScenario() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and links in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create a bridge end point. gateway.tell(new CreateBridgeEndpoint(session), observer); MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef bridge = endpointResponse.get(); // Create an ivr end point. gateway.tell(new CreateIvrEndpoint(session), observer); endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef ivr = endpointResponse.get(); // Create a link. gateway.tell(new CreateLink(session), observer); endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef link = endpointResponse.get(); // Start observing events from the link. link.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Initialize the link. final InitializeLink initialize = new InitializeLink(bridge, ivr); link.tell(initialize, observer); LinkStateChanged event = expectMsgClass(LinkStateChanged.class); assertTrue(LinkStateChanged.State.CLOSED == event.state()); // Open the link. link.tell(new OpenLink(ConnectionMode.SendRecv), observer); event = expectMsgClass(LinkStateChanged.class); assertTrue(LinkStateChanged.State.OPEN == event.state()); // Close the link. link.tell(new CloseLink(), observer); event = expectMsgClass(LinkStateChanged.class); assertTrue(LinkStateChanged.State.CLOSED == event.state()); // Stop observing events from the link. link.tell(new StopObserving(observer), observer); } }; } @SuppressWarnings("unchecked") @Test public void testSuccessfulScenarioWithModify() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and links in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create a bridge end point. gateway.tell(new CreateBridgeEndpoint(session), observer); MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef bridge = endpointResponse.get(); // Create an ivr end point. gateway.tell(new CreateIvrEndpoint(session), observer); endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef ivr = endpointResponse.get(); // Create a link. gateway.tell(new CreateLink(session), observer); endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef link = endpointResponse.get(); // Start observing events from the link. link.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Initialize the link. final InitializeLink initialize = new InitializeLink(bridge, ivr); link.tell(initialize, observer); LinkStateChanged event = expectMsgClass(LinkStateChanged.class); assertTrue(LinkStateChanged.State.CLOSED == event.state()); // Open the link. link.tell(new OpenLink(ConnectionMode.SendRecv), observer); event = expectMsgClass(LinkStateChanged.class); assertTrue(LinkStateChanged.State.OPEN == event.state()); // Modify the primary connection in the link. UpdateLink update = new UpdateLink(ConnectionMode.RecvOnly, UpdateLink.Type.PRIMARY); link.tell(update, observer); event = expectMsgClass(LinkStateChanged.class); assertTrue(LinkStateChanged.State.OPEN == event.state()); // Modify the secondary connection in the link. update = new UpdateLink(ConnectionMode.SendOnly, UpdateLink.Type.SECONDARY); link.tell(update, observer); event = expectMsgClass(LinkStateChanged.class); assertTrue(LinkStateChanged.State.OPEN == event.state()); // Close the link. link.tell(new CloseLink(), observer); event = expectMsgClass(LinkStateChanged.class); assertTrue(LinkStateChanged.State.CLOSED == event.state()); // Stop observing events from the link. link.tell(new StopObserving(observer), observer); } }; } private static final class MockMediaGateway extends AbstractMockMediaGateway { private final State primaryClosed; private final State secondaryClosed; private final State open; private final FiniteStateMachine fsm; // Some necessary state. private ActorRef sender; @SuppressWarnings("unused") public MockMediaGateway() { super(); final ActorRef source = self(); primaryClosed = new State("primaryClosed", new Closed(), null); secondaryClosed = new State("secondaryClosed", new Closed(), null); open = new State("open", new Open(), null); final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(secondaryClosed, open)); transitions.add(new Transition(open, open)); transitions.add(new Transition(open, primaryClosed)); transitions.add(new Transition(primaryClosed, secondaryClosed)); fsm = new FiniteStateMachine(secondaryClosed, transitions); } @Override protected void event(final Object message, final ActorRef sender) { this.sender = sender; final State state = fsm.state(); try { // Print the requests. if (message instanceof JainMgcpEvent) { System.out.println(message.toString()); } // FSM logic. final Class<?> klass = message.getClass(); if (CreateConnection.class.equals(klass)) { fsm.transition(message, open); } else if (ModifyConnection.class.equals(klass)) { fsm.transition(message, open); } else if (DeleteConnection.class.equals(klass)) { if (open.equals(state)) { fsm.transition(message, primaryClosed); } else if (primaryClosed.equals(state)) { fsm.transition(message, secondaryClosed); } } } catch (final Exception exception) { exception.printStackTrace(); } } private final class Closed implements Action { public Closed() { super(); } @Override public void execute(final Object message) throws Exception { final ActorRef self = self(); final DeleteConnection request = (DeleteConnection) message; DeleteConnectionResponse response = null; if (request.getConnectionIdentifier().toString().equals("183") && request.getEndpointIdentifier().toString().equals("mobicents/bridge/[email protected]:2427")) { response = new DeleteConnectionResponse(this, ReturnCode.Transaction_Executed_Normally); } else if (request.getConnectionIdentifier().toString().equals("184") && request.getEndpointIdentifier().toString().equals("mobicents/ivr/[email protected]:2427")) { response = new DeleteConnectionResponse(this, ReturnCode.Transaction_Executed_Normally); } else { response = new DeleteConnectionResponse(this, ReturnCode.Transient_Error); } response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); System.out.println(response.toString()); } } private final class Open implements Action { public Open() { super(); } @Override public void execute(final Object message) throws Exception { final ActorRef self = self(); final Class<?> klass = message.getClass(); // Handle transitions from primaryClosed and half open. if (CreateConnection.class.equals(klass)) { final CreateConnection request = (CreateConnection) message; CreateConnectionResponse response = null; // This is the new connection identifier and must be used to identify this connection. final ConnectionIdentifier primaryConnId = new ConnectionIdentifier("183"); final ConnectionIdentifier secondaryConnId = new ConnectionIdentifier("184"); // This is the specific end point identifier and must be used to identify the end point // being used by this connection for future communications. final EndpointIdentifier primaryEndpointId = new EndpointIdentifier("mobicents/bridge/1", domain); final EndpointIdentifier secondaryEndpointId = new EndpointIdentifier("mobicents/ivr/1", domain); response = new CreateConnectionResponse(this, ReturnCode.Transaction_Executed_Normally, primaryConnId); response.setSecondConnectionIdentifier(secondaryConnId); response.setSpecificEndpointIdentifier(primaryEndpointId); response.setSecondEndpointIdentifier(secondaryEndpointId); response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); System.out.println(response.toString()); } else if (ModifyConnection.class.equals(klass)) { final ModifyConnection request = (ModifyConnection) message; ModifyConnectionResponse response = null; if (request.getConnectionIdentifier().toString().equals("183") && request.getEndpointIdentifier().toString().equals("mobicents/bridge/[email protected]:2427")) { response = new ModifyConnectionResponse(this, ReturnCode.Transaction_Executed_Normally); } else if (request.getConnectionIdentifier().toString().equals("184") && request.getEndpointIdentifier().toString().equals("mobicents/ivr/[email protected]:2427")) { response = new ModifyConnectionResponse(this, ReturnCode.Transaction_Executed_Normally); } else { response = new ModifyConnectionResponse(this, ReturnCode.Transient_Error); } response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); System.out.println(response.toString()); } } } } }
16,026
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PlayCollectTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/test/java/org/restcomm/connect/mgcp/PlayCollectTest.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.mgcp; import static org.junit.Assert.assertTrue; import java.net.URI; import org.junit.Ignore; import org.junit.Test; /** * @author [email protected] (Thomas Quintana) */ public final class PlayCollectTest { public PlayCollectTest() { super(); } @Ignore @Test public void testFormatting() { // We will used the builder pattern to create this message. final PlayCollect.Builder builder = PlayCollect.builder(); builder.addPrompt(URI.create("hello.wav")); builder.setClearDigitBuffer(true); builder.setMinNumberOfDigits(1); builder.setMaxNumberOfDigits(16); builder.setDigitPattern("0123456789*#"); builder.setFirstDigitTimer(1000); builder.setInterDigitTimer(1000); builder.setEndInputKey("#"); final PlayCollect playCollect = builder.build(); final String result = playCollect.toString(); assertTrue("ip=hello.wav cb=true mx=16 mn=1 dp=0123456789*# fdt=10 idt=10 eik=#".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } @Test public void testFormattingDefaults() { // We will used the builder pattern to create this message. final PlayCollect.Builder builder = PlayCollect.builder(); builder.addPrompt(URI.create("hello.wav")); final PlayCollect playCollect = builder.build(); final String result = playCollect.toString(); assertTrue("ip=hello.wav".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } @Ignore @Test public void testFormattingWithNoPrompts() { // We will used the builder pattern to create this message. final PlayCollect.Builder builder = PlayCollect.builder(); builder.setClearDigitBuffer(true); builder.setMinNumberOfDigits(1); builder.setMaxNumberOfDigits(16); builder.setDigitPattern("0123456789*#"); builder.setFirstDigitTimer(1000); builder.setInterDigitTimer(1000); builder.setEndInputKey("#"); final PlayCollect playCollect = builder.build(); final String result = playCollect.toString(); assertTrue("cb=true mx=16 mn=1 dp=0123456789*# fdt=10 idt=10 eik=#".equals(result)); System.out.println("Signal Parameters: " + result + "\n"); } /** * testFormattingWithMultiplePrompts * https://github.com/RestComm/Restcomm-Connect/issues/1988 */ @Test public void testFormattingWithMultiplePrompts() { // We will used the builder pattern to create this message. final PlayCollect.Builder builder = PlayCollect.builder(); builder.addPrompt(URI.create("hello.wav")); builder.addPrompt(URI.create("world.wav")); builder.setClearDigitBuffer(true); builder.setMinNumberOfDigits(1); builder.setMaxNumberOfDigits(32767); builder.setDigitPattern("0123456789*#"); builder.setFirstDigitTimer(50); builder.setInterDigitTimer(50); builder.setEndInputKey("*"); final PlayCollect playCollect = builder.build(); final String result = playCollect.toString(); final String expectedResult = "ip=hello.wav,world.wav cb=true mx=32767 mn=1 dp=0123456789*# fdt=500 idt=500 eik=*"; assertTrue(expectedResult.equals(result)); } }
4,219
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IvrEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/test/java/org/restcomm/connect/mgcp/IvrEndpointTest.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.mgcp; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUPackage; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.NotificationRequestResponse; import jain.protocol.ip.mgcp.message.Notify; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import jain.protocol.ip.mgcp.pkg.MgcpEvent; /** * @author [email protected] (Thomas Quintana) */ public class IvrEndpointTest { private static ActorSystem system; public IvrEndpointTest() { super(); } @BeforeClass public static void before() throws Exception { system = ActorSystem.create(); } @AfterClass public static void after() throws Exception { system.shutdown(); } @SuppressWarnings("unchecked") @Test public void testSuccessfulScenario() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an IVR end point. gateway.tell(new CreateIvrEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Start observing events from the IVR end point. endpoint.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Play some audio. final List<URI> announcements = new ArrayList<URI>(); announcements.add(URI.create("hello.wav")); final Play play = new Play(announcements, 1); endpoint.tell(play, observer); final IvrEndpointResponse ivrResponse = expectMsgClass(IvrEndpointResponse.class); assertTrue(ivrResponse.succeeded()); // Stop observing events from the IVR end point. endpoint.tell(new StopObserving(observer), observer); } }; } @SuppressWarnings("unchecked") @Test public void testSuccessfulScenarioWithDigits() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(MockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an IVR end point. gateway.tell(new CreateIvrEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Start observing events from the IVR end point. endpoint.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Play some audio and collect digits. final PlayCollect.Builder builder = PlayCollect.builder(); builder.addPrompt(URI.create("hello.wav")); final PlayCollect playCollect = builder.build(); endpoint.tell(playCollect, observer); final IvrEndpointResponse ivrResponse = expectMsgClass(IvrEndpointResponse.class); assertTrue(ivrResponse.succeeded()); assertTrue("1".equals(((CollectedResult)ivrResponse.get()).getResult())); // Stop observing events from the IVR end point. endpoint.tell(new StopObserving(observer), observer); } }; } @SuppressWarnings("unchecked") @Test public void testFailureScenario() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new mock media gateway to simulate the real thing. final ActorRef gateway = system.actorOf(new Props(FailingMockMediaGateway.class)); // Create a media session. This is just an identifier that groups // a set of end points, connections, and lists in to one call. gateway.tell(new CreateMediaSession(), observer); final MediaGatewayResponse<MediaSession> mediaSessionResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(mediaSessionResponse.succeeded()); final MediaSession session = mediaSessionResponse.get(); // Create an IVR end point. gateway.tell(new CreateIvrEndpoint(session), observer); final MediaGatewayResponse<ActorRef> endpointResponse = expectMsgClass(MediaGatewayResponse.class); assertTrue(endpointResponse.succeeded()); final ActorRef endpoint = endpointResponse.get(); // Start observing events from the IVR end point. endpoint.tell(new Observe(observer), observer); final Observing observingResponse = expectMsgClass(Observing.class); assertTrue(observingResponse.succeeded()); // Play some audio. final List<URI> announcements = new ArrayList<URI>(); announcements.add(URI.create("hello.wav")); final Play play = new Play(announcements, 1); endpoint.tell(play, observer); final IvrEndpointResponse ivrResponse = expectMsgClass(IvrEndpointResponse.class); assertFalse(ivrResponse.succeeded()); // Stop observing events from the IVR end point. endpoint.tell(new StopObserving(observer), observer); } }; } private static final class MockMediaGateway extends AbstractMockMediaGateway { @SuppressWarnings("unused") public MockMediaGateway() { super(); } @Override protected void event(final Object message, final ActorRef sender) { final ActorRef self = self(); final Class<?> klass = message.getClass(); if (NotificationRequest.class.equals(klass)) { // Send a successful response for this request. final NotificationRequest request = (NotificationRequest) message; final JainMgcpResponseEvent response = new NotificationRequestResponse(this, ReturnCode.Transaction_Executed_Normally); sender.tell(response, self); // Send the notification. final MgcpEvent event = AUMgcpEvent.auoc.withParm("rc=100 dc=1"); final EventName[] events = { new EventName(AUPackage.AU, event) }; final Notify notify = new Notify(this, request.getEndpointIdentifier(), request.getRequestIdentifier(), events); notify.setTransactionHandle((int) transactionIdPool.get()); sender.tell(notify, self); } } } private static final class FailingMockMediaGateway extends AbstractMockMediaGateway { @SuppressWarnings("unused") public FailingMockMediaGateway() { super(); } @Override protected void event(final Object message, final ActorRef sender) { final ActorRef self = self(); final Class<?> klass = message.getClass(); if (NotificationRequest.class.equals(klass)) { // Send a successful response for this request. final NotificationRequest request = (NotificationRequest) message; final JainMgcpResponseEvent response = new NotificationRequestResponse(this, ReturnCode.Transaction_Executed_Normally); response.setTransactionHandle(request.getTransactionHandle()); sender.tell(response, self); // Send the notification. final MgcpEvent event = AUMgcpEvent.auoc.withParm("rc=300"); final EventName[] events = { new EventName(AUPackage.AU, event) }; final Notify notify = new Notify(this, request.getEndpointIdentifier(), request.getRequestIdentifier(), events); notify.setTransactionHandle((int) transactionIdPool.get()); sender.tell(notify, self); } } } }
11,258
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DestroyLink.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/DestroyLink.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.mgcp; import akka.actor.ActorRef; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class DestroyLink { private final ActorRef link; public DestroyLink(final ActorRef link) { super(); this.link = link; } public ActorRef link() { return link; } }
1,243
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MediaGateway.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MediaGateway.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.mgcp; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorContext; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.DeleteProviderException; import jain.protocol.ip.mgcp.JainMgcpCommandEvent; import jain.protocol.ip.mgcp.JainMgcpEvent; import jain.protocol.ip.mgcp.JainMgcpListener; import jain.protocol.ip.mgcp.JainMgcpProvider; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.JainMgcpStack; import jain.protocol.ip.mgcp.message.Constants; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.Notify; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.util.RevolvingCounter; import java.net.InetAddress; import java.util.Map; import java.util.TooManyListenersException; import java.util.concurrent.ConcurrentHashMap; /** * @author [email protected] (Thomas Quintana) */ public final class MediaGateway extends RestcommUntypedActor implements JainMgcpListener { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // MediaGateway connection information. private String name; private InetAddress localIp; private int localPort; private InetAddress remoteIp; private int remotePort; // Used for NAT traversal. private boolean useNat; private InetAddress externalIp; // Used to detect dead media gateways. private long timeout; // JAIN MGCP stuff. private JainMgcpProvider provider; private JainMgcpStack stack; // Call agent. private NotifiedEntity agent; // Media gateway domain name. private String domain; // Message responseListeners. private Map<String, ActorRef> notificationListeners; private Map<Integer, ActorRef> responseListeners; // Runtime stuff. private RevolvingCounter requestIdPool; private RevolvingCounter sessionIdPool; private RevolvingCounter transactionIdPool; public MediaGateway() { super(); notificationListeners = new ConcurrentHashMap<String, ActorRef>(); responseListeners = new ConcurrentHashMap<Integer, ActorRef>(); } private ActorRef getConnection(final Object message) { final CreateConnection request = (CreateConnection) message; final MediaSession session = request.session(); final ActorRef gateway = self(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Connection(gateway, session, agent, timeout); } }); return getContext().actorOf(props); } private ActorRef getBridgeEndpoint(final Object message) { final CreateBridgeEndpoint request = (CreateBridgeEndpoint) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final String endpointName = request.endpointName(); Props props = null; if(endpointName == null){ props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new BridgeEndpoint(gateway, session, agent, domain, timeout); } }); }else{ props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new BridgeEndpoint(gateway, session, agent, domain, timeout, endpointName); } }); } return getContext().actorOf(props); } private ActorRef getConferenceEndpoint(final Object message) { final ActorRef gateway = self(); final CreateConferenceEndpoint request = (CreateConferenceEndpoint) message; final MediaSession session = request.session(); final String endpointName = request.endpointName(); Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new ConferenceEndpoint(gateway, session, agent, domain, timeout, endpointName); } }); return getContext().actorOf(props); } private MediaGatewayInfo getInfo(final Object message) { return new MediaGatewayInfo(name, remoteIp, remotePort, useNat, externalIp); } private ActorRef getIvrEndpoint(final Object message) { final ActorRef gateway = self(); final CreateIvrEndpoint request = (CreateIvrEndpoint) message; final MediaSession session = request.session(); final String endpointName = request.endpointName(); Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new IvrEndpoint(gateway, session, agent, domain, timeout, endpointName); } }); return getContext().actorOf(props); } private ActorRef getLink(final Object message) { final CreateLink request = (CreateLink) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final ConnectionIdentifier connectionIdentifier = request.connectionIdentifier(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Link(gateway, session, agent, timeout, connectionIdentifier); } }); return getContext().actorOf(props); } private ActorRef getPacketRelayEndpoint(final Object message) { final ActorRef gateway = self(); final CreatePacketRelayEndpoint request = (CreatePacketRelayEndpoint) message; final MediaSession session = request.session(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new PacketRelayEndpoint(gateway, session, agent, domain, timeout); } }); return getContext().actorOf(props); } private MediaSession getSession() { MediaSession s=null; try{ s = new MediaSession((int) sessionIdPool.get()); }catch(Exception e){ logger.error("Exception in getSession: "+e.getMessage() +" is MediaGateway actor terminated? "+self().isTerminated() +" current object snapshot: \n"+this.toString(), e); } return s; } private void powerOff(final Object message) { // Clean up the JAIN MGCP provider. try { provider.removeJainMgcpListener(this); stack.deleteProvider(provider); } catch (final DeleteProviderException exception) { logger.error(exception, "Could not clean up the JAIN MGCP provider."); } // Make sure we don't leave anything behind. name = null; localIp = null; localPort = 0; remoteIp = null; remotePort = 0; useNat = false; externalIp = null; timeout = 0; provider = null; stack = null; agent = null; domain = null; responseListeners.clear(); responseListeners = null; requestIdPool = null; sessionIdPool = null; transactionIdPool = null; } private void powerOn(final Object message) { final PowerOnMediaGateway request = (PowerOnMediaGateway) message; name = request.getName(); localIp = request.getLocalIp(); localPort = request.getLocalPort(); remoteIp = request.getRemoteIp(); remotePort = request.getRemotePort(); useNat = request.useNat(); externalIp = request.getExternalIp(); timeout = request.getTimeout(); stack = request.getStack(); provider = request.getProvider(); //stack = new JainMgcpStackImpl(localIp, localPort); try { //provider = stack.createProvider(); provider.addJainMgcpListener(this); } catch (final TooManyListenersException exception) { //} catch (final CreateProviderException exception) { logger.error(exception, "Could not create a JAIN MGCP provider."); } agent = new NotifiedEntity("restcomm", localIp.getHostAddress(), localPort); domain = new StringBuilder().append(remoteIp.getHostAddress()).append(":").append(remotePort).toString(); notificationListeners.clear(); responseListeners.clear(); requestIdPool = new RevolvingCounter(1, Long.MAX_VALUE); sessionIdPool = new RevolvingCounter(1, Long.MAX_VALUE); transactionIdPool = new RevolvingCounter(1, Long.MAX_VALUE); } private boolean isPartialNotify(final Notify notify) { EventName[] events = notify.getObservedEvents(); return events != null && events.length != 0 && MgcpUtil.isPartialNotify(events[events.length - 1]); } @Override public void processMgcpCommandEvent(final JainMgcpCommandEvent event) { final int value = event.getObjectIdentifier(); switch (value) { case Constants.CMD_NOTIFY: { final Notify notify = (Notify) event; final String id = notify.getRequestIdentifier().toString(); final ActorRef listener; if (isPartialNotify(notify)) { listener = notificationListeners.get(id); } else { listener = notificationListeners.remove(id); } if (listener != null) { listener.tell(notify, self()); } } } } @Override public void processMgcpResponseEvent(final JainMgcpResponseEvent event) { final int id = event.getTransactionHandle(); final ActorRef listener = responseListeners.remove(id); if (listener != null) { listener.tell(event, self()); } } @Override public void onReceive(final Object message) throws Exception { final UntypedActorContext context = getContext(); final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (logger.isDebugEnabled()){ logger.debug("MediaGateway onReceive. self.isTerminated: "+self.isTerminated()+" | Processing "+klass.getName()+" | object snapshot: \n"+this.toString()); } if(self.isTerminated()) logger.error("MediaGateway is Terminated."); if (PowerOnMediaGateway.class.equals(klass)) { powerOn(message); } else if (PowerOffMediaGateway.class.equals(klass)) { powerOff(message); } else if (GetMediaGatewayInfo.class.equals(klass)) { sender.tell(new MediaGatewayResponse<MediaGatewayInfo>(getInfo(message)), sender); } else if (CreateConnection.class.equals(klass)) { sender.tell(new MediaGatewayResponse<ActorRef>(getConnection(message)), self); } else if (CreateLink.class.equals(klass)) { sender.tell(new MediaGatewayResponse<ActorRef>(getLink(message)), self); } else if (CreateMediaSession.class.equals(klass)) { sender.tell(new MediaGatewayResponse<MediaSession>(getSession()), self); } else if (CreateBridgeEndpoint.class.equals(klass)) { final ActorRef endpoint = getBridgeEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreatePacketRelayEndpoint.class.equals(klass)) { final ActorRef endpoint = getPacketRelayEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreateIvrEndpoint.class.equals(klass)) { final ActorRef endpoint = getIvrEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreateConferenceEndpoint.class.equals(klass)) { final ActorRef endpoint = getConferenceEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (DestroyConnection.class.equals(klass)) { final DestroyConnection request = (DestroyConnection) message; if (request.connection() != null) context.stop(request.connection()); } else if (DestroyLink.class.equals(klass)) { final DestroyLink request = (DestroyLink) message; context.stop(request.link()); } else if (DestroyEndpoint.class.equals(klass)) { final DestroyEndpoint request = (DestroyEndpoint) message; if (logger.isInfoEnabled()) logger.info("Gateway: "+self().path()+" about to stop endpoint path: "+request.endpoint().path()+" isTerminated: "+request.endpoint().isTerminated()+" sender: "+sender().path()); while (notificationListeners.containsValue(request.endpoint())) { notificationListeners.values().remove(request.endpoint()); } context.stop(request.endpoint()); } else if (message instanceof JainMgcpCommandEvent) { send(message, sender); } else if (message instanceof JainMgcpResponseEvent) { send(message); } } private void send(final Object message, final ActorRef sender) { final JainMgcpCommandEvent command = (JainMgcpCommandEvent) message; final int transactionId = (int) transactionIdPool.get(); command.setTransactionHandle(transactionId); responseListeners.put(transactionId, sender); if (NotificationRequest.class.equals(command.getClass())) { final NotificationRequest request = (NotificationRequest) command; final String id = Long.toString(requestIdPool.get()); request.getRequestIdentifier().setRequestIdentifier(id); notificationListeners.put(id, sender); } provider.sendMgcpEvents(new JainMgcpEvent[] { command }); } private void send(final Object message) { final JainMgcpResponseEvent response = (JainMgcpResponseEvent) message; provider.sendMgcpEvents(new JainMgcpEvent[] { response }); } @Override public String toString() { return "MediaGateway [logger=" + logger + ", name=" + name + ", localIp=" + localIp + ", localPort=" + localPort + ", remoteIp=" + remoteIp + ", remotePort=" + remotePort + ", useNat=" + useNat + ", externalIp=" + externalIp + ", timeout=" + timeout + ", provider=" + provider + ", stack=" + stack + ", agent=" + agent + ", domain=" + domain + ", notificationListeners=" + notificationListeners + ", responseListeners=" + responseListeners + ", requestIdPool=" + requestIdPool + ", sessionIdPool=" + sessionIdPool + ", transactionIdPool=" + transactionIdPool + "]"; } @Override public void postStop() { if (logger.isDebugEnabled()){ logger.debug("MediaGateway at postStop, here is object snapshot: \n"+this.toString()); } } }
16,988
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EndpointCredentials.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/EndpointCredentials.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.mgcp; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class EndpointCredentials { private final EndpointIdentifier endpointId; public EndpointCredentials(final EndpointIdentifier endpointId) { super(); this.endpointId = endpointId; } public EndpointIdentifier endpointId() { return endpointId; } }
1,360
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConferenceEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/ConferenceEndpoint.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.mgcp; import akka.actor.ActorRef; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ public final class ConferenceEndpoint extends GenericEndpoint { protected static String conferenceEndpointName = "mobicents/cnf/$"; public ConferenceEndpoint(final ActorRef gateway, final MediaSession session, final NotifiedEntity agent, final String domain, long timeout, String endpointName) { super(gateway, session, agent, new EndpointIdentifier(endpointName==null?conferenceEndpointName:endpointName, domain), timeout); } }
1,575
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IvrEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/IvrEndpoint.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.mgcp; import static jain.protocol.ip.mgcp.message.parms.ReturnCode.Transaction_Executed_Normally; import java.util.Map; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang.StringUtils; import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUPackage; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.StopObserving; import akka.actor.ActorRef; import jain.protocol.ip.mgcp.JainIPMgcpException; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.NotificationRequestResponse; import jain.protocol.ip.mgcp.message.Notify; import jain.protocol.ip.mgcp.message.NotifyResponse; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import jain.protocol.ip.mgcp.message.parms.RequestIdentifier; import jain.protocol.ip.mgcp.message.parms.RequestedAction; import jain.protocol.ip.mgcp.message.parms.RequestedEvent; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import jain.protocol.ip.mgcp.pkg.MgcpEvent; import jain.protocol.ip.mgcp.pkg.PackageName; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ public final class IvrEndpoint extends GenericEndpoint { private static final PackageName PACKAGE_NAME = AUPackage.AU; private static final RequestedEvent[] REQUESTED_EVENTS = new RequestedEvent[2]; static { final RequestedAction[] action = new RequestedAction[] { RequestedAction.NotifyImmediately }; REQUESTED_EVENTS[0] = new RequestedEvent(new EventName(PACKAGE_NAME, AUMgcpEvent.auoc), action); REQUESTED_EVENTS[1] = new RequestedEvent(new EventName(PACKAGE_NAME, AUMgcpEvent.auof), action); } private static final String EMPTY_STRING = new String(); private static final String DEFAULT_REQUEST_ID = "0"; private final NotifiedEntity agent; protected static String ivrEndpointName = "mobicents/ivr/$"; public IvrEndpoint(final ActorRef gateway, final MediaSession session, final NotifiedEntity agent, final String domain, long timeout, String endpointName) { super(gateway, session, agent, new EndpointIdentifier(endpointName==null?ivrEndpointName:endpointName, domain), timeout); this.agent = agent; } private void sendAsr(final AsrSignal message) { MgcpEvent event = AsrSignal.REQUEST_ASR.withParm(message.toString()); sendRequest(new EventName(PACKAGE_NAME, event), REQUESTED_EVENTS); } private void send(final Object message) { final Class<?> klass = message.getClass(); final String parameters = message.toString(); MgcpEvent event = null; if (Play.class.equals(klass)) { event = AUMgcpEvent.aupa.withParm(parameters); } else if (PlayCollect.class.equals(klass)) { event = AUMgcpEvent.aupc.withParm(parameters); } else if (PlayRecord.class.equals(klass)) { event = AUMgcpEvent.aupr.withParm(parameters); } sendRequest(new EventName(PACKAGE_NAME, event), REQUESTED_EVENTS); } private void sendRequest(EventName reqSignal, RequestedEvent[] reqEvents) { final EventName[] signal = new EventName[1]; signal[0] = reqSignal; final RequestIdentifier requestId = new RequestIdentifier(DEFAULT_REQUEST_ID); final NotificationRequest request = new NotificationRequest(self(), id, requestId); request.setNotifiedEntity(agent); request.setRequestedEvents(reqEvents); request.setSignalRequests(signal); gateway.tell(request, self()); } private void stop(Object message) { final EventName[] signal = new EventName[1]; StopEndpoint se = (StopEndpoint) message; String parameters = ""; if (se.getEvent() != null) { parameters = "sg=" + se.getEvent().getName(); } else { if (logger.isDebugEnabled()) { logger.debug("StopEndpoint event is null"); } } signal[0] = new EventName(PACKAGE_NAME, AUMgcpEvent.aues.withParm(parameters)); final RequestIdentifier requestId = new RequestIdentifier(DEFAULT_REQUEST_ID); final NotificationRequest request = new NotificationRequest(self(), id, requestId); request.setSignalRequests(signal); request.setNotifiedEntity(agent); //Ask RMS to notify for PlayRecording and PlayAnnouncement Signal. //This way IVR endpoint state at RMS side, will be ready for any subsequent request if (se.getEvent().getName().equalsIgnoreCase("pr") || se.getEvent().getName().equalsIgnoreCase("pa") ) { request.setRequestedEvents(REQUESTED_EVENTS); } gateway.tell(request, self()); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (Observe.class.equals(klass)) { onObserve((Observe) message, self, sender); } else if (StopObserving.class.equals(klass)) { onStopObserving((StopObserving) message, self, sender); } else if (InviteEndpoint.class.equals(klass)) { final EndpointCredentials credentials = new EndpointCredentials(id); sender.tell(credentials, self); } else if (UpdateEndpointId.class.equals(klass)) { final UpdateEndpointId request = (UpdateEndpointId) message; id = request.id(); } else if (DestroyEndpoint.class.equals(klass)) { onDestroyEndpoint((DestroyEndpoint) message, self, sender); } else if (Play.class.equals(klass) || PlayCollect.class.equals(klass) || PlayRecord.class.equals(klass)) { send(message); } else if (AsrSignal.class.equals(klass)) { sendAsr((AsrSignal) message); } else if (StopEndpoint.class.equals(klass)) { stop(message); } else if (Notify.class.equals(klass)) { notification(message); } else if (NotificationRequestResponse.class.equals(klass)) { response(message); } else if (message instanceof JainMgcpResponseEvent) { onJainMgcpResponseEvent((JainMgcpResponseEvent) message, self, sender); } } private void fail(final int code) { // Notify observers that the event failed. final ActorRef self = self(); final String error = Integer.toString(code); final String message = "The IVR request failed with the following error code " + error; final JainIPMgcpException exception = new JainIPMgcpException(message); final IvrEndpointResponse response = new IvrEndpointResponse(exception); for (final ActorRef observer : observers) { observer.tell(response, self); } } private void response(final Object message) { final NotificationRequestResponse response = (NotificationRequestResponse) message; final ReturnCode code = response.getReturnCode(); if (!Transaction_Executed_Normally.equals(code)) { final int value = code.getValue(); fail(value); } } private void handleAsrr(final Map<String, String> parameters, int code) { if (parameters.containsKey("asrr")) { String asrr = parameters.get("asrr"); if (!StringUtils.isEmpty(asrr)) { try { asrr = new String(Hex.decodeHex(asrr.toCharArray())); } catch (DecoderException e) { logger.error("asrr parameter cannot be decoded.", e); fail(code); } } // Notify the observers that the event successfully completed. final IvrEndpointResponse result = new IvrEndpointResponse(new CollectedResult(asrr, true, code == 101)); for (final ActorRef observer : observers) { observer.tell(result, self()); } } else { logger.error("asrr parameter is missing"); fail(code); } } private void notification(final Object message) { final Notify notification = (Notify) message; final ActorRef self = self(); // Let the media server know we successfully got the notification. final NotifyResponse response = new NotifyResponse(this, Transaction_Executed_Normally); final int transaction = notification.getTransactionHandle(); response.setTransactionHandle(transaction); gateway.tell(response, self); // We are only expecting one event "operation completed" or "operation failed". final EventName[] observedEvents = notification.getObservedEvents(); if (observedEvents.length == 1) { final MgcpEvent event = observedEvents[0].getEventIdentifier(); final Map<String, String> parameters = MgcpUtil.parseParameters(event.getParms()); final int code = Integer.parseInt(parameters.get("rc")); switch (code) { case 323: // provisioning error case 326: // No digits case 327: // No speech case 328: // Spoke too long case 329: // Digit pattern not matched case 331: // Speech pattern not detected case 100: { // Success(final result) String digits = parameters.get("dc"); if (digits == null && parameters.get("asrr") != null) { handleAsrr(parameters, code); } else { final IvrEndpointResponse result = new IvrEndpointResponse( new CollectedResult(digits == null ? EMPTY_STRING : digits, AsrSignal.REQUEST_ASR.getName().equals(event.getName()), false)); for (final ActorRef observer : observers) { observer.tell(result, self); } } break; } case 101: { // Success(partial result) handleAsrr(parameters, code); break; } default: { fail(code); } } } } @Override public void postStop () { if (logger.isInfoEnabled()) { logger.info("At IVR postStop()"); } super.postStop(); } }
11,679
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CloseLink.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CloseLink.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CloseLink { public CloseLink() { super(); } }
1,074
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AbstractCreateMessage.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/AbstractCreateMessage.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @NotThreadSafe public abstract class AbstractCreateMessage { private final MediaSession session; public AbstractCreateMessage(final MediaSession session) { super(); this.session = session; } public MediaSession session() { return session; } }
1,275
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MediaGatewayInfo.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MediaGatewayInfo.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.mgcp; import java.net.InetAddress; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class MediaGatewayInfo { private final String name; // Server Info. final InetAddress ip; final int port; // Used for NAT traversal. private final boolean useNat; private final InetAddress externalIp; public MediaGatewayInfo(final String name, final InetAddress ip, final int port, final boolean useNat, final InetAddress externalIp) { super(); this.name = name; this.ip = ip; this.port = port; this.useNat = useNat; this.externalIp = externalIp; } public String name() { return name; } public InetAddress ip() { return ip; } public int port() { return port; } public boolean useNat() { return useNat; } public InetAddress externalIP() { return externalIp; } }
1,879
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MockConnection.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MockConnection.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.mgcp; import akka.actor.ActorRef; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActorContext; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.CreateConnection; import jain.protocol.ip.mgcp.message.CreateConnectionResponse; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.ModifyConnection; import jain.protocol.ip.mgcp.message.ModifyConnectionResponse; import jain.protocol.ip.mgcp.message.parms.CallIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionDescriptor; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.LocalOptionExtension; import jain.protocol.ip.mgcp.message.parms.LocalOptionValue; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.fsm.Action; import org.restcomm.connect.commons.fsm.FiniteStateMachine; import org.restcomm.connect.commons.fsm.State; import org.restcomm.connect.commons.fsm.Transition; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import scala.concurrent.duration.Duration; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * @author [email protected] (Thomas Quintana) */ public final class MockConnection extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // Finite state machine stuff. private final State uninitialized; private final State closed; private final State halfOpen; private final State open; // Special intermediate states to indicate we are waiting for a response from the media gateway // before completing a move in to a different state. private final State initializing; private final State closing; private final State openingHalfWay; private final State opening; // Special intermediate state used when waiting for a response to a modify connection request. private final State modifying; // FSM. private final FiniteStateMachine fsm; // Runtime stuff. private final ActorRef gateway; private final MediaSession session; private final NotifiedEntity agent; private final long timeout; private final List<ActorRef> observers; private ActorRef endpoint; private EndpointIdentifier endpointId; private ConnectionIdentifier connId; private ConnectionDescriptor localDesc; private ConnectionDescriptor remoteDesc; private boolean webrtc; public MockConnection (final ActorRef gateway, final MediaSession session, final NotifiedEntity agent, final long timeout) { super(); final ActorRef source = self(); // Initialize the states for the FSM. uninitialized = new State("uninitialized", null, null); closed = new State("closed", new Closed(source), null); halfOpen = new State("half open", new HalfOpen(source), null); open = new State("open", new Open(source), null); initializing = new State("initializing", new EnteringInitialization(source), new ExitingInitialization(source)); closing = new State("closing", new Closing(source), null); openingHalfWay = new State("opening halfway", new OpeningHalfWay(source), null); opening = new State("opening", new Opening(source), null); modifying = new State("modifying", new Modifying(source), null); // Initialize the main transitions for the FSM. final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(uninitialized, initializing)); transitions.add(new Transition(uninitialized, closed)); transitions.add(new Transition(closed, openingHalfWay)); transitions.add(new Transition(closed, opening)); transitions.add(new Transition(closed, modifying)); transitions.add(new Transition(halfOpen, closing)); transitions.add(new Transition(halfOpen, modifying)); transitions.add(new Transition(open, closing)); transitions.add(new Transition(open, closed)); transitions.add(new Transition(open, modifying)); // Initialize the intermediate transitions for the FSM. transitions.add(new Transition(initializing, closed)); transitions.add(new Transition(closing, closed)); transitions.add(new Transition(openingHalfWay, closed)); transitions.add(new Transition(openingHalfWay, halfOpen)); transitions.add(new Transition(opening, closed)); transitions.add(new Transition(opening, closing)); transitions.add(new Transition(opening, open)); transitions.add(new Transition(modifying, open)); transitions.add(new Transition(modifying, closing)); // Initialize transitions needed in case the media gateway // goes away. transitions.add(new Transition(modifying, closed)); // Initialize the FSM. this.fsm = new FiniteStateMachine(uninitialized, transitions); // Initialize the rest of the connection state. this.gateway = gateway; this.session = session; this.agent = agent; this.timeout = timeout; this.observers = new ArrayList<ActorRef>(); this.connId = null; this.localDesc = null; this.remoteDesc = null; this.webrtc = false; } private void observe(final Object message) { final ActorRef self = self(); final Observe request = (Observe) message; final ActorRef observer = request.observer(); if (observer != null) { observers.add(observer); observer.tell(new Observing(self), self); } } // FSM logic. @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final State state = fsm.state(); if (logger.isInfoEnabled()) { logger.info(" ********** Connection Current State: " + state.toString()); logger.info(" ********** Connection Processing Message: " + klass.getName()); } if (Observe.class.equals(klass)) { observe(message); } else if (StopObserving.class.equals(klass)) { stopObserving(message); } else if (InitializeConnection.class.equals(klass)) { fsm.transition(message, initializing); } else if (EndpointCredentials.class.equals(klass)) { fsm.transition(message, closed); } else if (OpenConnection.class.equals(klass)) { final OpenConnection request = (OpenConnection) message; if (request.descriptor() == null) { this.webrtc = request.isWebrtc(); fsm.transition(message, openingHalfWay); } else { // TODO check based on descriptor if connection is webrtc fsm.transition(message, opening); } } else if (UpdateConnection.class.equals(klass)) { fsm.transition(message, modifying); } else if (CloseConnection.class.equals(klass)) { fsm.transition(message, closing); } else if (message instanceof JainMgcpResponseEvent) { final JainMgcpResponseEvent response = (JainMgcpResponseEvent) message; final int code = response.getReturnCode().getValue(); if (code == ReturnCode.TRANSACTION_BEING_EXECUTED) { return; } else if (code == ReturnCode.TRANSACTION_EXECUTED_NORMALLY) { if (openingHalfWay.equals(state)) { fsm.transition(message, halfOpen); } else if (opening.equals(state)) { fsm.transition(message, open); } else if (closing.equals(state)) { fsm.transition(message, closed); } else if (modifying.equals(state)) { fsm.transition(message, open); } } else { if (modifying.equals(state)) { fsm.transition(message, closing); } else { fsm.transition(message, closed); } } } else if (message instanceof ReceiveTimeout) { fsm.transition(message, closed); } } private void stopObserving(final Object message) { final StopObserving request = (StopObserving) message; final ActorRef observer = request.observer(); if (observer != null) { observers.remove(observer); } } private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } protected void log(final ConnectionStateChanged.State state) { final StringBuilder buffer = new StringBuilder(); // Start printing on a new line. buffer.append("\n"); // Log the message. switch (state) { case CLOSED: { buffer.append("Closed a connection"); } case HALF_OPEN: { buffer.append("Opened a connection halfway"); } case OPEN: { buffer.append("Opened a connection"); } } if (connId != null && endpointId != null) { buffer.append(" with ID ").append(connId.toString()).append(" "); buffer.append("to an endpoint with ID ").append(endpointId.toString()); } if(logger.isDebugEnabled()) { logger.debug(buffer.toString()); } } } private final class Closed extends AbstractAction { public Closed(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { /* Stop the timer. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); // Notify the observers. final ConnectionStateChanged event = new ConnectionStateChanged(ConnectionStateChanged.State.CLOSED, connId); for (final ActorRef observer : observers) { observer.tell(event, source); } // Log the state change. log(ConnectionStateChanged.State.CLOSED); // If we timed out log it. if (message instanceof ReceiveTimeout) { logger.error("The media gateway failed to respond in the requested timout period."); } } } private abstract class AbstractOpenAction extends AbstractAction { public AbstractOpenAction(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final CreateConnectionResponse response = (CreateConnectionResponse) message; if (connId == null) { connId = response.getConnectionIdentifier(); } localDesc = response.getLocalConnectionDescriptor(); // If the end point ends with a wild card we should update it. if (endpointId.getLocalEndpointName().endsWith("$")) { endpointId = response.getSpecificEndpointIdentifier(); endpoint.tell(new UpdateEndpointId(endpointId), source); } } } private final class HalfOpen extends AbstractOpenAction { public HalfOpen(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { super.execute(message); /* Stop the timer. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); // Notify the observers. final ConnectionStateChanged event = new ConnectionStateChanged(localDesc, ConnectionStateChanged.State.HALF_OPEN, connId); for (final ActorRef observer : observers) { observer.tell(event, source); } // Log the state change. log(ConnectionStateChanged.State.HALF_OPEN); } } private final class Open extends AbstractOpenAction { public Open(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { /* Stop the timer. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); if (remoteDesc != null && remoteDesc.toString().contains("PleaseFailThisConnection")) { final CreateConnectionResponse response = (CreateConnectionResponse) message; if (connId == null) { connId = response.getConnectionIdentifier(); } fsm.transition(message, closing); return; } // Handle results from opening or modifying states. final Class<?> klass = message.getClass(); if (CreateConnectionResponse.class.equals(klass)) { super.execute(message); } else if (ModifyConnectionResponse.class.equals(klass)) { final ModifyConnectionResponse response = (ModifyConnectionResponse) message; localDesc = response.getLocalConnectionDescriptor(); } final ConnectionStateChanged event = new ConnectionStateChanged(localDesc, ConnectionStateChanged.State.OPEN, connId); for (final ActorRef observer : observers) { observer.tell(event, source); } // Log the state change. log(ConnectionStateChanged.State.OPEN); } } private final class EnteringInitialization extends AbstractAction { public EnteringInitialization(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final InitializeConnection request = (InitializeConnection) message; endpoint = request.endpoint(); if (endpoint != null) { final InviteEndpoint invite = new InviteEndpoint(); endpoint.tell(invite, source); } } } private final class ExitingInitialization extends AbstractAction { public ExitingInitialization(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final EndpointCredentials response = (EndpointCredentials) message; endpointId = response.endpointId(); } } private final class Closing extends AbstractAction { public Closing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); final DeleteConnection dlcx = new DeleteConnection(source, callId, endpointId, connId); gateway.tell(dlcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } private abstract class AbstractOpeningAction extends AbstractAction { public AbstractOpeningAction(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final OpenConnection request = (OpenConnection) message; final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); final CreateConnection crcx = new CreateConnection(source, callId, endpointId, request.mode()); remoteDesc = request.descriptor(); if (remoteDesc != null) { crcx.setRemoteConnectionDescriptor(remoteDesc); } crcx.setNotifiedEntity(agent); LocalOptionValue[] localOptions = new LocalOptionValue[] { new LocalOptionExtension("webrtc", String.valueOf(webrtc)) }; crcx.setLocalConnectionOptions(localOptions); gateway.tell(crcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } private final class OpeningHalfWay extends AbstractOpeningAction { public OpeningHalfWay(final ActorRef source) { super(source); } } private final class Opening extends AbstractOpeningAction { public Opening(final ActorRef source) { super(source); } } private final class Modifying extends AbstractAction { public Modifying(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final UpdateConnection request = (UpdateConnection) message; final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); ConnectionIdentifier requestedConnId = request.connectionIdentifier(); requestedConnId = requestedConnId==null ? connId:requestedConnId; final ModifyConnection mdcx = new ModifyConnection(source, callId, endpointId, requestedConnId); final ConnectionMode mode = request.mode(); if (mode != null) { mdcx.setMode(mode); } final ConnectionDescriptor descriptor = request.descriptor(); if (descriptor != null) { mdcx.setRemoteConnectionDescriptor(descriptor); remoteDesc = descriptor; } gateway.tell(mdcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } }
19,895
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateConferenceEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CreateConferenceEndpoint.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CreateConferenceEndpoint extends AbstractCreateMessage { private String endpointName; public CreateConferenceEndpoint(final MediaSession session) { super(session); } public CreateConferenceEndpoint(final MediaSession session, final String endpointName) { this(session); this.endpointName = endpointName; } public String endpointName() { return this.endpointName; } }
1,442
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BridgeEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/BridgeEndpoint.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.mgcp; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ public final class BridgeEndpoint extends GenericEndpoint { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); protected static final String bridgeEndpointName = "mobicents/bridge/$"; public BridgeEndpoint(final ActorRef gateway, final MediaSession session, final NotifiedEntity agent, final String domain, long timeout) { super(gateway, session, agent, new EndpointIdentifier(bridgeEndpointName, domain), timeout); } public BridgeEndpoint(ActorRef gateway, MediaSession session, NotifiedEntity agent, String domain, long timeout, String endpointName) { super(gateway, session, agent, new EndpointIdentifier(endpointName==null?bridgeEndpointName:endpointName, domain), timeout); } @Override public void postStop() { ActorRef sender = this.sender(); if(logger.isInfoEnabled()) { logger.info("Bridge: " + self().path() + " bridge id: " + this.id + " at postStop, sender: " + sender.path()); } } }
2,210
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UpdateLink.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/UpdateLink.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.mgcp; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class UpdateLink { public static enum Type { PRIMARY, SECONDARY }; private final ConnectionMode mode; private final Type type; public UpdateLink(final ConnectionMode mode, final Type type) { super(); this.mode = mode; this.type = type; } public ConnectionMode mode() { return mode; } public Type type() { return type; } }
1,480
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MgcpUtil.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MgcpUtil.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.mgcp; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.pkg.MgcpEvent; import org.apache.commons.lang.math.NumberUtils; import java.util.HashMap; import java.util.Map; /** * Created by gdubina on 23.06.17. */ public final class MgcpUtil { public static final int RETURNCODE_PARTIAL = 101; private MgcpUtil(){} public static Map<String, String> parseParameters(final String input) { final Map<String, String> parameters = new HashMap<String, String>(); final String[] tokens = input.split(" "); for (final String token : tokens) { final String[] values = token.split("="); if (values.length == 1) { parameters.put(values[0], null); } else if (values.length == 2) { parameters.put(values[0], values[1]); } } return parameters; } public static boolean isPartialNotify(EventName lastEvent){ final MgcpEvent event = lastEvent.getEventIdentifier(); final Map<String, String> parameters = MgcpUtil.parseParameters(event.getParms()); return NumberUtils.toInt(parameters.get("rc")) == RETURNCODE_PARTIAL; } }
2,051
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EndpointState.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/EndpointState.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.mgcp; /** * Represents the current state of an MGCP endpoint. * * @author Henrique Rosa ([email protected]) * */ public enum EndpointState { DESTROYED, FAILED; }
1,131
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PacketRelayEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/PacketRelayEndpoint.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.mgcp; import akka.actor.ActorRef; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; /** * @author [email protected] (Thomas Quintana) */ public final class PacketRelayEndpoint extends GenericEndpoint { public PacketRelayEndpoint(final ActorRef gateway, final MediaSession session, final NotifiedEntity entity, final String domain, long timeout) { super(gateway, session, entity, new EndpointIdentifier("mobicents/relay/$", domain), timeout); } }
1,399
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MediaGatewayResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MediaGatewayResponse.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.mgcp; import org.restcomm.connect.commons.patterns.StandardResponse; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class MediaGatewayResponse<T> extends StandardResponse<T> { public MediaGatewayResponse(final T object) { super(object); } public MediaGatewayResponse(final Throwable cause) { super(cause); } public MediaGatewayResponse(final Throwable cause, final String message) { super(cause, message); } }
1,413
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
LinkStateChanged.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/LinkStateChanged.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class LinkStateChanged { public static enum State { CLOSED, OPEN }; private final State state; private final ConnectionIdentifier connectionIdentifier; public LinkStateChanged(final State state) { this(state, null); } public LinkStateChanged(final State state, final ConnectionIdentifier connectionIdentifier) { super(); this.state = state; this.connectionIdentifier = connectionIdentifier; } public State state() { return state; } public ConnectionIdentifier connectionIdentifier() { return connectionIdentifier; } }
1,699
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
InitializeLink.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/InitializeLink.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.mgcp; import akka.actor.ActorRef; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class InitializeLink { private final ActorRef primaryEndpoint; private final ActorRef secondaryEndpoint; public InitializeLink(final ActorRef primaryEndpoint, final ActorRef secondaryEndpoint) { super(); this.primaryEndpoint = primaryEndpoint; this.secondaryEndpoint = secondaryEndpoint; } public ActorRef primaryEndpoint() { return primaryEndpoint; } public ActorRef secondaryEndpoint() { return secondaryEndpoint; } }
1,530
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateLink.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CreateLink.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CreateLink extends AbstractCreateMessage { private ConnectionIdentifier connectionIdentifier; public CreateLink(final MediaSession session) { this(session, null); } public CreateLink(final MediaSession session, ConnectionIdentifier connectionIdentifier) { super(session); this.connectionIdentifier = connectionIdentifier; } public ConnectionIdentifier connectionIdentifier(){ return connectionIdentifier; } }
1,547
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OpenLink.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/OpenLink.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class OpenLink { private final String primaryEndpointId; private final String secondaryEndpointId; private final ConnectionMode mode; public OpenLink(final ConnectionMode mode) { this(mode, null, null); } public OpenLink(final ConnectionMode mode, final String primaryEndpointId, final String secondaryEndpointId) { super(); this.mode = mode; this.primaryEndpointId = primaryEndpointId; this.secondaryEndpointId = secondaryEndpointId; } public ConnectionMode mode() { return mode; } public String primaryEndpointId() { return primaryEndpointId; } public String secondaryEndpointId() { return secondaryEndpointId; } }
1,804
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
InviteEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/InviteEndpoint.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class InviteEndpoint { public InviteEndpoint() { super(); } }
1,084
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GenericEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/GenericEndpoint.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.mgcp; import akka.actor.ActorRef; import akka.actor.ReceiveTimeout; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import scala.concurrent.duration.Duration; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ public abstract class GenericEndpoint extends RestcommUntypedActor { protected final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); protected final ActorRef gateway; protected final MediaSession session; protected final NotifiedEntity entity; protected EndpointIdentifier id; protected AtomicBoolean destroying; protected AtomicBoolean pendingDestroy; protected ActorRef pendingDestroyEndpointSender; protected DestroyEndpoint pendingDestroyEndpointMessage; protected final long timeout; protected final List<ActorRef> observers; public GenericEndpoint(final ActorRef gateway, final MediaSession session, final NotifiedEntity entity, final EndpointIdentifier id, long timeout) { super(); this.gateway = gateway; this.session = session; this.entity = entity; this.id = id; this.destroying = new AtomicBoolean(false); this.pendingDestroy = new AtomicBoolean(false); this.observers = new ArrayList<ActorRef>(1); this.timeout = timeout; } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (Observe.class.equals(klass)) { onObserve((Observe) message, self, sender); } else if (StopObserving.class.equals(klass)) { onStopObserving((StopObserving) message, self, sender); } else if (InviteEndpoint.class.equals(klass)) { final EndpointCredentials credentials = new EndpointCredentials(id); sender.tell(credentials, self); } else if (UpdateEndpointId.class.equals(klass)) { final UpdateEndpointId request = (UpdateEndpointId) message; id = request.id(); if (pendingDestroy.get()) { pendingDestroy.set(false); onDestroyEndpoint(pendingDestroyEndpointMessage, self(), pendingDestroyEndpointSender); } } else if (DestroyEndpoint.class.equals(klass)) { onDestroyEndpoint((DestroyEndpoint) message, self, sender); } else if (message instanceof JainMgcpResponseEvent) { onJainMgcpResponseEvent((JainMgcpResponseEvent) message, self, sender); } else if (ReceiveTimeout.class.equals(klass)) { onReceiveTimeout((ReceiveTimeout) message, self, sender); } } protected void onObserve(Observe message, ActorRef self, ActorRef sender) { final ActorRef observer = message.observer(); if (observer != null) { synchronized (this.observers) { this.observers.add(observer); sender.tell(new Observing(self), self); } } } protected void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) { final ActorRef observer = message.observer(); if (observer != null) { observer.tell(message, self); } } protected void onDestroyEndpoint(DestroyEndpoint message, ActorRef self, ActorRef sender) { if (!id.getLocalEndpointName().contains("$")) { if (!this.destroying.get()) { if (logger.isInfoEnabled()) { String msg = String.format("About to destroy endoint %s", id); logger.info(msg); } this.destroying.set(true); DeleteConnection dlcx = new DeleteConnection(self, this.id); this.gateway.tell(dlcx, self); // Make sure we don't wait forever getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } else { this.pendingDestroy.set(true); this.pendingDestroyEndpointSender = sender; this.pendingDestroyEndpointMessage = message; if (logger.isInfoEnabled()) { String msg = String.format("DestroyEndoint %s will be set to pending until previous transaction completes", id); logger.info(msg); } } } protected void onJainMgcpResponseEvent(JainMgcpResponseEvent message, ActorRef self, ActorRef sender) { if (this.destroying.get()) { ReturnCode returnCode = message.getReturnCode(); if (ReturnCode.TRANSACTION_EXECUTED_NORMALLY == returnCode.getValue()) { broadcast(new EndpointStateChanged(EndpointState.DESTROYED)); } else { logger.error("Could not destroy endpoint " + this.id.toString() + ". Return Code: " + returnCode.toString()); broadcast(new EndpointStateChanged(EndpointState.FAILED)); } } } protected void onReceiveTimeout(ReceiveTimeout message, ActorRef self, ActorRef sender) { logger.error("Timeout received on Endpoint " + this.id.toString()); broadcast(new EndpointStateChanged(EndpointState.FAILED)); } protected void broadcast(final Object message) { if (!this.observers.isEmpty()) { final ActorRef self = self(); for (ActorRef observer : observers) { observer.tell(message, self); } } } }
7,129
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreatePacketRelayEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CreatePacketRelayEndpoint.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CreatePacketRelayEndpoint extends AbstractCreateMessage { public CreatePacketRelayEndpoint(final MediaSession session) { super(session); } }
1,169
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DestroyEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/DestroyEndpoint.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.mgcp; import akka.actor.ActorRef; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class DestroyEndpoint { private final ActorRef endpoint; public DestroyEndpoint(final ActorRef endpoint) { super(); this.endpoint = endpoint; } public DestroyEndpoint() { this(null); } public ActorRef endpoint() { return endpoint; } }
1,333
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OpenConnection.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/OpenConnection.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.mgcp; import jain.protocol.ip.mgcp.message.parms.ConnectionDescriptor; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class OpenConnection { private final ConnectionDescriptor descriptor; private final ConnectionMode mode; private final boolean webrtc; public OpenConnection(final ConnectionDescriptor descriptor, final ConnectionMode mode, final boolean webrtc) { super(); this.descriptor = descriptor; this.mode = mode; this.webrtc = webrtc; } public OpenConnection(final ConnectionDescriptor descriptor, final ConnectionMode mode) { this(descriptor, mode, false); } public OpenConnection(final ConnectionMode mode, final boolean webrtc) { this(null, mode, webrtc); } public ConnectionDescriptor descriptor() { return descriptor; } public ConnectionMode mode() { return mode; } public boolean isWebrtc() { return webrtc; } }
1,979
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MockMediaGatewayRingingError.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MockMediaGatewayRingingError.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.mgcp; import akka.actor.ActorRef; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.NotificationRequestResponse; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.message.parms.ReturnCode; public final class MockMediaGatewayRingingError extends MockMediaGateway { protected void notificationResponse(final Object message, final ActorRef sender) { final ActorRef self = self(); final NotificationRequest rqnt = (NotificationRequest) message; EventName[] events = rqnt.getSignalRequests(); //Thread sleep for the maximum recording length to simulate recording from RMS side int sleepTime = 0; boolean failResponse = false; if (events != null && events.length > 0 && events[0].getEventIdentifier() != null) { if (events[0].getEventIdentifier().getName().equalsIgnoreCase("pr")) { //Check for the Recording Length Timer parameter if the RQNT is about PlayRecord request String[] paramsArray = ((EventName) events[0]).getEventIdentifier().getParms().split(" "); for (String param : paramsArray) { if (param.startsWith("rlt")) { sleepTime = Integer.parseInt(param.replace("rlt=", "")); } } if (sleepTime == 3600000) { //If maxLength is not set, rlt will be rlt=3600000 //In that case don't sleep at all sleepTime = 0; } } else if (events[0].getEventIdentifier().getName().equalsIgnoreCase("pa")) { //If this is a Play Audio request, check that the parameter string ends with WAV String[] paramsArray = ((EventName) events[0]).getEventIdentifier().getParms().split(" "); for (String param : paramsArray) { if (param.startsWith("an")) { String annoUrl = param.replace("an=", ""); if (!annoUrl.toLowerCase().endsWith("wav")) { failResponse = true; } //If this is a ringing.wav request, then failed response if (annoUrl.toLowerCase().contains("ringing.wav")) { failResponse = true; } } } } } System.out.println(rqnt.toString()); ReturnCode code = null; if (failResponse) { code = ReturnCode.Transient_Error; } else { code = ReturnCode.Transaction_Executed_Normally; } final JainMgcpResponseEvent response = new NotificationRequestResponse(self, code); final int transaction = rqnt.getTransactionHandle(); response.setTransactionHandle(transaction); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { } System.out.println(response.toString()); sender.tell(response, self); } }
4,026
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateBridgeEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CreateBridgeEndpoint.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CreateBridgeEndpoint extends AbstractCreateMessage { private String endpointName; public CreateBridgeEndpoint(final MediaSession session) { super(session); } public CreateBridgeEndpoint(final MediaSession session, final String endpointName) { this(session); this.endpointName = endpointName; } public String endpointName() { return this.endpointName; } }
1,435
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PlayCollect.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/PlayCollect.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.mgcp; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ @Immutable public final class PlayCollect { private final List<URI> initialPrompts; private final boolean clearDigitBuffer; private final int maxNumberOfDigits; private final int minNumberOfDigits; private final String digitPattern; private final long firstDigitTimer; private final long interDigitTimer; private final String endInputKey; private final String startInputKey; private PlayCollect(final List<URI> initialPrompts, final boolean clearDigitBuffer, final int maxNumberOfDigits, final int minNumberOfDigits, final String digitPattern, final long firstDigitTimer, final long interDigitTimer, final String endInputKey, final String startInputKey) { super(); this.initialPrompts = initialPrompts; this.clearDigitBuffer = clearDigitBuffer; this.maxNumberOfDigits = maxNumberOfDigits; this.minNumberOfDigits = minNumberOfDigits; this.digitPattern = digitPattern; this.firstDigitTimer = firstDigitTimer; this.interDigitTimer = interDigitTimer; this.endInputKey = endInputKey; this.startInputKey = startInputKey; } public static Builder builder() { return new Builder(); } public List<URI> initialPrompts() { return initialPrompts; } public boolean clearDigitBuffer() { return clearDigitBuffer; } public int maxNumberOfDigits() { return maxNumberOfDigits; } public int minNumberOfDigits() { return minNumberOfDigits; } public String digitPattern() { return digitPattern; } public long firstDigitTimer() { return firstDigitTimer; } public long interDigitTimer() { return interDigitTimer; } public String endInputKey() { return endInputKey; } public String startInputKey() {return startInputKey; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); if (!initialPrompts.isEmpty()) { buffer.append("ip="); for (int index = 0; index < initialPrompts.size(); index++) { buffer.append(initialPrompts.get(index)); if (index < initialPrompts.size() - 1) { //https://github.com/RestComm/Restcomm-Connect/issues/1988 buffer.append(","); } } } if (clearDigitBuffer) { if (buffer.length() > 0) buffer.append(" "); buffer.append("cb=").append("true"); } if (maxNumberOfDigits > 0) { if (buffer.length() > 0) buffer.append(" "); buffer.append("mx=").append(maxNumberOfDigits); } if (minNumberOfDigits > 0) { if (buffer.length() > 0) buffer.append(" "); buffer.append("mn=").append(minNumberOfDigits); } if (digitPattern != null) { if (buffer.length() > 0) buffer.append(" "); buffer.append("dp=").append(digitPattern); } if (firstDigitTimer > 0) { if (buffer.length() > 0) buffer.append(" "); buffer.append("fdt=").append(firstDigitTimer * 10); } if (interDigitTimer > 0) { if (buffer.length() > 0) buffer.append(" "); buffer.append("idt=").append(interDigitTimer * 10); } if (startInputKey != null) { if (buffer.length() > 0) buffer.append(" "); buffer.append("sik=").append(startInputKey); } if (endInputKey != null) { if (buffer.length() > 0) buffer.append(" "); buffer.append("eik=").append(endInputKey); } return buffer.toString(); } public static final class Builder { private List<URI> initialPrompts; private boolean clearDigitBuffer; private int maxNumberOfDigits; private int minNumberOfDigits; private String digitPattern; private long firstDigitTimer; private long interDigitTimer; private String endInputKey; private String startInputKey; private Builder() { super(); initialPrompts = new ArrayList<URI>(); clearDigitBuffer = false; maxNumberOfDigits = -1; minNumberOfDigits = -1; digitPattern = null; firstDigitTimer = -1; interDigitTimer = -1; endInputKey = null; startInputKey = null; } public PlayCollect build() { return new PlayCollect(initialPrompts, clearDigitBuffer, maxNumberOfDigits, minNumberOfDigits, digitPattern, firstDigitTimer, interDigitTimer, endInputKey, startInputKey); } public void addPrompt(final URI prompt) { this.initialPrompts.add(prompt); } public void setClearDigitBuffer(final boolean clearDigitBuffer) { this.clearDigitBuffer = clearDigitBuffer; } public void setMaxNumberOfDigits(final int maxNumberOfDigits) { this.maxNumberOfDigits = maxNumberOfDigits; } public void setMinNumberOfDigits(final int minNumberOfDigits) { this.minNumberOfDigits = minNumberOfDigits; } public void setDigitPattern(final String digitPattern) { this.digitPattern = digitPattern; } public void setFirstDigitTimer(final long firstDigitTimer) { this.firstDigitTimer = firstDigitTimer; } public void setInterDigitTimer(final long interDigitTimer) { this.interDigitTimer = interDigitTimer; } public void setEndInputKey(final String endInputKey) { this.endInputKey = endInputKey; } public void setStartInputKey(final String startInputKey) {this.startInputKey = startInputKey; } } }
7,163
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Link.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/Link.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.mgcp; import akka.actor.ActorRef; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActorContext; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.CreateConnection; import jain.protocol.ip.mgcp.message.CreateConnectionResponse; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.ModifyConnection; import jain.protocol.ip.mgcp.message.parms.CallIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.fsm.Action; import org.restcomm.connect.commons.fsm.FiniteStateMachine; import org.restcomm.connect.commons.fsm.State; import org.restcomm.connect.commons.fsm.Transition; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import scala.concurrent.duration.Duration; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * @author [email protected] (Thomas Quintana) */ public final class Link extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // Finite state machine stuff. private final State uninitialized; private final State closed; private final State open; // Special intermediate states to indicate we are waiting for a response from the media gateway // before completing a move in to a different state. private final State initializingPrimary; private final State initializingSecondary; private final State closingPrimary; private final State closingSecondary; private final State opening; // Special intermediate state used when waiting for a response to a modify connection request. private final State modifying; private final FiniteStateMachine fsm; // Runtime Stuff. private final ActorRef gateway; private final MediaSession session; private final NotifiedEntity agent; private final long timeout; private final List<ActorRef> observers; private ActorRef primaryEndpoint; private ActorRef secondaryEndpoint; private EndpointIdentifier primaryEndpointId; private EndpointIdentifier secondaryEndpointId; private ConnectionIdentifier primaryConnId; private ConnectionIdentifier secondaryConnId; public Link(final ActorRef gateway, final MediaSession session, final NotifiedEntity agent, final long timeout) { this(gateway, session, agent, timeout, null); } public Link(final ActorRef gateway, final MediaSession session, final NotifiedEntity agent, final long timeout, final ConnectionIdentifier overrideSecondaryConnId) { super(); final ActorRef source = self(); // Initialize the states for the FSM. uninitialized = new State("uninitialized", null, null); closed = new State("closed", new ClosedAction(source), null); open = new State("open", new OpenAction(source), null); initializingPrimary = new State("initializing primary", new InitializingPrimary(source), null); initializingSecondary = new State("initializing secondary", new EnteringInitializingSecondary(source), new ExitingInitializingSecondary(source)); closingPrimary = new State("closing primary", new ClosingPrimary(source), null); closingSecondary = new State("closing secondary", new ClosingSecondary(source), null); opening = new State("opening", new Opening(source), null); modifying = new State("modifying", new Modifying(source), null); // Initialize the main transitions for the FSM. final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(uninitialized, initializingPrimary)); transitions.add(new Transition(uninitialized, closed)); transitions.add(new Transition(closed, opening)); transitions.add(new Transition(open, closingPrimary)); transitions.add(new Transition(open, modifying)); transitions.add(new Transition(open, closed)); // Initialize the intermediate transitions for the FSM. transitions.add(new Transition(initializingPrimary, initializingSecondary)); transitions.add(new Transition(initializingPrimary, closingPrimary)); transitions.add(new Transition(initializingSecondary, closed)); transitions.add(new Transition(closingPrimary, closingSecondary)); transitions.add(new Transition(closingSecondary, closed)); transitions.add(new Transition(opening, closed)); transitions.add(new Transition(opening, open)); transitions.add(new Transition(modifying, open)); transitions.add(new Transition(modifying, closingPrimary)); // Initialize transitions needed in case the media gateway // goes away. transitions.add(new Transition(closingPrimary, closed)); transitions.add(new Transition(modifying, closed)); // Initialize the FSM. this.fsm = new FiniteStateMachine(uninitialized, transitions); // Initialize the rest of the connection state. this.gateway = gateway; this.session = session; this.agent = agent; this.timeout = timeout; this.observers = new ArrayList<ActorRef>(); this.primaryConnId = null; this.secondaryConnId = overrideSecondaryConnId; } private void observe(final Object message) { final ActorRef self = self(); final Observe request = (Observe) message; final ActorRef observer = request.observer(); if (observer != null) { observers.add(observer); observer.tell(new Observing(self), self); } } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final State state = fsm.state(); if (Observe.class.equals(klass)) { observe(message); } else if (StopObserving.class.equals(klass)) { stopObserving(message); } else if (InitializeLink.class.equals(klass)) { logger.info("Link: "+self().path()+" ,received InitializeLink message from sender: "+sender().path()); fsm.transition(message, initializingPrimary); } else if (EndpointCredentials.class.equals(klass)) { if (initializingPrimary.equals(state)) { fsm.transition(message, initializingSecondary); } else if (initializingSecondary.equals(state)) { fsm.transition(message, closed); } } else if (OpenLink.class.equals(klass)) { fsm.transition(message, opening); } else if (UpdateLink.class.equals(klass)) { if (!closed.equals(state)) fsm.transition(message, modifying); } else if (CloseLink.class.equals(klass)) { if (!closingPrimary.equals(state)) fsm.transition(message, closingPrimary); } else if (message instanceof JainMgcpResponseEvent) { final JainMgcpResponseEvent response = (JainMgcpResponseEvent) message; final int code = response.getReturnCode().getValue(); if (code == ReturnCode.TRANSACTION_BEING_EXECUTED) { return; } else if (code == ReturnCode.TRANSACTION_EXECUTED_NORMALLY) { if (opening.equals(state)) { fsm.transition(message, open); } else if (closingPrimary.equals(state)) { fsm.transition(message, closingSecondary); } else if (closingSecondary.equals(state)) { fsm.transition(message, closed); } else if (modifying.equals(state)) { fsm.transition(message, open); } } else { if (modifying.equals(state)) { fsm.transition(message, closingPrimary); } else { fsm.transition(message, closed); } } } else if (message instanceof ReceiveTimeout) { fsm.transition(message, closed); } } private void stopObserving(final Object message) { final StopObserving request = (StopObserving) message; final ActorRef observer = request.observer(); if (observer != null) { observers.remove(observer); } } private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } protected void log(final LinkStateChanged.State state) { final StringBuilder buffer = new StringBuilder(); // Start printing on a new line. buffer.append("\n"); // Log the message. switch (state) { case CLOSED: { buffer.append("Closed a link"); } case OPEN: { buffer.append("Opened a link"); } } if (primaryConnId != null && primaryEndpointId != null && secondaryConnId != null && secondaryEndpointId != null) { buffer.append(" with primary connection ID of ").append(primaryConnId.toString()); buffer.append(" secondary connection ID of ").append(secondaryConnId.toString()); buffer.append(" A primary endpoint ID of ").append(primaryEndpointId.toString()); buffer.append(" and a secondary endpoint ID of ").append(secondaryEndpointId.toString()); } logger.debug(buffer.toString()); } } private final class ClosedAction extends AbstractAction { public ClosedAction(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { /* Stop the timer. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); // Notify the observers. final LinkStateChanged event = new LinkStateChanged(LinkStateChanged.State.CLOSED, secondaryConnId); for (final ActorRef observer : observers) { observer.tell(event, source); } // Log the state change. log(LinkStateChanged.State.CLOSED); // If we timed out log it. if (message instanceof ReceiveTimeout) { logger.error("The media gateway failed to respond in the requested timout period."); } } } private final class OpenAction extends AbstractAction { public OpenAction(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { /* Stop the timer. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); /* Configure the connection and end points. */ final Class<?> klass = message.getClass(); if (CreateConnectionResponse.class.equals(klass)) { final CreateConnectionResponse response = (CreateConnectionResponse) message; if (primaryConnId == null) { primaryConnId = response.getConnectionIdentifier(); } if (primaryEndpointId.getLocalEndpointName().endsWith("$")) { primaryEndpointId = response.getSpecificEndpointIdentifier(); primaryEndpoint.tell(new UpdateEndpointId(primaryEndpointId), source); } if (secondaryConnId == null) { secondaryConnId = response.getSecondConnectionIdentifier(); } if (secondaryEndpointId.getLocalEndpointName().endsWith("$")) { secondaryEndpointId = response.getSecondEndpointIdentifier(); secondaryEndpoint.tell(new UpdateEndpointId(secondaryEndpointId), source); } } final LinkStateChanged event = new LinkStateChanged(LinkStateChanged.State.OPEN, secondaryConnId); for (final ActorRef observer : observers) { observer.tell(event, source); } // Log the state change. log(LinkStateChanged.State.CLOSED); } } private final class InitializingPrimary extends AbstractAction { public InitializingPrimary(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final InitializeLink request = (InitializeLink) message; primaryEndpoint = request.primaryEndpoint(); secondaryEndpoint = request.secondaryEndpoint(); logger.info("Link: "+self().path()+" ,state: "+fsm.state()+" ,primaryEndpoint: "+primaryEndpoint.path()+" ,secondaryEndpoint: "+secondaryEndpoint.path()); if (primaryEndpoint != null && !primaryEndpoint.isTerminated()) { primaryEndpoint.tell(new InviteEndpoint(), source); logger.info("Link: "+self().path()+" ,state: "+fsm.state()+" InviteEndpoint sent to primaryEndpoint: "+primaryEndpoint.path()); } else { logger.info("Link: "+self().path()+" ,state: "+fsm.state()+" InviteEndpoint DIDN'T sent to primaryEndpoint: "+primaryEndpoint.path()+" primaryEndpoint is Terminated: "+primaryEndpoint.isTerminated()); } } } private final class EnteringInitializingSecondary extends AbstractAction { public EnteringInitializingSecondary(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final EndpointCredentials response = (EndpointCredentials) message; primaryEndpointId = response.endpointId(); if (secondaryEndpoint != null) { secondaryEndpoint.tell(new InviteEndpoint(), source); } logger.info("Link: "+self().path()+" ,state: "+fsm.state()+" ,primaryEndpointId: "+primaryEndpointId+" ,secondaryEndpoint: "+secondaryEndpoint.path()+" secondaryEndpoint isTerminated: "+secondaryEndpoint.isTerminated()); } } private final class ExitingInitializingSecondary extends AbstractAction { public ExitingInitializingSecondary(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final EndpointCredentials response = (EndpointCredentials) message; secondaryEndpointId = response.endpointId(); } } private final class ClosingPrimary extends AbstractAction { public ClosingPrimary(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); final DeleteConnection dlcx = new DeleteConnection(source, callId, primaryEndpointId, primaryConnId); gateway.tell(dlcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } private final class ClosingSecondary extends AbstractAction { public ClosingSecondary(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { /* Stop the timer here. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); final DeleteConnection dlcx = new DeleteConnection(source, callId, secondaryEndpointId, secondaryConnId); gateway.tell(dlcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } private final class Modifying extends AbstractAction { public Modifying(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final UpdateLink request = (UpdateLink) message; final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); ModifyConnection mdcx = null; switch (request.type()) { case PRIMARY: { mdcx = new ModifyConnection(source, callId, primaryEndpointId, primaryConnId); } case SECONDARY: { mdcx = new ModifyConnection(source, callId, secondaryEndpointId, secondaryConnId); } } final ConnectionMode mode = request.mode(); if (mode != null) { mdcx.setMode(mode); } gateway.tell(mdcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } private final class Opening extends AbstractAction { public Opening(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final OpenLink request = (OpenLink) message; if(request.primaryEndpointId() != null) primaryEndpointId = new EndpointIdentifier(request.primaryEndpointId(), primaryEndpointId.getDomainName()); if(request.secondaryEndpointId() != null) secondaryEndpointId = new EndpointIdentifier(request.secondaryEndpointId(), secondaryEndpointId.getDomainName()); final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); final CreateConnection crcx = new CreateConnection(source, callId, primaryEndpointId, request.mode()); crcx.setNotifiedEntity(agent); crcx.setSecondEndpointIdentifier(secondaryEndpointId); gateway.tell(crcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } }
20,314
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GatherMockMediaGateway.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/GatherMockMediaGateway.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.mgcp; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorContext; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.JainMgcpCommandEvent; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.CreateConnectionResponse; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.DeleteConnectionResponse; import jain.protocol.ip.mgcp.message.ModifyConnection; import jain.protocol.ip.mgcp.message.ModifyConnectionResponse; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.NotificationRequestResponse; import jain.protocol.ip.mgcp.message.Notify; import jain.protocol.ip.mgcp.message.parms.ConnectionDescriptor; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import jain.protocol.ip.mgcp.pkg.MgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUPackage; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.util.RevolvingCounter; import javax.sdp.SdpFactory; import javax.sdp.SdpParseException; import javax.sdp.SessionDescription; import java.net.InetAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * @author <a href="mailto:[email protected]">Hoan HL</a> */ public class GatherMockMediaGateway extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // Session description for the mock media gateway. private static final String sdp = "v=0\n" + "o=- 1362546170756 1 IN IP4 192.168.1.100\n" + "s=Mobicents Media Server\n" + "c=IN IP4 192.168.1.100\n" + "t=0 0\n" + "m=audio 63044 RTP/AVP 97 8 0 101\n" + "a=rtpmap:97 l16/8000\n" + "a=rtpmap:8 pcma/8000\n" + "a=rtpmap:0 pcmu/8000\n" + "a=rtpmap:101 telephone-event/8000\n" + "a=fmtp:101 0-15\n"; // MediaGateway connection information. private String name; private InetAddress localIp; private int localPort; private InetAddress remoteIp; private int remotePort; // Used for NAT traversal. private boolean useNat; private InetAddress externalIp; // Used to detect dead media gateways. private long timeout; // Call agent. private NotifiedEntity agent; // Media gateway domain name. private String domain; // Runtime stuff. private RevolvingCounter requestIdPool; private RevolvingCounter sessionIdPool; private RevolvingCounter transactionIdPool; private RevolvingCounter connectionIdPool; private RevolvingCounter endpointIdPool; private static Map<MediaSession, ActorRef> endpoints; private static Map<MediaSession, ActorRef> links; private static Map<MediaSession, ActorRef> connections; private ActorSystem system; public GatherMockMediaGateway() { super(); endpoints = new ConcurrentHashMap<MediaSession, ActorRef>(); links = new ConcurrentHashMap<MediaSession, ActorRef>(); connections = new ConcurrentHashMap<MediaSession, ActorRef>(); system = context().system(); } public static Map<MediaSession, ActorRef> getEndpointsMap() { return endpoints; } public static Map<MediaSession, ActorRef> getConnections() { return connections; } public static Map<MediaSession, ActorRef> getLinks() { return links; } private ActorRef getConnection(final Object message) { final CreateConnection request = (CreateConnection) message; final MediaSession session = request.session(); final ActorRef gateway = self(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new MockConnection(gateway, session, agent, timeout); } }); ActorRef connection = system.actorOf(props); connections.put(session, connection); return connection; } private ActorRef getBridgeEndpoint(final Object message) { final CreateBridgeEndpoint request = (CreateBridgeEndpoint) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new BridgeEndpoint(gateway, session, agent, domain, timeout); } }); ActorRef bridgeEndpoint = system.actorOf(props); endpoints.put(session, bridgeEndpoint); return bridgeEndpoint; } private ActorRef getConferenceEndpoint(final Object message) { final ActorRef gateway = self(); final CreateConferenceEndpoint request = (CreateConferenceEndpoint) message; final MediaSession session = request.session(); final String endpointName = request.endpointName(); Props props = null; props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new ConferenceEndpoint(gateway, session, agent, domain, timeout, endpointName); } }); ActorRef conferenceEndpoint = system.actorOf(props); endpoints.put(session, conferenceEndpoint); return conferenceEndpoint; } private MediaGatewayInfo getInfo(final Object message) { return new MediaGatewayInfo(name, remoteIp, remotePort, useNat, externalIp); } private ActorRef getIvrEndpoint(final Object message) { final ActorRef gateway = self(); final CreateIvrEndpoint request = (CreateIvrEndpoint) message; final MediaSession session = request.session(); final String endpointName = request.endpointName(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new IvrEndpoint(gateway, session, agent, domain, timeout, endpointName); } }); ActorRef ivrEndpoint = system.actorOf(props); endpoints.put(session, ivrEndpoint); return ivrEndpoint; } private ActorRef getLink(final Object message) { final CreateLink request = (CreateLink) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Link(gateway, session, agent, timeout); } }); ActorRef link = system.actorOf(props); links.put(session, link); return link; } private ActorRef getPacketRelayEndpoint(final Object message) { final ActorRef gateway = self(); final CreatePacketRelayEndpoint request = (CreatePacketRelayEndpoint) message; final MediaSession session = request.session(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new PacketRelayEndpoint(gateway, session, agent, domain, timeout); } }); ActorRef packetRelayEndpoint = system.actorOf(props); endpoints.put(session, packetRelayEndpoint); return packetRelayEndpoint; } private MediaSession getSession() { return new MediaSession((int) sessionIdPool.get()); } private void powerOff(final Object message) { // Make sure we don't leave anything behind. name = null; localIp = null; localPort = 0; remoteIp = null; remotePort = 0; useNat = false; externalIp = null; timeout = 0; agent = null; domain = null; requestIdPool = null; sessionIdPool = null; transactionIdPool = null; } private void powerOn(final Object message) { final PowerOnMediaGateway request = (PowerOnMediaGateway) message; name = request.getName(); localIp = request.getLocalIp(); localPort = request.getLocalPort(); remoteIp = request.getRemoteIp(); remotePort = request.getRemotePort(); useNat = request.useNat(); externalIp = request.getExternalIp(); timeout = request.getTimeout(); agent = new NotifiedEntity("restcomm", localIp.getHostAddress(), localPort); domain = new StringBuilder().append(remoteIp.getHostAddress()).append(":").append(remotePort).toString(); connectionIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); endpointIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); requestIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); sessionIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); transactionIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); } @Override public void onReceive(final Object message) throws Exception { final UntypedActorContext context = getContext(); final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (PowerOnMediaGateway.class.equals(klass)) { powerOn(message); } else if (PowerOffMediaGateway.class.equals(klass)) { powerOff(message); } else if (GetMediaGatewayInfo.class.equals(klass)) { sender.tell(new MediaGatewayResponse<MediaGatewayInfo>(getInfo(message)), sender); } else if (CreateConnection.class.equals(klass)) { sender.tell(new MediaGatewayResponse<ActorRef>(getConnection(message)), self); } else if (CreateLink.class.equals(klass)) { sender.tell(new MediaGatewayResponse<ActorRef>(getLink(message)), self); } else if (CreateMediaSession.class.equals(klass)) { sender.tell(new MediaGatewayResponse<MediaSession>(getSession()), self); } else if (CreateBridgeEndpoint.class.equals(klass)) { final ActorRef endpoint = getBridgeEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreatePacketRelayEndpoint.class.equals(klass)) { final ActorRef endpoint = getPacketRelayEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreateIvrEndpoint.class.equals(klass)) { final ActorRef endpoint = getIvrEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreateConferenceEndpoint.class.equals(klass)) { final ActorRef endpoint = getConferenceEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (DestroyConnection.class.equals(klass)) { final DestroyConnection request = (DestroyConnection) message; connections.values().remove(request.connection()); context.stop(request.connection()); } else if (DestroyLink.class.equals(klass)) { final DestroyLink request = (DestroyLink) message; links.values().remove(request.link()); context.stop(request.link()); } else if (DestroyEndpoint.class.equals(klass)) { final DestroyEndpoint request = (DestroyEndpoint) message; endpoints.values().remove(request.endpoint()); context.stop(request.endpoint()); } else if (message instanceof JainMgcpCommandEvent) { send(message, sender); } else if (message instanceof JainMgcpResponseEvent) { send(message); } } private void createConnection(final Object message, final ActorRef sender) { final ActorRef self = self(); final jain.protocol.ip.mgcp.message.CreateConnection crcx = (jain.protocol.ip.mgcp.message.CreateConnection) message; System.out.println(crcx.toString()); // Create a response. StringBuilder buffer = new StringBuilder(); buffer.append(connectionIdPool.get()); ConnectionIdentifier connId = new ConnectionIdentifier(buffer.toString()); final ReturnCode code = ReturnCode.Transaction_Executed_Normally; final CreateConnectionResponse response = new CreateConnectionResponse(self, code, connId); // Create a new end point id if necessary. EndpointIdentifier endpointId = crcx.getEndpointIdentifier(); String endpointName = endpointId.getLocalEndpointName(); if (endpointName.endsWith("$")) { final String[] tokens = endpointName.split("/"); final String type = tokens[1]; buffer = new StringBuilder(); buffer.append("mobicents/").append(type).append("/"); buffer.append(endpointIdPool.get()); endpointId = new EndpointIdentifier(buffer.toString(), domain); } response.setSpecificEndpointIdentifier(endpointId); // Create a new secondary end point id if necessary. EndpointIdentifier secondaryEndpointId = crcx.getSecondEndpointIdentifier(); if (secondaryEndpointId != null) { buffer = new StringBuilder(); buffer.append(connectionIdPool.get()); connId = new ConnectionIdentifier(buffer.toString()); response.setSecondConnectionIdentifier(connId); endpointName = secondaryEndpointId.getLocalEndpointName(); if (endpointName.endsWith("$")) { final String[] tokens = endpointName.split("/"); final String type = tokens[1]; buffer = new StringBuilder(); buffer.append("mobicents/").append(type).append("/"); buffer.append(endpointIdPool.get()); secondaryEndpointId = new EndpointIdentifier(buffer.toString(), domain); } response.setSecondEndpointIdentifier(secondaryEndpointId); } final ConnectionDescriptor descriptor = new ConnectionDescriptor(sdp); response.setLocalConnectionDescriptor(descriptor); final int transaction = crcx.getTransactionHandle(); response.setTransactionHandle(transaction); System.out.println(response.toString()); sender.tell(response, self); } private void modifyConnection(final Object message, final ActorRef sender) { final ActorRef self = self(); final ModifyConnection mdcx = (ModifyConnection) message; System.out.println(mdcx.toString()); ReturnCode code; SessionDescription sessionDescription = null; boolean isNonValidSdp = false; if (mdcx.getRemoteConnectionDescriptor()!=null) { try { sessionDescription = SdpFactory.getInstance().createSessionDescription(mdcx.getRemoteConnectionDescriptor().toString()); isNonValidSdp = sessionDescription.getSessionName().getValue().contains("NonValidSDP"); } catch (SdpParseException e) { logger.error("Error while trying to get SDP from MDCX"); } } if (sessionDescription != null && isNonValidSdp) { code = ReturnCode.Protocol_Error; final ModifyConnectionResponse response = new ModifyConnectionResponse(self, code); final int transaction = mdcx.getTransactionHandle(); response.setTransactionHandle(transaction); System.out.println(response.toString()); sender.tell(response, self); } else { code = ReturnCode.Transaction_Executed_Normally; final ModifyConnectionResponse response = new ModifyConnectionResponse(self, code); final ConnectionDescriptor descriptor = new ConnectionDescriptor(sdp); response.setLocalConnectionDescriptor(descriptor); final int transaction = mdcx.getTransactionHandle(); response.setTransactionHandle(transaction); System.out.println(response.toString()); sender.tell(response, self); } } private void deleteConnection(final Object message, final ActorRef sender) { final ActorRef self = self(); final DeleteConnection dlcx = (DeleteConnection) message; System.out.println(dlcx.toString()); final ReturnCode code = ReturnCode.Transaction_Executed_Normally; final DeleteConnectionResponse response = new DeleteConnectionResponse(self, code); final int transaction = dlcx.getTransactionHandle(); response.setTransactionHandle(transaction); System.out.println(response.toString()); sender.tell(response, self); } protected void notificationResponse(final Object message, final ActorRef sender) { final ActorRef self = self(); final NotificationRequest rqnt = (NotificationRequest) message; EventName[] events = rqnt.getSignalRequests(); //Thread sleep for the maximum recording length to simulate recording from RMS side int sleepTime = 0; boolean failResponse = false; if (events != null && events.length > 0 && events[0].getEventIdentifier() != null) { if (events[0].getEventIdentifier().getName().equalsIgnoreCase("pr")) { //Check for the Recording Length Timer parameter if the RQNT is about PlayRecord request String[] paramsArray = ((EventName) events[0]).getEventIdentifier().getParms().split(" "); for (String param : paramsArray) { if (param.startsWith("rlt")) { sleepTime = Integer.parseInt(param.replace("rlt=", "")); } } if (sleepTime == 36000) { //If maxLength is not set, rlt will be rlt=3600000 //In that case don't sleep at all sleepTime = 0; } } else if (events[0].getEventIdentifier().getName().equalsIgnoreCase("pa")) { //If this is a Play Audio request, check that the parameter string ends with WAV String[] paramsArray = ((EventName) events[0]).getEventIdentifier().getParms().split(" "); for (String param : paramsArray) { if (param.startsWith("an")) { String annoUrl = param.replace("an=", ""); if (!annoUrl.toLowerCase().endsWith("wav")) { failResponse = true; } } } } } System.out.println(rqnt.toString()); ReturnCode code = null; if (failResponse) { code = ReturnCode.Transient_Error; } else { code = ReturnCode.Transaction_Executed_Normally; } final JainMgcpResponseEvent response = new NotificationRequestResponse(self, code); final int transaction = rqnt.getTransactionHandle(); response.setTransactionHandle(transaction); try { Thread.sleep(sleepTime*10); } catch (InterruptedException e) { } logger.info("About to send MockMediaGateway response: "+response.toString()); sender.tell(response, self); } private void notify(final Object message, final ActorRef sender) { final ActorRef self = self(); final NotificationRequest request = (NotificationRequest) message; final MgcpEvent event = AUMgcpEvent.auoc.withParm("rc=100 dc=1"); final EventName[] events = {new EventName(AUPackage.AU, event)}; final Notify notify = new Notify(this, request.getEndpointIdentifier(), request.getRequestIdentifier(), events); notify.setTransactionHandle((int) transactionIdPool.get()); System.out.println(notify.toString()); sender.tell(notify, self); } private void respond(final Object message, final ActorRef sender) { final Class<?> klass = message.getClass(); if (jain.protocol.ip.mgcp.message.CreateConnection.class.equals(klass)) { createConnection(message, sender); } else if (ModifyConnection.class.equals(klass)) { modifyConnection(message, sender); } else if (DeleteConnection.class.equals(klass)) { deleteConnection(message, sender); } else if (NotificationRequest.class.equals(klass)) { notificationResponse(message, sender); } } private void send(final Object message, final ActorRef sender) { final JainMgcpCommandEvent command = (JainMgcpCommandEvent) message; final int transactionId = (int) transactionIdPool.get(); command.setTransactionHandle(transactionId); respond(message, sender); } private void send(final Object message) { final JainMgcpResponseEvent response = (JainMgcpResponseEvent) message; System.out.println(response.toString()); } }
22,798
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DestroyConnection.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/DestroyConnection.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.mgcp; import akka.actor.ActorRef; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class DestroyConnection { private final ActorRef connection; public DestroyConnection(final ActorRef connection) { super(); this.connection = connection; } public ActorRef connection() { return connection; } }
1,291
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CloseConnection.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CloseConnection.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CloseConnection { public CloseConnection() { super(); } }
1,088
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateIvrEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CreateIvrEndpoint.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CreateIvrEndpoint extends AbstractCreateMessage { private String endpointName; public CreateIvrEndpoint(final MediaSession session) { super(session); } public CreateIvrEndpoint(final MediaSession session, final String endpointName) { this(session); this.endpointName = endpointName; } public String endpointName(){ return endpointName; } }
1,413
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StopEndpoint.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/StopEndpoint.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.mgcp; import jain.protocol.ip.mgcp.pkg.MgcpEvent; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class StopEndpoint { private MgcpEvent event; public StopEndpoint(MgcpEvent event) { super(); this.event = event; } public MgcpEvent getEvent() { return this.event; } }
1,267
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Play.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/Play.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.mgcp; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class Play { private final List<URI> announcements; private final int iterations; public Play(final List<URI> announcements, final int iterations) { super(); this.announcements = announcements; this.iterations = iterations; } public Play(final URI announcement, final int iterations) { super(); this.announcements = new ArrayList<URI>(); announcements.add(announcement); this.iterations = iterations; } public List<URI> announcements() { return announcements; } public int iterations() { return iterations; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); if (!announcements.isEmpty()) { buffer.append("an="); for (int index = 0; index < announcements.size(); index++) { buffer.append(announcements.get(index)); if (index < announcements.size() - 1) { buffer.append(";"); } } if (iterations > 0) { buffer.append(" "); buffer.append("it=").append(iterations); } } return buffer.toString(); } }
2,333
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GetMediaGatewayInfo.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/GetMediaGatewayInfo.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class GetMediaGatewayInfo { public GetMediaGatewayInfo() { super(); } }
1,094
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateConnection.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CreateConnection.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CreateConnection extends AbstractCreateMessage { public CreateConnection(final MediaSession session) { super(session); } }
1,151
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UpdateConnection.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/UpdateConnection.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import jain.protocol.ip.mgcp.message.parms.ConnectionDescriptor; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class UpdateConnection { private final ConnectionDescriptor descriptor; private final ConnectionMode mode; private final ConnectionIdentifier connectionIdentifier; public UpdateConnection(final ConnectionDescriptor descriptor, final ConnectionMode mode, final ConnectionIdentifier connectionIdentifier) { super(); this.descriptor = descriptor; this.mode = mode; this.connectionIdentifier = connectionIdentifier; } public UpdateConnection(final ConnectionDescriptor descriptor, final ConnectionMode mode) { this(descriptor, mode, null); } public UpdateConnection(final ConnectionDescriptor descriptor) { this(descriptor, null); } public UpdateConnection(final ConnectionMode mode) { this(null, mode); } public ConnectionDescriptor descriptor() { return descriptor; } public ConnectionMode mode() { return mode; } public ConnectionIdentifier connectionIdentifier() { return connectionIdentifier; } }
2,249
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IvrEndpointResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/IvrEndpointResponse.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.mgcp; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author [email protected] (Thomas Quintana) */ public class IvrEndpointResponse<T> extends StandardResponse<T> { public IvrEndpointResponse(final T object) { super(object); } public IvrEndpointResponse(final Throwable cause) { super(cause); } public IvrEndpointResponse(final Throwable cause, final String message) { super(cause, message); } }
1,321
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Connection.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/Connection.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.mgcp; import akka.actor.ActorRef; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActorContext; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.CreateConnection; import jain.protocol.ip.mgcp.message.CreateConnectionResponse; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.ModifyConnection; import jain.protocol.ip.mgcp.message.ModifyConnectionResponse; import jain.protocol.ip.mgcp.message.parms.CallIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionDescriptor; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.ConnectionMode; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.LocalOptionExtension; import jain.protocol.ip.mgcp.message.parms.LocalOptionValue; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.fsm.Action; import org.restcomm.connect.commons.fsm.FiniteStateMachine; import org.restcomm.connect.commons.fsm.State; import org.restcomm.connect.commons.fsm.Transition; import org.restcomm.connect.commons.patterns.Observe; import org.restcomm.connect.commons.patterns.Observing; import org.restcomm.connect.commons.patterns.StopObserving; import scala.concurrent.duration.Duration; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; /** * @author [email protected] (Thomas Quintana) */ public final class Connection extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // Finite state machine stuff. private final State uninitialized; private final State closed; private final State halfOpen; private final State open; // Special intermediate states to indicate we are waiting for a response from the media gateway // before completing a move in to a different state. private final State initializing; private final State closing; private final State openingHalfWay; private final State opening; // Special intermediate state used when waiting for a response to a modify connection request. private final State modifying; // FSM. private final FiniteStateMachine fsm; // Runtime stuff. private final ActorRef gateway; private final MediaSession session; private final NotifiedEntity agent; private final long timeout; private final List<ActorRef> observers; private ActorRef endpoint; private EndpointIdentifier endpointId; private ConnectionIdentifier connId; private ConnectionIdentifier requestedConnId; private ConnectionDescriptor localDesc; private ConnectionDescriptor remoteDesc; private boolean webrtc; public Connection(final ActorRef gateway, final MediaSession session, final NotifiedEntity agent, final long timeout) { super(); final ActorRef source = self(); // Initialize the states for the FSM. uninitialized = new State("uninitialized", null, null); closed = new State("closed", new Closed(source), null); halfOpen = new State("half open", new HalfOpen(source), null); open = new State("open", new Open(source), null); initializing = new State("initializing", new EnteringInitialization(source), new ExitingInitialization(source)); closing = new State("closing", new Closing(source), null); openingHalfWay = new State("opening halfway", new OpeningHalfWay(source), null); opening = new State("opening", new Opening(source), null); modifying = new State("modifying", new Modifying(source), null); // Initialize the main transitions for the FSM. final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(uninitialized, initializing)); transitions.add(new Transition(uninitialized, closed)); transitions.add(new Transition(closed, openingHalfWay)); transitions.add(new Transition(closed, opening)); transitions.add(new Transition(closed, modifying)); transitions.add(new Transition(halfOpen, closing)); transitions.add(new Transition(halfOpen, modifying)); transitions.add(new Transition(open, closing)); transitions.add(new Transition(open, closed)); transitions.add(new Transition(open, modifying)); // Initialize the intermediate transitions for the FSM. transitions.add(new Transition(initializing, closed)); transitions.add(new Transition(closing, closed)); transitions.add(new Transition(openingHalfWay, closed)); transitions.add(new Transition(openingHalfWay, halfOpen)); transitions.add(new Transition(opening, closed)); transitions.add(new Transition(opening, open)); transitions.add(new Transition(modifying, open)); transitions.add(new Transition(modifying, closing)); // Initialize transitions needed in case the media gateway // goes away. transitions.add(new Transition(modifying, closed)); // Initialize the FSM. this.fsm = new FiniteStateMachine(uninitialized, transitions); // Initialize the rest of the connection state. this.gateway = gateway; this.session = session; this.agent = agent; this.timeout = timeout; this.observers = new ArrayList<ActorRef>(); this.connId = null; this.localDesc = null; this.remoteDesc = null; this.webrtc = false; } private void observe(final Object message) { final ActorRef self = self(); final Observe request = (Observe) message; final ActorRef observer = request.observer(); if (observer != null) { observers.add(observer); observer.tell(new Observing(self), self); } } // FSM logic. @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final State state = fsm.state(); if (logger.isInfoEnabled()) { logger.info(" ********** Connection Current State: " + state.toString()); logger.info(" ********** Connection Processing Message: " + klass.getName()); } if (Observe.class.equals(klass)) { observe(message); } else if (StopObserving.class.equals(klass)) { stopObserving(message); } else if (InitializeConnection.class.equals(klass)) { fsm.transition(message, initializing); } else if (EndpointCredentials.class.equals(klass)) { fsm.transition(message, closed); } else if (OpenConnection.class.equals(klass)) { final OpenConnection request = (OpenConnection) message; if (request.descriptor() == null) { this.webrtc = request.isWebrtc(); fsm.transition(message, openingHalfWay); } else { // TODO check based on descriptor if connection is webrtc fsm.transition(message, opening); } } else if (UpdateConnection.class.equals(klass)) { fsm.transition(message, modifying); } else if (CloseConnection.class.equals(klass)) { fsm.transition(message, closing); } else if (message instanceof JainMgcpResponseEvent) { final JainMgcpResponseEvent response = (JainMgcpResponseEvent) message; final int code = response.getReturnCode().getValue(); if (code == ReturnCode.TRANSACTION_BEING_EXECUTED) { return; } else if (code == ReturnCode.TRANSACTION_EXECUTED_NORMALLY) { if (openingHalfWay.equals(state)) { fsm.transition(message, halfOpen); } else if (opening.equals(state)) { fsm.transition(message, open); } else if (closing.equals(state)) { fsm.transition(message, closed); } else if (modifying.equals(state)) { fsm.transition(message, open); } } else { String err = String.format( "MGCP Transaction did not executed normally: session: %s | endpointId: %s | requestedConnId: %s | connId: %s", session.id() + "", endpointId == null ? "null" : endpointId.getLocalEndpointName(), requestedConnId, connId); logger.error(err); if (modifying.equals(state)) { fsm.transition(message, closing); } else { fsm.transition(message, closed); } } } else if (message instanceof ReceiveTimeout) { fsm.transition(message, closed); } } private void stopObserving(final Object message) { final StopObserving request = (StopObserving) message; final ActorRef observer = request.observer(); if (observer != null) { observers.remove(observer); } } private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } protected void log(final ConnectionStateChanged.State state) { final StringBuilder buffer = new StringBuilder(); // Start printing on a new line. buffer.append("\n"); // Log the message. switch (state) { case CLOSED: { buffer.append("Closed a connection"); } case HALF_OPEN: { buffer.append("Opened a connection halfway"); } case OPEN: { buffer.append("Opened a connection"); } } if (connId != null && endpointId != null) { buffer.append(" with ID ").append(connId.toString()).append(" "); buffer.append("to an endpoint with ID ").append(endpointId.toString()); } if(logger.isDebugEnabled()) { logger.debug(buffer.toString()); } } } private final class Closed extends AbstractAction { public Closed(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { /* Stop the timer. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); // Notify the observers. final ConnectionStateChanged event = new ConnectionStateChanged(ConnectionStateChanged.State.CLOSED, connId); for (final ActorRef observer : observers) { observer.tell(event, source); } // Log the state change. log(ConnectionStateChanged.State.CLOSED); // If we timed out log it. if (message instanceof ReceiveTimeout) { String err = String.format( "The media gateway failed to respond in the requested timout period. session: %s | endpointId: %s | requestedConnId: %s | connId: %s", session.id() + "", endpointId == null ? "null" : endpointId.getLocalEndpointName(), requestedConnId, connId); logger.error(err); } } } private abstract class AbstractOpenAction extends AbstractAction { public AbstractOpenAction(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final CreateConnectionResponse response = (CreateConnectionResponse) message; if (connId == null) { connId = response.getConnectionIdentifier(); } localDesc = response.getLocalConnectionDescriptor(); // If the end point ends with a wild card we should update it. if (endpointId.getLocalEndpointName().endsWith("$")) { endpointId = response.getSpecificEndpointIdentifier(); endpoint.tell(new UpdateEndpointId(endpointId), source); } } } private final class HalfOpen extends AbstractOpenAction { public HalfOpen(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { super.execute(message); /* Stop the timer. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); // Notify the observers. final ConnectionStateChanged event = new ConnectionStateChanged(localDesc, ConnectionStateChanged.State.HALF_OPEN, connId); for (final ActorRef observer : observers) { observer.tell(event, source); } // Log the state change. log(ConnectionStateChanged.State.HALF_OPEN); } } private final class Open extends AbstractOpenAction { public Open(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { /* Stop the timer. */ final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); // Handle results from opening or modifying states. final Class<?> klass = message.getClass(); if (CreateConnectionResponse.class.equals(klass)) { super.execute(message); } else if (ModifyConnectionResponse.class.equals(klass)) { final ModifyConnectionResponse response = (ModifyConnectionResponse) message; localDesc = response.getLocalConnectionDescriptor(); } final ConnectionStateChanged event = new ConnectionStateChanged(localDesc, ConnectionStateChanged.State.OPEN, connId); for (final ActorRef observer : observers) { observer.tell(event, source); } // Log the state change. log(ConnectionStateChanged.State.OPEN); } } private final class EnteringInitialization extends AbstractAction { public EnteringInitialization(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final InitializeConnection request = (InitializeConnection) message; endpoint = request.endpoint(); if (endpoint != null) { final InviteEndpoint invite = new InviteEndpoint(); endpoint.tell(invite, source); } } } private final class ExitingInitialization extends AbstractAction { public ExitingInitialization(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final EndpointCredentials response = (EndpointCredentials) message; endpointId = response.endpointId(); } } private final class Closing extends AbstractAction { public Closing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); final DeleteConnection dlcx = new DeleteConnection(source, callId, endpointId, connId); gateway.tell(dlcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } private abstract class AbstractOpeningAction extends AbstractAction { public AbstractOpeningAction(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final OpenConnection request = (OpenConnection) message; final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); final CreateConnection crcx = new CreateConnection(source, callId, endpointId, request.mode()); remoteDesc = request.descriptor(); if (remoteDesc != null) { crcx.setRemoteConnectionDescriptor(remoteDesc); } crcx.setNotifiedEntity(agent); LocalOptionValue[] localOptions = new LocalOptionValue[] { new LocalOptionExtension("webrtc", String.valueOf(webrtc)) }; crcx.setLocalConnectionOptions(localOptions); gateway.tell(crcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } private final class OpeningHalfWay extends AbstractOpeningAction { public OpeningHalfWay(final ActorRef source) { super(source); } } private final class Opening extends AbstractOpeningAction { public Opening(final ActorRef source) { super(source); } } private final class Modifying extends AbstractAction { public Modifying(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final UpdateConnection request = (UpdateConnection) message; final String sessionId = Integer.toString(session.id()); final CallIdentifier callId = new CallIdentifier(sessionId); requestedConnId = request.connectionIdentifier(); requestedConnId = requestedConnId==null ? connId:requestedConnId; final ModifyConnection mdcx = new ModifyConnection(source, callId, endpointId, requestedConnId); final ConnectionMode mode = request.mode(); if (mode != null) { mdcx.setMode(mode); } final ConnectionDescriptor descriptor = request.descriptor(); if (descriptor != null) { mdcx.setRemoteConnectionDescriptor(descriptor); remoteDesc = descriptor; } gateway.tell(mdcx, source); // Make sure we don't wait for a response indefinitely. getContext().setReceiveTimeout(Duration.create(timeout, TimeUnit.MILLISECONDS)); } } }
20,119
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EndpointStateChanged.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/EndpointStateChanged.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.mgcp; import org.apache.http.annotation.Immutable; /** * Message broadcast by an MGCP Endpoint to all observers.<br> * Occurs when the state of the endpoint changes. * * @author Henrique Rosa ([email protected]) * */ @Immutable public class EndpointStateChanged { private final EndpointState state; public EndpointStateChanged(EndpointState state) { this.state = state; } public EndpointState getState() { return state; } }
1,429
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PowerOnMediaGateway.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/PowerOnMediaGateway.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.mgcp; import akka.actor.ActorRef; import jain.protocol.ip.mgcp.JainMgcpProvider; import jain.protocol.ip.mgcp.JainMgcpStack; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import java.net.InetAddress; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class PowerOnMediaGateway { // MediaGateway connection information. private final String name; private final InetAddress localIp; private final int localPort; private final InetAddress remoteIp; private final int remotePort; // Used for NAT traversal. private final boolean useNat; private final InetAddress externalIp; // Used to detect dead media gateways. private final long timeout; private final JainMgcpStack stack; private final JainMgcpProvider provider; private final ActorRef monitoringService; public PowerOnMediaGateway(final String name, final InetAddress localIp, final int localPort, final InetAddress remoteIp, final int remotePort, final boolean useNat, final InetAddress externalIp, final long timeout, final JainMgcpStack stack, final JainMgcpProvider provider, final ActorRef monitoringService) { super(); this.name = name; this.localIp = localIp; this.localPort = localPort; this.remoteIp = remoteIp; this.remotePort = remotePort; this.useNat = useNat; this.externalIp = externalIp; this.timeout = timeout; this.stack = stack; this.provider = provider; this.monitoringService = monitoringService; } public static Builder builder() { return new Builder(); } public String getName() { return name; } public InetAddress getLocalIp() { return localIp; } public int getLocalPort() { return localPort; } public InetAddress getRemoteIp() { return remoteIp; } public int getRemotePort() { return remotePort; } public boolean useNat() { return useNat; } public InetAddress getExternalIp() { return externalIp; } public long getTimeout() { return timeout; } public JainMgcpStack getStack() { return stack; } public JainMgcpProvider getProvider() { return provider; } public ActorRef getMonitoringService () { return monitoringService; } public static final class Builder { private String name; private InetAddress localIp; private int localPort; private InetAddress remoteIp; private int remotePort; private boolean useNat; private InetAddress externalIp; private long timeout; private JainMgcpStack stack; private JainMgcpProvider provider; private ActorRef monitoringService; private Builder() { super(); } public PowerOnMediaGateway build() { return new PowerOnMediaGateway(name, localIp, localPort, remoteIp, remotePort, useNat, externalIp, timeout, stack, provider, monitoringService); } public void setName(final String name) { this.name = name; } public void setLocalIP(final InetAddress localIp) { this.localIp = localIp; } public void setLocalPort(final int localPort) { this.localPort = localPort; } public void setRemoteIP(final InetAddress remoteIp) { this.remoteIp = remoteIp; } public void setRemotePort(final int remotePort) { this.remotePort = remotePort; } public void setUseNat(final boolean useNat) { this.useNat = useNat; } public void setExternalIP(final InetAddress externalIp) { this.externalIp = externalIp; } public void setTimeout(final long timeout) { this.timeout = timeout; } public void setStack(JainMgcpStack stack) { this.stack = stack; } public void setProvider(JainMgcpProvider provider) { this.provider = provider; } public void setMonitoringService (ActorRef monitoringService) { this.monitoringService = monitoringService; } } }
5,214
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateMediaSession.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CreateMediaSession.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class CreateMediaSession { public CreateMediaSession() { super(); } }
1,093
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UpdateEndpointId.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/UpdateEndpointId.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.mgcp; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class UpdateEndpointId { private final EndpointIdentifier id; public UpdateEndpointId(final EndpointIdentifier id) { super(); this.id = id; } public EndpointIdentifier id() { return id; } }
1,306
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MediaSession.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MediaSession.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class MediaSession { private final int id; public MediaSession(final int id) { super(); this.id = id; } public int id() { return id; } }
1,189
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PowerOffMediaGateway.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/PowerOffMediaGateway.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class PowerOffMediaGateway { public PowerOffMediaGateway() { super(); } }
1,096
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MockMediaGatewayConferenceLinkCreationError.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MockMediaGatewayConferenceLinkCreationError.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.mgcp; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.message.CreateConnectionResponse; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.ReturnCode; public final class MockMediaGatewayConferenceLinkCreationError extends MockMediaGateway { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); @Override protected void createConnection (final Object message, final ActorRef sender) { final jain.protocol.ip.mgcp.message.CreateConnection crcx = (jain.protocol.ip.mgcp.message.CreateConnection) message; if(logger.isInfoEnabled()) logger.info("createConnection: " +crcx.toString()); // check if its a conference and call link request if(crcx.getSecondEndpointIdentifier() != null && crcx.getSecondEndpointIdentifier().getLocalEndpointName() != null && crcx.getSecondEndpointIdentifier().getLocalEndpointName().contains("cnf")){ // if yes then fail this connection request if(logger.isInfoEnabled()) logger.info("got conference and call link request, will fail it! with error code Endpoint_Unknown"); StringBuilder buffer = new StringBuilder(); buffer.append(connectionIdPool.get()); ConnectionIdentifier connId = new ConnectionIdentifier(buffer.toString()); sender.tell(new CreateConnectionResponse(self(), ReturnCode.Endpoint_Unknown, connId), self()); }else { // if not then let daddy proceed with existing mocked mechanism. super.createConnection(message, sender); } } }
2,563
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConnectionStateChanged.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/ConnectionStateChanged.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.mgcp; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import jain.protocol.ip.mgcp.message.parms.ConnectionDescriptor; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class ConnectionStateChanged { public static enum State { CLOSED, HALF_OPEN, OPEN }; private final ConnectionDescriptor descriptor; private final State state; private ConnectionIdentifier connectionIdentifier; public ConnectionStateChanged(final ConnectionDescriptor descriptor, final State state) { this(descriptor,state,null); } public ConnectionStateChanged(final ConnectionDescriptor descriptor, final State state, final ConnectionIdentifier connectionIdentifier) { super(); this.descriptor = descriptor; this.state = state; this.connectionIdentifier = connectionIdentifier; } public ConnectionStateChanged(final State state) { this(null, state); } public ConnectionStateChanged(final State state, final ConnectionIdentifier connectionIdentifier) { this(null, state, connectionIdentifier); } public ConnectionDescriptor descriptor() { return descriptor; } public State state() { return state; } public ConnectionIdentifier connectionIdentifier() { return connectionIdentifier; } }
2,294
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MockPlayDelayMediaGateway.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MockPlayDelayMediaGateway.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.mgcp; import akka.actor.ActorRef; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.Notify; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.pkg.MgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUPackage; /** * @author [email protected] */ public class MockPlayDelayMediaGateway extends MockMediaGateway { @Override protected void notify(Object message, ActorRef sender) { final ActorRef self = self(); final NotificationRequest request = (NotificationRequest) message; MgcpEvent event = null; if (!request.getSignalRequests()[0].getEventIdentifier().getParms().equalsIgnoreCase("sg=pa") && (request.getSignalRequests()[0].getEventIdentifier().getName().equalsIgnoreCase("es") || request.getSignalRequests()[0].getEventIdentifier().getName().equalsIgnoreCase("pr"))) { //Looks like this is either an RQNT AU/ES or //recording max length reached and we got the original recording RQNT event = AUMgcpEvent.auoc.withParm("AU/pr ri=file://" + recordingFile.toPath() + " rc=100 dc=1"); } else { event = AUMgcpEvent.auoc.withParm("rc=100 dc=1"); if(!request.getSignalRequests()[0].getEventIdentifier().getParms().contains("ringing.wav")) { try { Thread.sleep(2000); } catch (Exception e){ logger.error(e.toString()); } } } final EventName[] events = {new EventName(AUPackage.AU, event)}; final Notify notify = new Notify(this, request.getEndpointIdentifier(), request.getRequestIdentifier(), events); notify.setTransactionHandle((int) transactionIdPool.get()); System.out.println(notify.toString()); sender.tell(notify, self); } }
2,823
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MockMediaGateway.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MockMediaGateway.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.mgcp; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActor; import akka.actor.UntypedActorContext; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import jain.protocol.ip.mgcp.JainMgcpCommandEvent; import jain.protocol.ip.mgcp.JainMgcpResponseEvent; import jain.protocol.ip.mgcp.message.CreateConnectionResponse; import jain.protocol.ip.mgcp.message.DeleteConnection; import jain.protocol.ip.mgcp.message.DeleteConnectionResponse; import jain.protocol.ip.mgcp.message.ModifyConnection; import jain.protocol.ip.mgcp.message.ModifyConnectionResponse; import jain.protocol.ip.mgcp.message.NotificationRequest; import jain.protocol.ip.mgcp.message.NotificationRequestResponse; import jain.protocol.ip.mgcp.message.Notify; import jain.protocol.ip.mgcp.message.parms.ConnectionDescriptor; import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier; import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier; import jain.protocol.ip.mgcp.message.parms.EventName; import jain.protocol.ip.mgcp.message.parms.NotifiedEntity; import jain.protocol.ip.mgcp.message.parms.ReturnCode; import jain.protocol.ip.mgcp.pkg.MgcpEvent; import org.joda.time.DateTime; import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUPackage; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.util.RevolvingCounter; import org.restcomm.connect.commons.util.WavUtils; import org.restcomm.connect.mgcp.stats.MgcpConnectionAdded; import org.restcomm.connect.mgcp.stats.MgcpConnectionDeleted; import org.restcomm.connect.mgcp.stats.MgcpEndpointAdded; import org.restcomm.connect.mgcp.stats.MgcpEndpointDeleted; import scala.concurrent.duration.Duration; import javax.sdp.SdpFactory; import javax.sdp.SdpParseException; import javax.sdp.SessionDescription; import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** * @author [email protected] (Thomas Quintana) */ public class MockMediaGateway extends RestcommUntypedActor { protected final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // Session description for the mock media gateway. private static final String sdp = "v=0\n" + "o=- 1362546170756 1 IN IP4 192.168.1.100\n" + "s=Mobicents Media Server\n" + "c=IN IP4 192.168.1.100\n" + "t=0 0\n" + "m=audio 63044 RTP/AVP 97 8 0 101\n" + "a=rtpmap:97 l16/8000\n" + "a=rtpmap:8 pcma/8000\n" + "a=rtpmap:0 pcmu/8000\n" + "a=rtpmap:101 telephone-event/8000\n" + "a=fmtp:101 0-15\n"; // MediaGateway connection information. private String name; private InetAddress localIp; private int localPort; private InetAddress remoteIp; private int remotePort; // Used for NAT traversal. private boolean useNat; private InetAddress externalIp; // Used to detect dead media gateways. private long timeout; // Call agent. private NotifiedEntity agent; // Media gateway domain name. private String domain; // Runtime stuff. private RevolvingCounter requestIdPool; private RevolvingCounter sessionIdPool; protected RevolvingCounter transactionIdPool; protected RevolvingCounter connectionIdPool; private RevolvingCounter endpointIdPool; private Map<String, String> connEndpointMap; private ActorRef monitoringService; protected File recordingFile = null; private int recordingMaxLength; private DateTime startTime; private DateTime endTime; private ActorSystem system; private NotificationRequest recordingRqnt; private ActorRef recordingRqntSender; private boolean recording = false; public MockMediaGateway () { super(); system = context().system(); connEndpointMap = new ConcurrentHashMap<String, String>(); } private ActorRef getConnection (final Object message) { final CreateConnection request = (CreateConnection) message; final MediaSession session = request.session(); final ActorRef gateway = self(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create () throws Exception { return new MockConnection(gateway, session, agent, timeout); } }); ActorRef connection = system.actorOf(props); if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Added new Connection, path: %s", connection.path()); logger.info(msg); } return connection; } private ActorRef getBridgeEndpoint (final Object message) { final CreateBridgeEndpoint request = (CreateBridgeEndpoint) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create () throws Exception { return new BridgeEndpoint(gateway, session, agent, domain, timeout); } }); ActorRef bridgeEndpoint = system.actorOf(props); if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Added Bridge endpoint, path: %s", bridgeEndpoint.path()); logger.info(msg); } return bridgeEndpoint; } private ActorRef getConferenceEndpoint (final Object message) { final ActorRef gateway = self(); final CreateConferenceEndpoint request = (CreateConferenceEndpoint) message; final MediaSession session = request.session(); final String endpointName = request.endpointName(); Props props = null; props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create () throws Exception { return new ConferenceEndpoint(gateway, session, agent, domain, timeout, endpointName); } }); ActorRef conferenceEndpoint = system.actorOf(props); if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Added Conference endpoint, path: %s", conferenceEndpoint.path()); logger.info(msg); } return conferenceEndpoint; } private MediaGatewayInfo getInfo (final Object message) { return new MediaGatewayInfo(name, remoteIp, remotePort, useNat, externalIp); } private ActorRef getIvrEndpoint (final Object message) { final ActorRef gateway = self(); final CreateIvrEndpoint request = (CreateIvrEndpoint) message; final MediaSession session = request.session(); final String endpointName = request.endpointName(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create () throws Exception { return new IvrEndpoint(gateway, session, agent, domain, timeout, endpointName); } }); ActorRef ivrEndpoint = system.actorOf(props); if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Added Ivr endpoint, path: %s", ivrEndpoint.path()); logger.info(msg); } return ivrEndpoint; } private ActorRef getLink (final Object message) { final CreateLink request = (CreateLink) message; final ActorRef gateway = self(); final MediaSession session = request.session(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create () throws Exception { return new Link(gateway, session, agent, timeout); } }); ActorRef link = system.actorOf(props); if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Added new Link, path: %s", link.path()); logger.info(msg); } return link; } private ActorRef getPacketRelayEndpoint (final Object message) { final ActorRef gateway = self(); final CreatePacketRelayEndpoint request = (CreatePacketRelayEndpoint) message; final MediaSession session = request.session(); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create () throws Exception { return new PacketRelayEndpoint(gateway, session, agent, domain, timeout); } }); ActorRef packetRelayEndpoint = system.actorOf(props); if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Added PacketRelay endpoint, path: %s", packetRelayEndpoint.path()); logger.info(msg); } return packetRelayEndpoint; } private MediaSession getSession () { return new MediaSession((int) sessionIdPool.get()); } private void powerOff (final Object message) { // Make sure we don't leave anything behind. name = null; localIp = null; localPort = 0; remoteIp = null; remotePort = 0; useNat = false; externalIp = null; timeout = 0; agent = null; domain = null; requestIdPool = null; sessionIdPool = null; transactionIdPool = null; } private void powerOn (final Object message) { final PowerOnMediaGateway request = (PowerOnMediaGateway) message; name = request.getName(); localIp = request.getLocalIp(); localPort = request.getLocalPort(); remoteIp = request.getRemoteIp(); remotePort = request.getRemotePort(); useNat = request.useNat(); externalIp = request.getExternalIp(); timeout = request.getTimeout(); agent = new NotifiedEntity("restcomm", localIp.getHostAddress(), localPort); domain = new StringBuilder().append(remoteIp.getHostAddress()).append(":").append(remotePort).toString(); connectionIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); endpointIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); requestIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); sessionIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); transactionIdPool = new RevolvingCounter(1, Integer.MAX_VALUE); monitoringService = request.getMonitoringService(); } @Override public void onReceive (final Object message) throws Exception { final UntypedActorContext context = getContext(); final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (PowerOnMediaGateway.class.equals(klass)) { powerOn(message); } else if (PowerOffMediaGateway.class.equals(klass)) { powerOff(message); } else if (GetMediaGatewayInfo.class.equals(klass)) { sender.tell(new MediaGatewayResponse<MediaGatewayInfo>(getInfo(message)), sender); } else if (CreateConnection.class.equals(klass)) { sender.tell(new MediaGatewayResponse<ActorRef>(getConnection(message)), self); } else if (CreateLink.class.equals(klass)) { sender.tell(new MediaGatewayResponse<ActorRef>(getLink(message)), self); } else if (CreateMediaSession.class.equals(klass)) { sender.tell(new MediaGatewayResponse<MediaSession>(getSession()), self); } else if (CreateBridgeEndpoint.class.equals(klass)) { final ActorRef endpoint = getBridgeEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreatePacketRelayEndpoint.class.equals(klass)) { final ActorRef endpoint = getPacketRelayEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreateIvrEndpoint.class.equals(klass)) { final ActorRef endpoint = getIvrEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (CreateConferenceEndpoint.class.equals(klass)) { final ActorRef endpoint = getConferenceEndpoint(message); sender.tell(new MediaGatewayResponse<ActorRef>(endpoint), self); } else if (DestroyConnection.class.equals(klass)) { final DestroyConnection request = (DestroyConnection) message; if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Connection destroyed, path %s", request.connection().path()); logger.info(msg); } context.stop(request.connection()); } else if (DestroyLink.class.equals(klass)) { final DestroyLink request = (DestroyLink) message; if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Link destroyed, path %s", request.link().path()); logger.info(msg); } context.stop(request.link()); } else if (DestroyEndpoint.class.equals(klass)) { final DestroyEndpoint request = (DestroyEndpoint) message; if (logger.isInfoEnabled()) { String msg = String.format("MockMediaGateway, Endpoint destroyed, path %s", request.endpoint().path()); logger.info(msg); } context.stop(request.endpoint()); } else if (message instanceof JainMgcpCommandEvent) { send(message, sender); } else if (message instanceof JainMgcpResponseEvent) { send(message); } else if (message instanceof ReceiveTimeout) { onReceiveTimeout(message); } } private void onReceiveTimeout (Object message) { getContext().setReceiveTimeout(Duration.Undefined()); if (recording) { if (logger.isInfoEnabled()) { logger.info("Max recording length reached"); } stopRecording(); notify(recordingRqnt, recordingRqntSender); } } private void writeRecording (File srcWaveFile, File outWaveFile, int duration) { DateTime start = new DateTime(); DateTime end; long operationDuration; AudioInputStream audioInputStream = null; AudioInputStream shortenedStream = null; try { File tempFile = File.createTempFile("tempRecording", ".wav"); tempFile.deleteOnExit(); if (outWaveFile.exists()) { String msg = String.format("Recording file %s doesn't exist, will create it", outWaveFile); logger.warning(msg); outWaveFile.createNewFile(); } audioInputStream = AudioSystem.getAudioInputStream(srcWaveFile); AudioFileFormat fileFormat = AudioSystem.getAudioFileFormat(srcWaveFile); AudioFormat format = fileFormat.getFormat(); int bytesPerSecond = format.getFrameSize() * (int) format.getFrameRate(); long framesOfAudioToCopy = duration * (int) format.getFrameRate(); shortenedStream = new AudioInputStream(audioInputStream, format, framesOfAudioToCopy); AudioSystem.write(shortenedStream, fileFormat.getType(), tempFile); Files.move(tempFile.toPath(), outWaveFile.toPath(), StandardCopyOption.REPLACE_EXISTING); double recordedDuration = WavUtils.getAudioDuration(outWaveFile); String msg = String.format("Write to recording file %s completed, duration %6.0f", outWaveFile, recordedDuration); logger.info(msg); } catch (UnsupportedAudioFileException | IOException e) { String msg = String.format("Exception while trying to write to recording file %s for duration of %d, exception %s", outWaveFile, duration, e); logger.error(msg); } finally { if (audioInputStream != null) try { audioInputStream.close(); } catch (Exception e) { e.printStackTrace(); } if (shortenedStream != null) try { shortenedStream.close(); } catch (Exception e) { e.printStackTrace(); } end = new DateTime(); operationDuration = (end.getMillis() - start.getMillis()); String msg = String.format("Write to recording file %s completed, operation duration %d ms", outWaveFile, operationDuration); logger.info(msg); } } protected void createConnection (final Object message, final ActorRef sender) { final ActorRef self = self(); final jain.protocol.ip.mgcp.message.CreateConnection crcx = (jain.protocol.ip.mgcp.message.CreateConnection) message; System.out.println(crcx.toString()); // Create a response. StringBuilder buffer = new StringBuilder(); buffer.append(connectionIdPool.get()); ConnectionIdentifier connId = new ConnectionIdentifier(buffer.toString()); final ReturnCode code = ReturnCode.Transaction_Executed_Normally; final CreateConnectionResponse response = new CreateConnectionResponse(self, code, connId); // Create a new end point id if necessary. EndpointIdentifier endpointId = crcx.getEndpointIdentifier(); String endpointName = endpointId.getLocalEndpointName(); if (endpointName.endsWith("$")) { final String[] tokens = endpointName.split("/"); final String type = tokens[1]; buffer = new StringBuilder(); buffer.append("mobicents/").append(type).append("/"); buffer.append(endpointIdPool.get()); endpointId = new EndpointIdentifier(buffer.toString(), domain); } connEndpointMap.put(connId.toString(), endpointId.getLocalEndpointName()); if (logger.isInfoEnabled()) { String msg = String.format("About to add connId %s for endpoint %s", connId.toString(), endpointId.getLocalEndpointName()); logger.info(msg); } monitoringService.tell(new MgcpEndpointAdded(connId.toString(), endpointId.getLocalEndpointName()), self()); monitoringService.tell(new MgcpConnectionAdded(connId.toString(), endpointId.getLocalEndpointName()), self()); response.setSpecificEndpointIdentifier(endpointId); // Create a new secondary end point id if necessary. EndpointIdentifier secondaryEndpointId = crcx.getSecondEndpointIdentifier(); if (secondaryEndpointId != null) { buffer = new StringBuilder(); buffer.append(connectionIdPool.get()); ConnectionIdentifier secondayConnId = new ConnectionIdentifier(buffer.toString()); response.setSecondConnectionIdentifier(secondayConnId); endpointName = secondaryEndpointId.getLocalEndpointName(); if (endpointName.endsWith("$")) { final String[] tokens = endpointName.split("/"); final String type = tokens[1]; buffer = new StringBuilder(); buffer.append("mobicents/").append(type).append("/"); buffer.append(endpointIdPool.get()); secondaryEndpointId = new EndpointIdentifier(buffer.toString(), domain); } connEndpointMap.put(secondayConnId.toString(), secondaryEndpointId.getLocalEndpointName()); if (logger.isInfoEnabled()) { String msg = String.format("About to add connId %s for secondary endpoint %s associated with endpont %s", secondayConnId.toString(), secondaryEndpointId.getLocalEndpointName(), endpointId.getLocalEndpointName()); logger.info(msg); } monitoringService.tell(new MgcpEndpointAdded(connId.toString(), secondaryEndpointId.getLocalEndpointName()), self()); monitoringService.tell(new MgcpConnectionAdded(secondayConnId.toString(), secondaryEndpointId.getLocalEndpointName())); response.setSecondEndpointIdentifier(secondaryEndpointId); } final ConnectionDescriptor descriptor = new ConnectionDescriptor(sdp); response.setLocalConnectionDescriptor(descriptor); final int transaction = crcx.getTransactionHandle(); response.setTransactionHandle(transaction); System.out.println(response.toString()); sender.tell(response, self); } private void modifyConnection (final Object message, final ActorRef sender) { final ActorRef self = self(); final ModifyConnection mdcx = (ModifyConnection) message; System.out.println("MDCX: \n" + mdcx.toString()); if (logger.isInfoEnabled()) { String msg = String.format("Got MDCX for endpoint %s connId %s, mdcx: \n%s", mdcx.getEndpointIdentifier().getLocalEndpointName(), mdcx.getConnectionIdentifier(), mdcx); logger.info(msg); } ReturnCode code; SessionDescription sessionDescription = null; boolean isNonValidSdp = false; if (mdcx.getRemoteConnectionDescriptor() != null) { try { sessionDescription = SdpFactory.getInstance().createSessionDescription(mdcx.getRemoteConnectionDescriptor().toString()); isNonValidSdp = sessionDescription.getSessionName().getValue().contains("NonValidSDP"); } catch (SdpParseException e) { logger.error("Error while trying to get SDP from MDCX"); } } if (sessionDescription != null && isNonValidSdp) { code = ReturnCode.Protocol_Error; final ModifyConnectionResponse response = new ModifyConnectionResponse(self, code); final int transaction = mdcx.getTransactionHandle(); response.setTransactionHandle(transaction); System.out.println(response.toString()); sender.tell(response, self); } else { code = ReturnCode.Transaction_Executed_Normally; final ModifyConnectionResponse response = new ModifyConnectionResponse(self, code); final ConnectionDescriptor descriptor = new ConnectionDescriptor(sdp); response.setLocalConnectionDescriptor(descriptor); final int transaction = mdcx.getTransactionHandle(); response.setTransactionHandle(transaction); System.out.println(response.toString()); sender.tell(response, self); } } private void deleteConnection (final Object message, final ActorRef sender) { final ActorRef self = self(); final DeleteConnection dlcx = (DeleteConnection) message; if (dlcx.getConnectionIdentifier() == null) { connEndpointMap.values().removeAll(Collections.singleton(dlcx.getEndpointIdentifier().getLocalEndpointName())); monitoringService.tell(new MgcpConnectionDeleted(null, dlcx.getEndpointIdentifier().getLocalEndpointName()), self()); monitoringService.tell(new MgcpEndpointDeleted(dlcx.getEndpointIdentifier().getLocalEndpointName()), self()); if (logger.isInfoEnabled()) { String msg = String.format("Endpoint deleted %s", dlcx.getEndpointIdentifier().getLocalEndpointName()); logger.info(msg); } } else { connEndpointMap.remove(dlcx.getConnectionIdentifier().toString()); monitoringService.tell(new MgcpConnectionDeleted(dlcx.getConnectionIdentifier().toString(), null), self()); //If all connections have been removed for a given Endpoint, we can consider that the endpoint is stopped (this is the RMS behavior) //Here check if we have Endpoint ID on the map, and if not, tell MonitoringService that the endpoint stopped. if (!connEndpointMap.values().contains(dlcx.getEndpointIdentifier().getLocalEndpointName())) { monitoringService.tell(new MgcpEndpointDeleted(dlcx.getEndpointIdentifier().getLocalEndpointName()), self()); if (logger.isInfoEnabled()) { String msg = String.format("Endpoint deleted %s since because there are no more connections related to this endpoint", dlcx.getEndpointIdentifier().getLocalEndpointName()); logger.info(msg); } } } System.out.println(dlcx.toString()); final ReturnCode code = ReturnCode.Transaction_Executed_Normally; final DeleteConnectionResponse response = new DeleteConnectionResponse(self, code); final int transaction = dlcx.getTransactionHandle(); response.setTransactionHandle(transaction); System.out.println(response.toString()); sender.tell(response, self); } protected void notificationResponse (final Object message, final ActorRef sender) { final ActorRef self = self(); final NotificationRequest rqnt = (NotificationRequest) message; EventName[] events = rqnt.getSignalRequests(); //Thread sleep for the maximum recording length to simulate recording from RMS side String filename = null; boolean failResponse = false; if (events != null && events.length > 0 && events[0].getEventIdentifier() != null) { if (events[0].getEventIdentifier().getName().equalsIgnoreCase("pr")) { recording = true; startTime = DateTime.now(); //Check for the Recording Length Timer parameter if the RQNT is about PlayRecord request String[] paramsArray = ((EventName) events[0]).getEventIdentifier().getParms().split(" "); for (String param : paramsArray) { if (param.startsWith("rlt")) { recordingMaxLength = Integer.parseInt(param.replace("rlt=", "")); } else if (param.startsWith("ri")) { filename = param.replace("ri=", ""); } } //If maxLength is not set, rlt will be rlt=36000 if (recordingMaxLength != 36000) { getContext().setReceiveTimeout(Duration.create(recordingMaxLength*10, TimeUnit.MILLISECONDS)); } if (filename != null) { Path path = Paths.get(filename.replaceFirst("file://", "")); recordingFile = new File(filename.replaceFirst("file://", "")); recordingFile.getParentFile().mkdir(); } } else if (events[0].getEventIdentifier().getName().equalsIgnoreCase("es")) { String signal = ((EventName) events[0]).getEventIdentifier().getParms().split("=")[1]; if (signal.equalsIgnoreCase("pr") && recording) { stopRecording(); } } else if (events[0].getEventIdentifier().getName().equalsIgnoreCase("pa")) { //If this is a Play Audio request, check that the parameter string ends with WAV String[] paramsArray = ((EventName) events[0]).getEventIdentifier().getParms().split(" "); for (String param : paramsArray) { if (param.startsWith("an")) { String annoUrl = param.replace("an=", ""); if (!annoUrl.toLowerCase().endsWith("wav")) { failResponse = true; } } } } } System.out.println(rqnt.toString()); ReturnCode code = null; if (failResponse) { code = ReturnCode.Transient_Error; } else { code = ReturnCode.Transaction_Executed_Normally; } final JainMgcpResponseEvent response = new NotificationRequestResponse(self, code); final int transaction = rqnt.getTransactionHandle(); response.setTransactionHandle(transaction); String msg = String.format("About to send MockMediaGateway response %s", response.toString()); logger.info(msg); sender.tell(response, self); } private void stopRecording () { if (recordingFile != null) { recording = false; endTime = DateTime.now(); long recordingDuration = (int) ((endTime.getMillis() - startTime.getMillis()) / 1000); try { int duration = (int) recordingDuration; if (duration > 0) { String msg = String.format("Will write to recording file %s for duration of %d", recordingFile, duration); logger.info(msg); URI waveFileUri = ClassLoader.getSystemResource("FiveMinutes.wav").toURI(); File waveFile = new File(waveFileUri); writeRecording(waveFile, recordingFile, duration); } else { String msg = String.format("Will not write recording file %s because duration is %d", recordingFile, duration); logger.info(msg); } } catch (Exception e) { String msg = String.format("Exception while trying to create Recording file %s, exception %s", recordingFile, e); logger.error(msg); } } } protected void notify (final Object message, final ActorRef sender) { final ActorRef self = self(); final NotificationRequest request = (NotificationRequest) message; MgcpEvent event = null; // Remove case RQNT for stoping media instead of stop recording. if (!request.getSignalRequests()[0].getEventIdentifier().getParms().equalsIgnoreCase("sg=pa") && (request.getSignalRequests()[0].getEventIdentifier().getName().equalsIgnoreCase("es") || request.getSignalRequests()[0].getEventIdentifier().getName().equalsIgnoreCase("pr"))) { //Looks like this is either an RQNT AU/ES or //recording max length reached and we got the original recording RQNT event = AUMgcpEvent.auoc.withParm("AU/pr ri=file://" + recordingFile.toPath() + " rc=100 dc=1"); } else { event = AUMgcpEvent.auoc.withParm("rc=100 dc=1"); } final EventName[] events = {new EventName(AUPackage.AU, event)}; final Notify notify = new Notify(this, request.getEndpointIdentifier(), request.getRequestIdentifier(), events); notify.setTransactionHandle((int) transactionIdPool.get()); System.out.println(notify.toString()); sender.tell(notify, self); } private void respond (final Object message, final ActorRef sender) { final Class<?> klass = message.getClass(); if (jain.protocol.ip.mgcp.message.CreateConnection.class.equals(klass)) { createConnection(message, sender); } else if (ModifyConnection.class.equals(klass)) { modifyConnection(message, sender); } else if (DeleteConnection.class.equals(klass)) { deleteConnection(message, sender); } else if (NotificationRequest.class.equals(klass)) { notificationResponse(message, sender); } } private void send (final Object message, final ActorRef sender) { final JainMgcpCommandEvent command = (JainMgcpCommandEvent) message; final int transactionId = (int) transactionIdPool.get(); command.setTransactionHandle(transactionId); respond(message, sender); EventName[] events = null; if (message instanceof NotificationRequest) { final NotificationRequest rqnt = (NotificationRequest) message; events = rqnt.getSignalRequests(); if (events != null && events[0].getEventIdentifier().getName().equalsIgnoreCase("pr")) { recordingRqnt = rqnt; recordingRqntSender = sender(); } } if (events != null && !events[0].getEventIdentifier().getName().equalsIgnoreCase("pr") && // In real scenario, there is no NTFY for finish ringing immediately. !events[0].getEventIdentifier().getParms().contains("ringing.wav")) { if (NotificationRequest.class.equals(command.getClass())) { final NotificationRequest request = (NotificationRequest) command; final String id = Long.toString(requestIdPool.get()); request.getRequestIdentifier().setRequestIdentifier(id); notify(request, sender); } } } private void send (final Object message) { final JainMgcpResponseEvent response = (JainMgcpResponseEvent) message; System.out.println(response.toString()); } }
34,701
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PlayRecord.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/PlayRecord.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.mgcp; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class PlayRecord { private final List<URI> initialPrompts; private final boolean clearDigitBuffer; private final long preSpeechTimer; private final long postSpeechTimer; private final long recordingLength; private final String endInputKey; private final URI recordingId; private PlayRecord(final List<URI> initialPrompts, final boolean clearDigitBuffer, final long preSpeechTimer, final long postSpeechTimer, final long recordingLength, final String endInputKey, final URI recordingId) { super(); this.initialPrompts = initialPrompts; this.clearDigitBuffer = clearDigitBuffer; this.preSpeechTimer = preSpeechTimer; this.postSpeechTimer = postSpeechTimer; this.recordingLength = recordingLength; this.endInputKey = endInputKey; this.recordingId = recordingId; } public static Builder builder() { return new Builder(); } public List<URI> initialPrompts() { return initialPrompts; } public boolean clearDigitBuffer() { return clearDigitBuffer; } public long preSpeechTimer() { return preSpeechTimer; } public long postSpeechTimer() { return postSpeechTimer; } public long recordingLength() { return recordingLength; } public String endInputKey() { return endInputKey; } public URI recordingId() { return recordingId; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); if (!initialPrompts.isEmpty()) { buffer.append("ip="); for (int index = 0; index < initialPrompts.size(); index++) { buffer.append(initialPrompts.get(index)); if (index < initialPrompts.size() - 1) { buffer.append(";"); } } } if (recordingId != null) { if (buffer.length() > 0) buffer.append(" "); buffer.append("ri=").append(recordingId); } if (clearDigitBuffer) { if (buffer.length() > 0) buffer.append(" "); buffer.append("cb=").append("true"); } if (preSpeechTimer > 0) { if (buffer.length() > 0) buffer.append(" "); buffer.append("prt=").append(preSpeechTimer * 10); } if (postSpeechTimer > 0) { if (buffer.length() > 0) buffer.append(" "); buffer.append("pst=").append(postSpeechTimer * 10); } if (recordingLength > 0) { if (buffer.length() > 0) buffer.append(" "); buffer.append("rlt=").append(recordingLength * 10); } if (endInputKey != null) { if (buffer.length() > 0) buffer.append(" "); buffer.append("eik=").append(endInputKey).append(" "); //https://github.com/RestComm/Restcomm-Connect/issues/1890 // buffer.append("mn=").append(endInputKey.length()).append(" "); // buffer.append("mx=").append(endInputKey.length()); } return buffer.toString(); } public static final class Builder { private List<URI> initialPrompts; private boolean clearDigitBuffer; private long preSpeechTimer; private long postSpeechTimer; private long recordingLength; private String endInputKey; private URI recordingId; private Builder() { super(); initialPrompts = new ArrayList<URI>(); clearDigitBuffer = false; preSpeechTimer = -1; postSpeechTimer = -1; recordingLength = -1; endInputKey = null; recordingId = null; } public PlayRecord build() { return new PlayRecord(initialPrompts, clearDigitBuffer, preSpeechTimer, postSpeechTimer, recordingLength, endInputKey, recordingId); } public void addPrompt(final URI prompt) { this.initialPrompts.add(prompt); } public void setClearDigitBuffer(final boolean clearDigitBuffer) { this.clearDigitBuffer = clearDigitBuffer; } public void setPreSpeechTimer(final long preSpeechTimer) { this.preSpeechTimer = preSpeechTimer; } public void setPostSpeechTimer(final long postSpeechTimer) { this.postSpeechTimer = postSpeechTimer; } public void setRecordingLength(final long recordingLength) { this.recordingLength = recordingLength; } public void setEndInputKey(final String endInputKey) { this.endInputKey = endInputKey; } public void setRecordingId(final URI recordingId) { this.recordingId = recordingId; } } }
6,023
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MediaResourceBrokerResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/MediaResourceBrokerResponse.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.mgcp; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author Maria Farooq ([email protected]) */ public final class MediaResourceBrokerResponse<T> extends StandardResponse<T> { public MediaResourceBrokerResponse(final T object) { super(object); } public MediaResourceBrokerResponse(final Throwable cause) { super(cause); } public MediaResourceBrokerResponse(final Throwable cause, final String message) { super(cause, message); } }
1,356
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AsrSignal.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/AsrSignal.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.mgcp; import jain.protocol.ip.mgcp.pkg.MgcpEvent; import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.apache.commons.codec.binary.Hex; import java.net.URI; import java.util.List; /** * Created by gdubina on 6/6/17. */ @Immutable public class AsrSignal { public static final MgcpEvent REQUEST_ASR = MgcpEvent.factory("asr", AUMgcpEvent.END_SIGNAL + 1); private static final String SPACE_CHARACTER = " "; private final String driver; private final List<URI> initialPrompts; private final String endInputKey; private final int maximumRecTimer; private final int waitingInputTimer; private final int timeAfterSpeech; private final String hotWords; private final String lang; private final String input; private final int minNumber; private final int maxNumber; private final boolean partialResult; /** * * @param driver ASR driver * @param lang speech language * @param initialPrompts Initial prompt * @param endInputKey end input key, if present stop ASR with dtmf signal * @param maximumRecTimer maximum recognition time * @param waitingInputTimer waiting time to detect user input (gather timeout) * @param timeAfterSpeech amount of silence necessary after the end of speech (gather timeout) * @param hotWords hints for speech analyzer tool * @param input "dtmf", "speech", "dtmf speech" * @param numberOfDigits number of digits system expects from User * @param partialResult whether RC needs partial results */ public AsrSignal(String driver, String lang, List<URI> initialPrompts, String endInputKey, int maximumRecTimer, int waitingInputTimer, int timeAfterSpeech, String hotWords, String input, int numberOfDigits, boolean partialResult) { this.driver = driver; this.initialPrompts = initialPrompts; this.endInputKey = endInputKey; this.maximumRecTimer = maximumRecTimer; this.waitingInputTimer = waitingInputTimer; this.timeAfterSpeech = timeAfterSpeech; this.hotWords = hotWords; this.lang = lang; this.input = input; //RMS expects two parameters but Collect in RVD has only one this.minNumber = numberOfDigits; this.maxNumber = numberOfDigits; this.partialResult = partialResult; } @Override public String toString() { final StringBuilder buffer = new StringBuilder(); if (!initialPrompts.isEmpty()) { buffer.append("ip="); for (int index = 0; index < initialPrompts.size(); index++) { buffer.append(initialPrompts.get(index)); if (index < initialPrompts.size() - 1) { //https://github.com/RestComm/Restcomm-Connect/issues/1988 buffer.append(","); } } } if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("dr=").append(driver); if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("ln=").append(lang); if (endInputKey != null) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("eik=").append(endInputKey); } if (maximumRecTimer > 0) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("mrt=").append(maximumRecTimer * 10); } if (waitingInputTimer > 0) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("wit=").append(waitingInputTimer * 10); } if (timeAfterSpeech > 0) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("pst=").append(timeAfterSpeech * 10); } if (hotWords != null) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("hw=").append(Hex.encodeHexString(hotWords.getBytes())); } if (input != null) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("in=").append(input); } if (minNumber > 0) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("mn=").append(minNumber); } if (maxNumber > 0) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("mx=").append(maxNumber); } if (partialResult) { if (buffer.length() > 0) buffer.append(SPACE_CHARACTER); buffer.append("pr=").append(partialResult); } return buffer.toString(); } }
5,787
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CollectedResult.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/CollectedResult.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.mgcp; /** * Created by gdubina on 6/6/17. */ public class CollectedResult { private final String result; private final boolean isAsr; private final boolean isPartial; public CollectedResult(String result, boolean isAsr, boolean isPartial) { this.result = result; this.isAsr = isAsr; this.isPartial = isPartial; } public String getResult() { return result; } public boolean isAsr() { return isAsr; } public boolean isPartial() { return isPartial; } @Override public String toString() { return "CollectedResult{" + "result='" + result + '\'' + ", isAsr=" + isAsr + ", isPartial=" + isPartial + '}'; } }
1,627
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
InitializeConnection.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/InitializeConnection.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.mgcp; import akka.actor.ActorRef; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class InitializeConnection { private final ActorRef endpoint; public InitializeConnection(final ActorRef endpoint) { super(); this.endpoint = endpoint; } public ActorRef endpoint() { return endpoint; } }
1,285
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MgcpEndpointAdded.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/stats/MgcpEndpointAdded.java
package org.restcomm.connect.mgcp.stats; public class MgcpEndpointAdded { private final String connId; private final String endpoint; public MgcpEndpointAdded (String connId, String endpoint) { this.connId = connId; this.endpoint = endpoint; } public String getConnId () { return connId; } public String getEndpoint () { return endpoint; } }
410
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MgcpEndpointDeleted.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/stats/MgcpEndpointDeleted.java
package org.restcomm.connect.mgcp.stats; public class MgcpEndpointDeleted { private final String endpoint; public MgcpEndpointDeleted (String endpoint) { this.endpoint = endpoint; } public String getEndpoint () { return endpoint; } }
273
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MgcpConnectionDeleted.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/stats/MgcpConnectionDeleted.java
package org.restcomm.connect.mgcp.stats; public class MgcpConnectionDeleted { private final String connId; private final String endpoint; public MgcpConnectionDeleted (String connId, String endpoint) { this.connId = connId; this.endpoint = endpoint; } public String getConnId () { return connId; } public String getEndpoint () { return endpoint; } }
418
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MgcpConnectionAdded.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mgcp/src/main/java/org/restcomm/connect/mgcp/stats/MgcpConnectionAdded.java
package org.restcomm.connect.mgcp.stats; public class MgcpConnectionAdded { private final String connId; private final String endpointId; public MgcpConnectionAdded (String connId, String endpointId) { this.connId = connId; this.endpointId = endpointId; } public String getConnId () { return connId; } public String getEndpointId () { return endpointId; } }
426
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DisconnectTelephoneNumberOrderType.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/DisconnectTelephoneNumberOrderType.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; /** * Created by sbarstow on 10/17/14. */ @XmlRootElement(name = "DisconnectTelephoneNumberOrderType") @XmlAccessorType(XmlAccessType.FIELD) public class DisconnectTelephoneNumberOrderType { @XmlElementWrapper(name = "TelephoneNumberList") @XmlElement(name = "TelephoneNumber") private List<String> telephoneNumberList = new ArrayList<String>(); @XmlElement(name = "DisconnectMode") private String disconnectMode; public List<String> getTelephoneNumberList() { return telephoneNumberList; } public void setTelephoneNumberList(List<String> telephoneNumberList) { this.telephoneNumberList = telephoneNumberList; } public String getDisconnectMode() { return disconnectMode; } public void setDisconnectMode(String disconnectMode) { this.disconnectMode = disconnectMode; } }
2,029
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TelephoneNumber.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/TelephoneNumber.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "TelephoneNumber") @XmlAccessorType(XmlAccessType.FIELD) public class TelephoneNumber { @XmlElement(name = "FullNumber") private String fullNumber; public TelephoneNumber() { } public String getFullNumber() { return fullNumber; } public void setFullNumber(String fullNumber) { this.fullNumber = fullNumber; } }
1,454
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SearchResult.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/SearchResult.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.provisioning.number.bandwidth; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; /** * The root entity returned by IRIS for a local or toll-free number search. * <p/> * If number details were desired (only works for local queries), * {@link #telephoneNumberDetailList} will be populated and * {@link #telephoneNumberList} will be empty. * <p/> * If details were not desired, the plain list of numbers can be found in * {@link #telephoneNumberList} and {@link #telephoneNumberDetailList} will be * empty. */ @XmlRootElement(name = "SearchResult") @XmlAccessorType(XmlAccessType.FIELD) public class SearchResult { @XmlElement(name = "Error") private Error error; @XmlElement(name = "ResultCount") private Integer resultCount; @XmlElementWrapper(name = "TelephoneNumberList") @XmlElement(name = "TelephoneNumber") private List<String> telephoneNumberList = new ArrayList<String>(); @XmlElementWrapper(name = "TelephoneNumberDetailList") @XmlElement(name = "TelephoneNumberDetail") private List<TelephoneNumberDetail> telephoneNumberDetailList = new ArrayList<TelephoneNumberDetail>(); public Error getError() { return error; } public void setError(Error error) { this.error = error; } public Integer getResultCount() { return resultCount; } public void setResultCount(Integer resultCount) { this.resultCount = resultCount; } public List<String> getTelephoneNumberList() { return telephoneNumberList; } public void setTelephoneNumberList(List<String> telephoneNumberList) { this.telephoneNumberList = telephoneNumberList; } public List<TelephoneNumberDetail> getTelephoneNumberDetailList() { return telephoneNumberDetailList; } public void setTelephoneNumberDetailList(List<TelephoneNumberDetail> telephoneNumberDetailList) { this.telephoneNumberDetailList = telephoneNumberDetailList; } }
3,065
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OrderRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/OrderRequest.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; /** * Created by sbarstow on 10/17/14. */ @XmlRootElement(name = "orderRequest") @XmlAccessorType(XmlAccessType.FIELD) public class OrderRequest { @XmlElement(name = "Name") private String name; @XmlElement(name = "OrderCreateDate") private Date orderCreateDate; @XmlElement(name = "id") private String id; @XmlElement(name = "DisconnectTelephoneNumberOrderType") private DisconnectTelephoneNumberOrderType disconnectTelephoneNumberOrderType; public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getOrderCreateDate() { return orderCreateDate; } public void setOrderCreateDate(Date orderCreateDate) { this.orderCreateDate = orderCreateDate; } public String getid() { return id; } public void setid(String id) { this.id = id; } public DisconnectTelephoneNumberOrderType getDisconnectTelephoneNumberOrderType() { return disconnectTelephoneNumberOrderType; } public void setDisconnectTelephoneNumberOrderType(DisconnectTelephoneNumberOrderType disconnectTelephoneNumberOrderType) { this.disconnectTelephoneNumberOrderType = disconnectTelephoneNumberOrderType; } }
2,377
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OrderResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/OrderResponse.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "OrderResponse") @XmlAccessorType(XmlAccessType.FIELD) public class OrderResponse { @XmlElement(name = "Order") private Order order; public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
1,366
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Error.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/Error.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Created by sbarstow on 10/17/14. */ @XmlRootElement(name = "Error") @XmlAccessorType(XmlAccessType.FIELD) public class Error { @XmlElement(name = "Code") private String code; @XmlElement(name = "Description") private String description; @XmlElement(name = "TelephoneNumber") private String telephoneNumber; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getTelephoneNumber() { return telephoneNumber; } public void setTelephoneNumber(String telephoneNumber) { this.telephoneNumber = telephoneNumber; } }
1,907
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DisconnectTelephoneNumberOrderResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/DisconnectTelephoneNumberOrderResponse.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; /** * Created by sbarstow on 10/17/14. */ @XmlRootElement(name = "DisconnectTelephoneNumberOrderResponse") @XmlAccessorType(XmlAccessType.FIELD) public class DisconnectTelephoneNumberOrderResponse { @XmlElement(name = "orderRequest") private OrderRequest orderRequest; @XmlElementWrapper(name = "ErrorList") @XmlElement(name = "Error") private List<Error> errorList = new ArrayList<Error>(); @XmlElement(name = "OrderStatus") private String orderStatus; public OrderRequest getorderRequest() { return orderRequest; } public void setorderRequest(OrderRequest orderRequest) { this.orderRequest = orderRequest; } public List<Error> getErrorList() { return errorList; } public void setErrorList(List<Error> errorList) { this.errorList = errorList; } public String getOrderStatus() { return orderStatus; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } }
2,188
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ExistingTelephoneNumberOrderType.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/ExistingTelephoneNumberOrderType.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import java.util.ArrayList; import java.util.List; /** * Created by sbarstow on 10/14/14. */ @XmlRootElement(name = "ExistingTelephoneNumberOrderType") @XmlAccessorType(XmlAccessType.FIELD) public class ExistingTelephoneNumberOrderType { @XmlElementWrapper(name = "TelephoneNumberList") @XmlElement(name = "TelephoneNumber") private List<String> telephoneNumberList = new ArrayList<String>(); public List<String> getTelephoneNumberList() { return telephoneNumberList; } public void setTelephoneNumberList(List<String> telephoneNumberList) { this.telephoneNumberList = telephoneNumberList; } }
1,759
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Order.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/Order.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.Date; @XmlRootElement(name = "Order") @XmlAccessorType(XmlAccessType.FIELD) public class Order { @XmlElement(name = "id") private String id; @XmlElement(name = "BackOrderRequested") private boolean backOrderRequested; @XmlElement(name = "OrderCreateDate") private Date orderCreateDate; @XmlElement(name = "Name") private String name; @XmlElement(name = "SiteId") private String siteId; @XmlElement(name = "CustomerOrderId") private String customerOrderId; @XmlElement(name = "PartialAllowed") private boolean partialAllowed = false; @XmlElement(name = "ExistingTelephoneNumberOrderType") private ExistingTelephoneNumberOrderType existingTelephoneNumberOrderType; public String getid() { return id; } public void setid(String id) { this.id = id; } public boolean isBackOrderRequested() { return backOrderRequested; } public void setBackOrderRequested(boolean backOrderRequested) { this.backOrderRequested = backOrderRequested; } public Date getOrderCreateDate() { return orderCreateDate; } public void setOrderCreateDate(Date orderCreateDate) { this.orderCreateDate = orderCreateDate; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSiteId() { return siteId; } public void setSiteId(String siteId) { this.siteId = siteId; } public String getCustomerOrderId() { return customerOrderId; } public void setCustomerOrderId(String customerOrderId) { this.customerOrderId = customerOrderId; } public boolean isPartialAllowed() { return partialAllowed; } public void setPartialAllowed(boolean partialAllowed) { this.partialAllowed = partialAllowed; } public ExistingTelephoneNumberOrderType getExistingTelephoneNumberOrderType() { return existingTelephoneNumberOrderType; } public void setExistingTelephoneNumberOrderType(ExistingTelephoneNumberOrderType existingTelephoneNumberOrderType) { this.existingTelephoneNumberOrderType = existingTelephoneNumberOrderType; } }
3,352
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TelephoneNumberDetail.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/TelephoneNumberDetail.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * Describes a telephone number with details. */ @XmlRootElement(name = "TelephoneNumberDetail") @XmlAccessorType(XmlAccessType.FIELD) public class TelephoneNumberDetail { @XmlElement(name = "City") private String city; @XmlElement(name = "LATA") private String lata; @XmlElement(name = "RateCenter") private String rateCenter; @XmlElement(name = "State") private String state; @XmlElement(name = "FullNumber") private String fullNumber; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLATA() { return lata; } public void setLATA(String lata) { this.lata = lata; } public String getRateCenter() { return rateCenter; } public void setRateCenter(String rateCenter) { this.rateCenter = rateCenter; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getFullNumber() { return fullNumber; } public void setFullNumber(String fullNumber) { this.fullNumber = fullNumber; } }
2,283
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BandwidthNumberProvisioningManager.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/BandwidthNumberProvisioningManager.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.provisioning.number.bandwidth; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import javax.servlet.sip.SipURI; import javax.xml.stream.XMLInputFactory; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.utils.URIBuilder; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; import org.restcomm.connect.provisioning.number.api.ContainerConfiguration; import org.restcomm.connect.provisioning.number.api.PhoneNumber; import org.restcomm.connect.provisioning.number.api.PhoneNumberParameters; import org.restcomm.connect.provisioning.number.api.PhoneNumberProvisioningManager; import org.restcomm.connect.provisioning.number.api.PhoneNumberSearchFilters; import org.restcomm.connect.provisioning.number.api.PhoneNumberType; import org.restcomm.connect.provisioning.number.api.ProvisionProvider; import org.restcomm.connect.provisioning.number.bandwidth.utils.XmlUtils; import com.google.i18n.phonenumbers.PhoneNumberUtil; /** * @author [email protected] */ public class BandwidthNumberProvisioningManager implements PhoneNumberProvisioningManager { private static final Logger logger = Logger.getLogger(BandwidthNumberProvisioningManager.class); protected String uri, username, password, accountId, siteId; protected Configuration activeConfiguration; protected ContainerConfiguration containerConfiguration; protected boolean telestaxProxyEnabled; private DefaultHttpClient httpClient; private XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); public BandwidthNumberProvisioningManager() { } /* * (non-Javadoc) * * @see * PhoneNumberProvisioningManager#init(org.apache.commons.configuration * .Configuration, boolean) */ @Override public void init(org.apache.commons.configuration.Configuration phoneNumberProvisioningConfiguration, org.apache.commons.configuration.Configuration telestaxProxyConfiguration, ContainerConfiguration containerConfiguration) { this.containerConfiguration = containerConfiguration; telestaxProxyEnabled = telestaxProxyConfiguration.getBoolean("enabled", false); if (telestaxProxyEnabled) { uri = telestaxProxyConfiguration.getString("uri"); username = telestaxProxyConfiguration.getString("login"); password = telestaxProxyConfiguration.getString("password"); accountId = telestaxProxyConfiguration.getString("endpoint"); siteId = telestaxProxyConfiguration.getString("siteId"); activeConfiguration = telestaxProxyConfiguration; } else { Configuration bandwidthConfiguration = phoneNumberProvisioningConfiguration.subset("bandwidth"); uri = bandwidthConfiguration.getString("uri"); username = bandwidthConfiguration.getString("username"); password = bandwidthConfiguration.getString("password"); accountId = bandwidthConfiguration.getString("accountId"); siteId = bandwidthConfiguration.getString("siteId"); activeConfiguration = bandwidthConfiguration; } httpClient = new DefaultHttpClient(); Credentials credentials = new UsernamePasswordCredentials(username, password); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, credentials); } public List<String> getAvailableCountries() { List<String> countries = new ArrayList<String>(); countries.add("US"); return countries; } public boolean buyNumber(PhoneNumber phoneNumberObject, PhoneNumberParameters parameters) { String phoneNumber = phoneNumberObject.getPhoneNumber(); boolean isSucceeded = false; phoneNumber = phoneNumber.substring(2); //we don't want the +1 Order order = new Order(); order.setSiteId(this.siteId); order.setName("Order For Number: " + phoneNumber); ExistingTelephoneNumberOrderType existingTelephoneNumberOrderType = new ExistingTelephoneNumberOrderType(); existingTelephoneNumberOrderType.getTelephoneNumberList().add(phoneNumber); order.setExistingTelephoneNumberOrderType(existingTelephoneNumberOrderType); try { HttpPost post = new HttpPost(buildOrdersUri()); String xml = XmlUtils.toXml(order); StringEntity entity = new StringEntity(xml, ContentType.APPLICATION_XML); post.setEntity(entity); if (telestaxProxyEnabled) addTelestaxProxyHeaders(post, ProvisionProvider.REQUEST_TYPE.ASSIGNDID.name()); OrderResponse response = (OrderResponse) XmlUtils.fromXml(executeRequest(post), OrderResponse.class); if (response.getOrder().getExistingTelephoneNumberOrderType().getTelephoneNumberList().get(0).equals(phoneNumber)) { isSucceeded = true; } } catch (Exception e) { logger.error("Error creating order: " + e.getMessage()); isSucceeded = false; } return isSucceeded; } public boolean cancelNumber(PhoneNumber phoneNumberObj) { String phoneNumber = phoneNumberObj.getPhoneNumber(); boolean isSucceeded = false; phoneNumber = phoneNumber.substring(2); DisconnectTelephoneNumberOrder order = new DisconnectTelephoneNumberOrder(); order.setName("Disconnect Order For Number: " + phoneNumber); DisconnectTelephoneNumberOrderType disconnectTelephoneNumberOrderType = new DisconnectTelephoneNumberOrderType(); disconnectTelephoneNumberOrderType.getTelephoneNumberList().add(phoneNumber); order.setDisconnectTelephoneNumberOrderType(disconnectTelephoneNumberOrderType); try { HttpPost post = new HttpPost(buildDisconnectsUri()); StringEntity entity = new StringEntity(XmlUtils.toXml(order), ContentType.APPLICATION_XML); post.setEntity(entity); if (telestaxProxyEnabled) addTelestaxProxyHeaders(post, ProvisionProvider.REQUEST_TYPE.RELEASEDID.name()); DisconnectTelephoneNumberOrderResponse response = (DisconnectTelephoneNumberOrderResponse) XmlUtils.fromXml(executeRequest(post), DisconnectTelephoneNumberOrderResponse.class); if (response.getErrorList().size() == 0 && response.getorderRequest(). getDisconnectTelephoneNumberOrderType().getTelephoneNumberList().get(0).equals(phoneNumber)) { isSucceeded = true; } //TODO: get order status and check it before returning. } catch (Exception e) { logger.error(String.format("Error disconnecting number: %s : %s ", phoneNumber, e.getMessage())); isSucceeded = false; } return isSucceeded; } /* * (non-Javadoc) * * @see * PhoneNumberProvisioningManager#searchForNumbers(java.lang.String, * java.lang.String, java.util.regex.Pattern, boolean, boolean, boolean, boolean, int, int) */ @Override public List<PhoneNumber> searchForNumbers(String country, PhoneNumberSearchFilters listFilters) { List<PhoneNumber> availableNumbers = new ArrayList<PhoneNumber>(); if (logger.isDebugEnabled()) { logger.debug("searchPattern: " + listFilters.getFilterPattern()); } try { String uri = buildSearchUri(listFilters); HttpGet httpGet = new HttpGet(uri); if (telestaxProxyEnabled) addTelestaxProxyHeaders(httpGet, ProvisionProvider.REQUEST_TYPE.GETDIDS.name()); String response = executeRequest(httpGet); availableNumbers = toPhoneNumbers((SearchResult) XmlUtils.fromXml(response, SearchResult.class)); return availableNumbers; } catch (Exception e) { logger.error("Could not execute search request: " + uri, e); } return availableNumbers; } public boolean updateNumber(PhoneNumber phoneNumberObj, PhoneNumberParameters parameters) { return true; } private String buildDisconnectsUri() throws URISyntaxException { URIBuilder builder = new URIBuilder(this.uri); builder.setPath("/v1.0/accounts/" + this.accountId + "/disconnects"); return builder.build().toString(); } private String buildOrdersUri() throws URISyntaxException { URIBuilder builder = new URIBuilder(this.uri); builder.setPath("/v1.0/accounts/" + this.accountId + "/orders"); return builder.build().toString(); } private String buildSearchUri(PhoneNumberSearchFilters filters) throws URISyntaxException { Pattern filterPattern = filters.getFilterPattern(); URIBuilder builder = new URIBuilder(this.uri); builder.setPath("/v1.0/accounts/" + this.accountId + "/availableNumbers"); //Local number type search if (filters.getPhoneNumberTypeSearch().equals(PhoneNumberType.Local)) { if (!StringUtils.isEmpty(filters.getAreaCode())) { builder.addParameter("areaCode", filters.getAreaCode()); } if (!StringUtils.isEmpty(filters.getInLata())) { builder.addParameter("lata", filters.getInLata()); } if (!StringUtils.isEmpty(filters.getInPostalCode())) { builder.addParameter("zip", filters.getInPostalCode()); } if (!StringUtils.isEmpty(filters.getInRateCenter())) { builder.addParameter("rateCenter", filters.getInRateCenter()); builder.addParameter("state", filters.getInRegion()); } builder.addParameter("enableTNDetail", String.valueOf(true)); } else if (filters.getPhoneNumberTypeSearch().equals(PhoneNumberType.TollFree)) { //Make some assumptions for the user if (filterPattern == null || StringUtils.isEmpty(filterPattern.toString())) { builder.addParameter("tollFreeWildCardPattern", "8**"); } else { if (filterPattern.toString().contains("*")) { builder.addParameter("tollFreeWildCardPattern", filterPattern.toString()); } else { builder.addParameter("tollFreeVanity", filterPattern.toString()); } } } else { logger.error("Phone Number Type: " + filters.getPhoneNumberTypeSearch().name() + " is not supported"); } builder.addParameter("quantity", String.valueOf(filters.getRangeSize() == -1 ? 5 : filters.getRangeSize())); if(logger.isDebugEnabled()) { logger.debug("building uri: " + builder.build().toString()); } return builder.build().toString(); } protected String executeRequest(HttpUriRequest request) throws IOException { String response = ""; try { HttpResponse httpResponse = httpClient.execute(request); response = httpResponse.getEntity() != null ? EntityUtils.toString(httpResponse.getEntity()) : ""; } catch (ClientProtocolException cpe) { logger.error("Error in execute request: " + cpe.getMessage()); throw new IOException(cpe); } return response; } private List<PhoneNumber> toPhoneNumbers(final SearchResult searchResult) { final List<PhoneNumber> numbers = new ArrayList<>(); if (searchResult.getTelephoneNumberDetailList().size() > 0) { for (final TelephoneNumberDetail detail : searchResult.getTelephoneNumberDetailList()) { String name = getFriendlyName(detail.getFullNumber(), "US"); final PhoneNumber phoneNumber = new PhoneNumber(name, name, Integer.parseInt(detail.getLATA()), detail.getRateCenter(), null, null, detail.getState(), null, "US", null, true, true, false, false, false); numbers.add(phoneNumber); } } else if (searchResult.getTelephoneNumberList().size() > 0) { for (final String number : searchResult.getTelephoneNumberList()) { String name = getFriendlyName(number, "US"); final PhoneNumber phoneNumber = new PhoneNumber(name, name, null, null, null, null, null, null, "US", null, true, true, false, false, false); numbers.add(phoneNumber); } } return numbers; } private String getFriendlyName(final String number, String countryCode) { try { PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); com.google.i18n.phonenumbers.Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(number, countryCode); String friendlyName = phoneNumberUtil.format(phoneNumber, PhoneNumberUtil.PhoneNumberFormat.E164); return friendlyName; } catch (final Exception ignored) { return number; } } private void addTelestaxProxyHeaders(HttpRequest httpRequest, String requestType) { //This will work as a flag for LB that this request will need to be modified and proxied to VI httpRequest.addHeader("TelestaxProxy", "true"); //Adds the Provision provider class name httpRequest.addHeader("Provider", ProvisionProvider.bandiwidthClass); //This will tell LB that this request is a getAvailablePhoneNumberByAreaCode request httpRequest.addHeader("RequestType", requestType); //This is will add the instance id for the CancelNumber request that is missing SiteId from the request body httpRequest.addHeader("SiteId", siteId); //This will let LB match the DID to a node based on the node host+port List<SipURI> uris = containerConfiguration.getOutboundInterfaces(); for (SipURI uri: uris) { httpRequest.addHeader("OutboundIntf", uri.getHost()+":"+uri.getPort()+":"+uri.getTransportParam()); } } }
15,631
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TelephoneNumberSearchFilters.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/TelephoneNumberSearchFilters.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.provisioning.number.bandwidth; /** * Created by sbarstow on 9/22/14. */ public class TelephoneNumberSearchFilters { private String inAreaCode; private String filterPattern; private String inState; private String inPostalCode; private boolean isTollFree; private int quantity = 5; private boolean returnTelephoneNumberDetails = true; private String inRateCenter; private String inLata; public boolean isReturnTelephoneNumberDetails() { return returnTelephoneNumberDetails; } public void setReturnTelephoneNumberDetails(boolean returnTelephoneNumberDetails) { this.returnTelephoneNumberDetails = returnTelephoneNumberDetails; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public String getInAreaCode() { return inAreaCode; } public void setInAreaCode(String inAreaCode) { this.inAreaCode = inAreaCode; } public String getFilterPattern() { return filterPattern; } public void setFilterPattern(String filterPattern) { this.filterPattern = filterPattern; } public String getInState() { return inState; } public void setInState(String inState) { this.inState = inState; } public String getInPostalCode() { return inPostalCode; } public void setInPostalCode(String inPostalCode) { this.inPostalCode = inPostalCode; } public boolean isTollFree() { return isTollFree; } public void setTollFree(boolean isTollFree) { this.isTollFree = isTollFree; } public String getInRateCenter() { return inRateCenter; } public void setInRateCenter(String inRateCenter) { this.inRateCenter = inRateCenter; } public String getInLata() { return inLata; } public void setInLata(String inLata) { this.inLata = inLata; } }
2,849
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DisconnectTelephoneNumberOrder.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/DisconnectTelephoneNumberOrder.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.provisioning.number.bandwidth; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "DisconnectTelephoneNumberOrder") @XmlAccessorType(XmlAccessType.FIELD) public class DisconnectTelephoneNumberOrder { @XmlElement(name = "Name") private String name; @XmlElement(name = "DisconnectTelephoneNumberOrderType") private DisconnectTelephoneNumberOrderType disconnectTelephoneNumberOrderType; public String getName() { return name; } public void setName(String name) { this.name = name; } public DisconnectTelephoneNumberOrderType getDisconnectTelephoneNumberOrderType() { return disconnectTelephoneNumberOrderType; } public void setDisconnectTelephoneNumberOrderType(DisconnectTelephoneNumberOrderType disconnectTelephoneNumberOrderType) { this.disconnectTelephoneNumberOrderType = disconnectTelephoneNumberOrderType; } }
1,906
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
XmlUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.bandwidth/src/main/java/org/restcomm/connect/provisioning/number/bandwidth/utils/XmlUtils.java
package org.restcomm.connect.provisioning.number.bandwidth.utils; import org.apache.log4j.Logger; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.ByteArrayInputStream; import java.io.StringWriter; /** * Created by sbarstow on 10/14/14. */ public class XmlUtils { private static final Logger LOG = Logger.getLogger(XmlUtils.class); private static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); public static Object fromXml(String responseBody, Class c) throws JAXBException, XMLStreamException { ByteArrayInputStream inputStream = new ByteArrayInputStream(responseBody.getBytes()); JAXBContext jaxbContext = JAXBContext.newInstance(c); XMLStreamReader xsr = xmlInputFactory.createXMLStreamReader(inputStream); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); return jaxbUnmarshaller.unmarshal(xsr); } public static String toXml(Object o) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(o.getClass()); Marshaller marshaller = jaxbContext.createMarshaller(); StringWriter writer = new StringWriter(); marshaller.marshal(o, writer); LOG.debug("toXml: " + writer.toString()); return writer.toString(); } }
1,517
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RecordingLengthTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/RecordingLengthTest.java
package org.restcomm.connect.commons; import org.junit.Test; import org.restcomm.connect.commons.util.WavUtils; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import static org.junit.Assert.assertEquals; public class RecordingLengthTest { @Test public void testDuration() throws URISyntaxException, IOException, UnsupportedAudioFileException { URI recordingFileUri = this.getClass().getClassLoader().getResource("test_recording.wav").toURI(); File recordingFile = new File(recordingFileUri); double duration = WavUtils.getAudioDuration(recordingFile); assertEquals(12, duration, 1.0); } @Test public void testDuration2() throws URISyntaxException, IOException, UnsupportedAudioFileException { URI recordingFileUri = this.getClass().getClassLoader().getResource("test_recording2.wav").toURI(); File recordingFile = new File(recordingFileUri); double duration = WavUtils.getAudioDuration(recordingFile); assertEquals(19, duration, 1.0); } }
1,155
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SupervisorActorCreationStressTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/faulttolerance/SupervisorActorCreationStressTest.java
package org.restcomm.connect.commons.faulttolerance; import static org.junit.Assert.assertTrue; import java.net.MalformedURLException; import java.net.UnknownHostException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.apache.commons.configuration.ConfigurationException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.restcomm.connect.commons.faulttolerance.tool.ActorCreatingThread; import akka.actor.ActorSystem; import org.junit.Ignore; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.WithInSecsTests; /** * @author mariafarooq * */ public class SupervisorActorCreationStressTest { protected static ActorSystem system; //nThreads the number of threads in the pool private static final int nThreads = 150; //we can increase decrease value of this to put less request to create actors from RestcommSupervisor // each of this thread will ask RestcommSupervisor to create a SimpleActor private static final int THREAD_COUNT = 300; public static AtomicInteger actorSuccessCount; public static AtomicInteger actorFailureCount; @BeforeClass public static void beforeClass() throws Exception { Config config = ConfigFactory.load("akka_fault_tolerance_application.conf"); system = ActorSystem.create("test", config ); actorSuccessCount = new AtomicInteger(); actorFailureCount = new AtomicInteger(); } @Test @Category(value={WithInSecsTests.class}) public void testCreateSampleAkkaActor() throws ConfigurationException, MalformedURLException, UnknownHostException, InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(nThreads); for (int i = 0; i < THREAD_COUNT; i++) { Runnable worker = new ActorCreatingThread(system); executor.execute(worker); } executor.shutdown(); // Wait until all threads are finish while (!executor.isTerminated()) { } Thread.sleep(THREAD_COUNT*2); System.out.println("\nFinished all threads: \n actorSuccessCount: "+actorSuccessCount+"\nactorFailureCount: "+actorFailureCount); assertTrue(actorFailureCount.get()==0); assertTrue(actorSuccessCount.get()==THREAD_COUNT); } @AfterClass public static void afterClass() throws Exception { system.shutdown(); } }
2,510
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MyUntypedActor.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/faulttolerance/tool/MyUntypedActor.java
package org.restcomm.connect.commons.faulttolerance.tool; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.faulttolerance.SupervisorActorCreationStressTest; /** * MyUntypedActor represent a restcomm-connect class that request supervisor to create actor for it * * @author mariafarooq * */ public class MyUntypedActor extends RestcommUntypedActor { private LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private final ActorSystem system; public MyUntypedActor(final ActorSystem system){ this.system = system; } @Override public void onReceive(Object message) throws Exception { final Class<?> klass = message.getClass(); if (logger.isInfoEnabled()) { logger.info(" ********** MyUntypedActor " + self().path() + " Processing Message: " + klass.getName()); } if (String.class.equals(klass)) { if (logger.isInfoEnabled()) logger.debug("create"); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new SimpleActor(); } }); ActorRef actorToBeCreated = null; try { actorToBeCreated = system.actorOf(props); if (logger.isInfoEnabled()) logger.debug("Actor created: "+actorToBeCreated.path()); SupervisorActorCreationStressTest.actorSuccessCount.incrementAndGet(); } catch (Exception e) { SupervisorActorCreationStressTest.actorFailureCount.incrementAndGet(); e.printStackTrace(); logger.error("Problem during creation of actor: "+e); } } else { unhandled(message); } } }
2,140
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SimpleActor.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/faulttolerance/tool/SimpleActor.java
package org.restcomm.connect.commons.faulttolerance.tool; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; /** * SampleActor: a simple actor to be created * * @author mariafarooq * */ public class SimpleActor extends RestcommUntypedActor { public SimpleActor(){ } @Override public void onReceive(Object message) throws Exception {} }
374
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ActorCreatingThread.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/faulttolerance/tool/ActorCreatingThread.java
package org.restcomm.connect.commons.faulttolerance.tool; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActorFactory; import akka.testkit.JavaTestKit; /** * @author mariafarooq * */ public class ActorCreatingThread implements Runnable { private final ActorSystem system; public ActorCreatingThread(final ActorSystem system){ this.system = system; } @Override public void run() { new JavaTestKit(system) { { final ActorRef self = getRef(); ActorRef actorCreator = system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new MyUntypedActor(system); } })); actorCreator.tell(new String(), self); }}; } }
953
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ObserverPatternTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/patterns/ObserverPatternTest.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.commons.patterns; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * @author [email protected] (Thomas Quintana) */ public class ObserverPatternTest { private static ActorSystem system; public ObserverPatternTest() { super(); } @BeforeClass public static void before() { system = ActorSystem.create(); } @AfterClass public static void after() { system.shutdown(); } @Test public void testSuccessScenario() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create an observable actor. final Props properties = new Props(ObservableActor.class); final ActorRef observable = system.actorOf(properties); // Start observing the observable actor. observable.tell(new Observe(observer), observer); // Verify that we are now observing the observable actor. Observing response = expectMsgClass(Observing.class); assertTrue(response.succeeded()); // Tell the observable actor to broadcast an event. observable.tell(new BroadcastHelloWorld(), observer); // Verify we get the broadcasted event. expectMsgEquals("Hello World!"); // Stop observing the observable actor. observable.tell(new StopObserving(observer), observer); } }; } @Test public void testTooManyObserversException() { new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create an observable actor. final Props properties = new Props(ObservableActor.class); final ActorRef observable = system.actorOf(properties); // Start observing the observable actor. observable.tell(new Observe(observer), observer); // Verify that we are now observing the observable actor. Observing response = expectMsgClass(Observing.class); assertTrue(response.succeeded()); // Try to observe twice. observable.tell(new Observe(observer), observer); // Verify that observing more than once is not allowed. response = expectMsgClass(Observing.class); assertFalse(response.succeeded()); assertTrue(response.cause() instanceof TooManyObserversException); // Stop observing the observable actor. observable.tell(new StopObserving(observer), observer); } }; } private static final class BroadcastHelloWorld { } private static final class ObservableActor extends RestcommUntypedActor { private final List<ActorRef> listeners; @SuppressWarnings("unused") public ObservableActor() { super(); listeners = new ArrayList<ActorRef>(); } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (Observe.class.equals(klass)) { final Observe request = (Observe) message; final ActorRef observer = request.observer(); if (!listeners.contains(observer)) { listeners.add(observer); final Observing response = new Observing(self); sender.tell(response, self); } else { final Observing response = new Observing(new TooManyObserversException("Already observing this actor.")); sender.tell(response, self); } } else if (BroadcastHelloWorld.class.equals(klass)) { for (final ActorRef listener : listeners) { listener.tell("Hello World!", self()); } } else if (StopObserving.class.equals(klass)) { final StopObserving request = (StopObserving) message; final ActorRef observer = request.observer(); if (listeners.contains(observer)) { listeners.remove(observer); } } } } }
5,640
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SidTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/sid/SidTest.java
package org.restcomm.connect.commons.sid; import static org.junit.Assert.*; import org.junit.Test; import org.restcomm.connect.commons.dao.Sid; public class SidTest { /** * testSidConversion String to Sid conversation */ @Test public void testSidConversion() { String sidString = "AC6dcfdfd531e44ae4ac30e8f97e071ab2"; try{ Sid sid = new Sid(sidString); assertTrue(sid != null); }catch(Exception e){ fail("invalid validation"); } } /** * testNewCallSid: String to Sid conversation */ @Test public void testNewCallSid() { String sidString = "ID6dcfdfd531e44ae4ac30e8f97e071122-CA6dcfdfd531e44ae4ac30e8f97e071ab2"; try{ Sid sid = new Sid(sidString); assertTrue(sid != null); }catch(Exception e){ fail("invalid validation"); } } /** * testOldCallSid: it should be supported * because from call api we can check older cdrs where sid was in old format * and sid conversion should work */ @Test public void testOldCallSid() { String sidString = "CA6dcfdfd531e44ae4ac30e8f97e071ab2"; try{ Sid sid = new Sid(sidString); assertTrue(sid != null); }catch(Exception e){ fail("invalid validation"); } } }
1,177
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CacheConfigurationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/configuration/CacheConfigurationTest.java
package org.restcomm.connect.commons.configuration; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.configuration.sets.CacheConfigurationSet; import java.net.MalformedURLException; import java.net.URL; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class CacheConfigurationTest { private static final String CACHE_PATH_VALUE = "${restcomm:home}/cache"; private static final String CACHE_URI_VALUE = "http://127.0.0.1:8080/restcomm/cache"; private RestcommConfiguration defaultCfg; private RestcommConfiguration enabledNoWavCacheCfg; private RestcommConfiguration disabledNoWavCacheCfg; private RestcommConfiguration createCfg(final String cfgFileName) throws ConfigurationException, MalformedURLException { URL url = this.getClass().getResource(cfgFileName); Configuration xml = new XMLConfiguration(url); return new RestcommConfiguration(xml); } @Before public void before() throws ConfigurationException, MalformedURLException { defaultCfg = createCfg("/restcomm.xml"); enabledNoWavCacheCfg = createCfg("/restcomm-cache-no-wav-true.xml"); disabledNoWavCacheCfg = createCfg("/restcomm-cache-no-wav-false.xml"); } public CacheConfigurationTest() { super(); } @Test public void checkCacheSection() throws ConfigurationException, MalformedURLException { CacheConfigurationSet cacheSet = defaultCfg.getCache(); assertTrue(CACHE_PATH_VALUE.equals(cacheSet.getCachePath())); assertTrue(CACHE_URI_VALUE.equals(cacheSet.getCacheUri())); } @Test public void checkNoWavCacheFlagAbsenceInCfg() { // the default value of "noWavCache" flag is "false" if <cache-no-wav> tag doesn't present in *.xml assertFalse(defaultCfg.getCache().isNoWavCache()); } @Test public void checkNoWavCacheFlagEnabledInCfg() { assertTrue(enabledNoWavCacheCfg.getCache().isNoWavCache()); } @Test public void checkNoWavCacheFlagDisabledInCfg() { assertFalse(disabledNoWavCacheCfg.getCache().isNoWavCache()); } }
2,508
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConfigurationSetTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/configuration/ConfigurationSetTest.java
package org.restcomm.connect.commons.configuration; import static org.junit.Assert.*; import org.junit.Test; import org.restcomm.connect.commons.configuration.sets.CustomConfigurationSet; import org.restcomm.connect.commons.configuration.sources.EditableConfigurationSource; public class ConfigurationSetTest { public ConfigurationSetTest() { // TODO Auto-generated constructor stub } @Test public void testValueRetrievalAndSetLifecycle() { // EditableConfigurationSource source = new EditableConfigurationSource(); source.setProperty(CustomConfigurationSet.PROPERTY1_KEY, "value1"); // test value retrieval CustomConfigurationSet customSet = new CustomConfigurationSet(source); assertTrue( customSet.getProperty1().equals("value1") ); // make sure values are properly cached by the configuration set and are not changed when source changes source.setProperty(CustomConfigurationSet.PROPERTY1_KEY, "changed_value1"); assertTrue( customSet.getProperty1().equals("value1") ); // test conf set lifecycle RestcommConfiguration conf = new RestcommConfiguration(); conf.addConfigurationSet("custom", customSet); CustomConfigurationSet customSet2 = conf.get("custom",CustomConfigurationSet.class); assertNotNull(customSet2); assertTrue( customSet.getProperty1().equals("value1") ); } }
1,433
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MgAsrConfigurationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/configuration/MgAsrConfigurationTest.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.commons.configuration; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.junit.Test; import org.restcomm.connect.commons.configuration.sets.impl.MgAsrConfigurationSet; import java.net.MalformedURLException; import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.junit.Assert.*; public class MgAsrConfigurationTest { private List<String> expectedDrivers = Arrays.asList("driver1", "driver2"); private List<String> expectedLanguages = Arrays.asList("en-US", "en-GB", "es-ES", "it-IT", "fr-FR", "pl-PL", "pt-PT"); private RestcommConfiguration createCfg(final String cfgFileName) throws ConfigurationException, MalformedURLException { URL url = this.getClass().getResource(cfgFileName); Configuration xml = new XMLConfiguration(url); return new RestcommConfiguration(xml); } public MgAsrConfigurationTest() { super(); } @Test public void checkMgAsrSection() throws ConfigurationException, MalformedURLException { MgAsrConfigurationSet conf = createCfg("/restcomm.xml").getMgAsr(); assertTrue(CollectionUtils.isEqualCollection(expectedDrivers, conf.getDrivers())); assertEquals("driver1", conf.getDefaultDriver()); } @Test public void checkNoMgAsrSection() throws ConfigurationException, MalformedURLException { MgAsrConfigurationSet conf = createCfg("/restcomm-no-mg-asr.xml").getMgAsr(); assertTrue(CollectionUtils.isEqualCollection(Collections.emptyList(), conf.getDrivers())); assertNull(conf.getDefaultDriver()); } @Test public void checkAsrLanguagesSection() throws ConfigurationException, MalformedURLException { MgAsrConfigurationSet conf = createCfg("/restcomm.xml").getMgAsr(); assertTrue(CollectionUtils.isEqualCollection(expectedLanguages, conf.getLanguages())); assertEquals("en-US", conf.getDefaultLanguage()); } @Test public void checkAsrMRT() throws ConfigurationException, MalformedURLException { MgAsrConfigurationSet conf = createCfg("/restcomm.xml").getMgAsr(); assertSame(60, conf.getAsrMRT()); } @Test public void checkDefaultGatheringTimeout() throws ConfigurationException, MalformedURLException { MgAsrConfigurationSet conf = createCfg("/restcomm.xml").getMgAsr(); assertSame(5, conf.getDefaultGatheringTimeout()); } }
3,486
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommConfigurationTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/configuration/RestcommConfigurationTest.java
package org.restcomm.connect.commons.configuration; import java.net.InetSocketAddress; import static org.junit.Assert.*; import java.net.MalformedURLException; import java.net.URL; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.commons.configuration.sets.MainConfigurationSet; import org.restcomm.connect.commons.common.http.SslMode; public class RestcommConfigurationTest { private RestcommConfiguration conf; private XMLConfiguration xml; public RestcommConfigurationTest() { super(); } @Before public void before() throws ConfigurationException, MalformedURLException { URL url = this.getClass().getResource("/restcomm.xml"); // String relativePath = "../../../../../../../../restcomm.application/src/main/webapp/WEB-INF/conf/restcomm.xml"; xml = new XMLConfiguration(); xml.setDelimiterParsingDisabled(true); xml.setAttributeSplittingDisabled(true); xml.load(url); conf = new RestcommConfiguration(xml); } @Test public void allConfiguraitonSetsAreAvailable() { assertNotNull(conf.getMain()); // add new sets here ... // ... } // Test properties for the 'Main' configuration set @Test public void mainSetConfigurationOptionsAreValid() { MainConfigurationSet main = conf.getMain(); assertEquals(SslMode.strict, main.getSslMode()); assertEquals("127.0.0.1", main.getHostname()); assertTrue(main.isUseHostnameToResolveRelativeUrls()); assertEquals(Integer.valueOf(200), main.getDefaultHttpMaxConns()); assertEquals(Integer.valueOf(20), main.getDefaultHttpMaxConnsPerRoute()); assertEquals(Integer.valueOf(30000), main.getDefaultHttpTTL()); assertEquals(2, main.getDefaultHttpRoutes().size()); InetSocketAddress addr1= new InetSocketAddress("127.0.0.1", 8080); assertEquals(Integer.valueOf(10), main.getDefaultHttpRoutes().get(addr1)); InetSocketAddress addr2= new InetSocketAddress("192.168.1.1", 80); assertEquals(Integer.valueOf(60), main.getDefaultHttpRoutes().get(addr2)); } @Test public void validSingletonOperation() { // make sure it is created RestcommConfiguration.createOnce(xml); RestcommConfiguration conf1 = RestcommConfiguration.getInstance(); assertNotNull(conf1); // make sure it's not created again for subsequent calls RestcommConfiguration.createOnce(xml); RestcommConfiguration conf2 = RestcommConfiguration.getInstance(); assertTrue( conf1 == conf2 ); } }
2,782
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EditableConfigurationSource.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/configuration/sources/EditableConfigurationSource.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.commons.configuration.sources; import org.restcomm.connect.commons.configuration.sources.ConfigurationSource; import java.util.HashMap; import java.util.Map; /* * Mockup configuration source. Fill it up in your tests with values that simulate the actual source * * @author [email protected] (Orestis Tsakiridis) */ public class EditableConfigurationSource implements ConfigurationSource { Map<String,String> properties = new HashMap<String,String>(); public EditableConfigurationSource() { // TODO Auto-generated constructor stub } public Map<String, String> getProperties() { return properties; } @Override public String getProperty(String key) { return properties.get(key); } @Override public String getProperty (String key, String defValue) { String result = properties.get(key); if (key == null || key.isEmpty()) result = defValue; return result; } public void setProperty(String key, String value) { properties.put(key, value); } }
1,925
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CustomConfigurationSet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/configuration/sets/CustomConfigurationSet.java
package org.restcomm.connect.commons.configuration.sets; import org.restcomm.connect.commons.configuration.sets.impl.ConfigurationSet; import org.restcomm.connect.commons.configuration.sources.ConfigurationSource; public class CustomConfigurationSet extends ConfigurationSet { public static final String PROPERTY1_KEY = "property1"; private String property1; public CustomConfigurationSet(ConfigurationSource source) { super(source); property1 = source.getProperty(PROPERTY1_KEY); } public String getProperty1() { return property1; } }
594
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z