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 |
---|---|---|---|---|---|---|---|---|---|---|---|
DataCoding.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/DataCoding.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.sms.smpp;
public class DataCoding {
public static final byte DATA_CODING_GSM7 = 0;
public static final byte DATA_CODING_GSM8 = 4;
public static final byte DATA_CODING_UCS2 = 8;
}
| 1,142 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Smpp.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/Smpp.java | package org.restcomm.connect.sms.smpp;
import org.apache.log4j.Logger;
import com.cloudhopper.commons.charset.Charset;
import com.cloudhopper.commons.charset.CharsetUtil;
import com.cloudhopper.smpp.SmppBindType;
import com.cloudhopper.smpp.impl.DefaultSmppSession;
import com.cloudhopper.smpp.type.Address;
/**
*
* @author amit bhayani
*
*/
public class Smpp {
private static final Logger logger = Logger.getLogger(Smpp.class);
private static final String DEFAULT_SMPP_INBOUND_ENCODING = "MODIFIED-UTF8";
private static final String DEFAULT_SMPP_OUTBOUND_ENCODING = "GSM";
private String name;
private String systemId;
private String peerIp;
private int peerPort;
private SmppBindType smppBindType;
private String password;
private String systemType;
private byte interfaceVersion;
private Address address;
private long connectTimeout;
private int windowSize;
private long windowWaitTimeout;
// if > 0, then activated
private long requestExpiryTimeout;
private long windowMonitorInterval;
private boolean countersEnabled;
private boolean logBytes;
private long enquireLinkDelay;
private Charset inboundCharacterEncoding;
private Charset outboundCharacterEncoding;
private boolean messagePayloadFlag;
private boolean autoDetectDcsFlag;
// not used as of today, but later we can allow users to stop each SMPP
private boolean started = true;
private transient DefaultSmppSession defaultSmppSession = null;
public Smpp(String name, String systemId, String peerIp, int peerPort, SmppBindType smppBindType, String password,
String systemType, byte interfaceVersion, Address address, long connectTimeout, int windowSize,
long windowWaitTimeout, long requestExpiryTimeout, long windowMonitorInterval, boolean countersEnabled,
boolean logBytes, long enquireLinkDelay, String inboundCharacterEncoding, String outboundCharacterEncoding, boolean messagePayloadFlag, boolean autoDetectDcsFlag) {
super();
this.name = name;
this.systemId = systemId;
this.peerIp = peerIp;
this.peerPort = peerPort;
this.smppBindType = smppBindType;
this.password = password;
this.systemType = systemType;
this.interfaceVersion = interfaceVersion;
this.address = address;
this.connectTimeout = connectTimeout;
this.windowSize = windowSize;
this.windowWaitTimeout = windowWaitTimeout;
this.requestExpiryTimeout = requestExpiryTimeout;
this.windowMonitorInterval = windowMonitorInterval;
this.countersEnabled = countersEnabled;
this.logBytes = logBytes;
this.enquireLinkDelay = enquireLinkDelay;
try {
this.inboundCharacterEncoding = CharsetUtil.map(inboundCharacterEncoding);
} catch (Exception e) {
this.inboundCharacterEncoding = CharsetUtil.map(DEFAULT_SMPP_INBOUND_ENCODING);
if(logger.isInfoEnabled()) {
logger.info("Charset " + inboundCharacterEncoding + " does not exist. Inbound encoding is set to default " + DEFAULT_SMPP_INBOUND_ENCODING + "\n" + e.getMessage());
}
}
try {
this.outboundCharacterEncoding = CharsetUtil.map(outboundCharacterEncoding);
} catch (Exception e) {
this.outboundCharacterEncoding = CharsetUtil.map(DEFAULT_SMPP_OUTBOUND_ENCODING);
if(logger.isInfoEnabled()) {
logger.info("Charset " + outboundCharacterEncoding+ " does not exist. Outbound encoding is set to default " + DEFAULT_SMPP_OUTBOUND_ENCODING + "\n" + e.getMessage());
}
}
this.messagePayloadFlag = messagePayloadFlag;
this.autoDetectDcsFlag = autoDetectDcsFlag;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public String getPeerIp() {
return peerIp;
}
public void setPeerIp(String peerIp) {
this.peerIp = peerIp;
}
public int getPeerPort() {
return peerPort;
}
public void setPeerPort(int peerPort) {
this.peerPort = peerPort;
}
public SmppBindType getSmppBindType() {
return smppBindType;
}
public void setSmppBindType(SmppBindType smppBindType) {
this.smppBindType = smppBindType;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSystemType() {
return systemType;
}
public void setSystemType(String systemType) {
this.systemType = systemType;
}
public byte getInterfaceVersion() {
return interfaceVersion;
}
public void setInterfaceVersion(byte interfaceVersion) {
this.interfaceVersion = interfaceVersion;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(long connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getWindowSize() {
return windowSize;
}
public void setWindowSize(int windowSize) {
this.windowSize = windowSize;
}
public long getWindowWaitTimeout() {
return windowWaitTimeout;
}
public void setWindowWaitTimeout(long windowWaitTimeout) {
this.windowWaitTimeout = windowWaitTimeout;
}
public long getRequestExpiryTimeout() {
return requestExpiryTimeout;
}
public void setRequestExpiryTimeout(long requestExpiryTimeout) {
this.requestExpiryTimeout = requestExpiryTimeout;
}
public long getWindowMonitorInterval() {
return windowMonitorInterval;
}
public void setWindowMonitorInterval(long windowMonitorInterval) {
this.windowMonitorInterval = windowMonitorInterval;
}
public boolean isCountersEnabled() {
return countersEnabled;
}
public void setCountersEnabled(boolean countersEnabled) {
this.countersEnabled = countersEnabled;
}
public boolean isLogBytes() {
return logBytes;
}
public void setLogBytes(boolean logBytes) {
this.logBytes = logBytes;
}
public long getEnquireLinkDelay() {
return enquireLinkDelay;
}
public void setEnquireLinkDelay(long enquireLinkDelay) {
this.enquireLinkDelay = enquireLinkDelay;
}
public Charset getInboundDefaultEncoding() {
return inboundCharacterEncoding;
}
public Charset getOutboundDefaultEncoding() {
return outboundCharacterEncoding;
}
public boolean getMessagePayloadFlag() {
return messagePayloadFlag;
}
public boolean getAutoDetectDcsFlag() {
return autoDetectDcsFlag;
}
public boolean isStarted() {
return started;
}
public void setStarted(boolean started) {
this.started = started;
if (this.started == false) {
this.defaultSmppSession.close(5000);
}
}
public DefaultSmppSession getSmppSession() {
return defaultSmppSession;
}
public void setSmppSession(DefaultSmppSession smppSession) {
this.defaultSmppSession = smppSession;
}
@Override
public String toString() {
return "Smpp [name=" + name + ", systemId=" + systemId + ", peerIp=" + peerIp + ", peerPort=" + peerPort
+ ", smppBindType=" + smppBindType + ", password=" + password + ", systemType=" + systemType
+ ", interfaceVersion=" + interfaceVersion + ", address=" + address + ", connectTimeout=" + connectTimeout
+ ", windowSize=" + windowSize + ", windowWaitTimeout=" + windowWaitTimeout + ", requestExpiryTimeout="
+ requestExpiryTimeout + ", windowMonitorInterval=" + windowMonitorInterval + ", countersEnabled="
+ countersEnabled + ", logBytes=" + logBytes + ", enquireLinkDelay=" + enquireLinkDelay
+ ", inboundCharacterEncoding=" + inboundCharacterEncoding.toString()
+ ", outboundCharacterEncoding=" + outboundCharacterEncoding.toString()
+ "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Smpp other = (Smpp) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
| 9,227 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmppClientOpsThread.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/SmppClientOpsThread.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.sms.smpp;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.servlet.ServletException;
import org.apache.log4j.Logger;
import org.restcomm.connect.sms.smpp.dlr.provider.TelestaxDlrParser;
import org.restcomm.connect.sms.smpp.dlr.spi.DLRPayload;
import org.restcomm.connect.sms.smpp.dlr.spi.DlrParser;
import com.cloudhopper.commons.charset.Charset;
import com.cloudhopper.commons.charset.CharsetUtil;
import com.cloudhopper.smpp.PduAsyncResponse;
import com.cloudhopper.smpp.SmppConstants;
import com.cloudhopper.smpp.SmppSession;
import com.cloudhopper.smpp.SmppSessionConfiguration;
import com.cloudhopper.smpp.SmppSessionHandler;
import com.cloudhopper.smpp.impl.DefaultSmppClient;
import com.cloudhopper.smpp.impl.DefaultSmppSession;
import com.cloudhopper.smpp.pdu.DeliverSm;
import com.cloudhopper.smpp.pdu.EnquireLink;
import com.cloudhopper.smpp.pdu.EnquireLinkResp;
import com.cloudhopper.smpp.pdu.PduRequest;
import com.cloudhopper.smpp.pdu.PduResponse;
import com.cloudhopper.smpp.tlv.Tlv;
import com.cloudhopper.smpp.type.Address;
import com.cloudhopper.smpp.type.RecoverablePduException;
import com.cloudhopper.smpp.type.UnrecoverablePduException;
import akka.actor.ActorRef;
/**
* @author amit bhayani
* @author [email protected]
*/
public class SmppClientOpsThread implements Runnable {
private static final Logger logger = Logger
.getLogger(SmppClientOpsThread.class);
private static final long SCHEDULE_CONNECT_DELAY = 1000 * 30; // 30 sec
private List<ChangeRequest> pendingChanges = new CopyOnWriteArrayList<ChangeRequest>();
private Object waitObject = new Object();
private final DefaultSmppClient clientBootstrap;
private static SmppSession getSmppSession;
//FIXME: like getSmppSession, this is bad design
//this assumes singular SMPP connection all the time,so it works
private static Charset outboundEncoding;
private static Charset inboundEncoding;
private static boolean messagePayloadFlag;
private static boolean autoDetectDcsFlag;
protected volatile boolean started = true;
private static int sipPort;
private final ActorRef smppMessageHandler;
public SmppClientOpsThread(DefaultSmppClient clientBootstrap, int sipPort, final ActorRef smppMessageHandler) {
this.clientBootstrap = clientBootstrap;
this.sipPort = sipPort;
this.smppMessageHandler = smppMessageHandler;
}
protected void setStarted(boolean started) {
this.started = started;
synchronized (this.waitObject) {
this.waitObject.notify();
}
}
protected void scheduleConnect(Smpp esme) {
synchronized (this.pendingChanges) {
this.pendingChanges.add(new ChangeRequest(esme,
ChangeRequest.CONNECT, System.currentTimeMillis()
+ SCHEDULE_CONNECT_DELAY));
}
synchronized (this.waitObject) {
this.waitObject.notify();
}
}
protected void scheduleEnquireLink(Smpp esme) {
synchronized (this.pendingChanges) {
this.pendingChanges.add(new ChangeRequest(esme,
ChangeRequest.ENQUIRE_LINK, System.currentTimeMillis()
+ esme.getEnquireLinkDelay()));
}
synchronized (this.waitObject) {
this.waitObject.notify();
}
}
@Override
public void run() {
if (logger.isInfoEnabled()) {
logger.info("SmppClientOpsThread started.");
}
while (this.started) {
try {
synchronized (this.pendingChanges) {
Iterator<ChangeRequest> changes = pendingChanges.iterator();
while (changes.hasNext()) {
ChangeRequest change = changes.next();
switch (change.getType()) {
case ChangeRequest.CONNECT:
if (!change.getSmpp().isStarted()) {
pendingChanges.remove(change);
// changes.remove();
} else {
if (change.getExecutionTime() <= System
.currentTimeMillis()) {
pendingChanges.remove(change);
// changes.remove();
initiateConnection(change.getSmpp());
}
}
break;
case ChangeRequest.ENQUIRE_LINK:
if (!change.getSmpp().isStarted()) {
pendingChanges.remove(change);
// changes.remove();
} else {
if (change.getExecutionTime() <= System
.currentTimeMillis()) {
pendingChanges.remove(change);
// changes.remove();
enquireLink(change.getSmpp());
}
}
break;
}
}
}
synchronized (this.waitObject) {
this.waitObject.wait(5000);
}
} catch (InterruptedException e) {
logger.error("Error while looping SmppClientOpsThread thread",
e);
}
}
if (logger.isInfoEnabled()) {
logger.info("SmppClientOpsThread for stopped.");
}
}
private void enquireLink(Smpp esme) {
SmppSession smppSession = esme.getSmppSession();
if (!esme.isStarted()) {
return;
}
if (smppSession != null && smppSession.isBound()) {
try {
EnquireLinkResp enquireLinkResp1 = smppSession.enquireLink(
new EnquireLink(), 10000);
// all ok lets scehdule another ENQUIRE_LINK
this.scheduleEnquireLink(esme);
return;
} catch (RecoverablePduException e) {
logger.warn(
String.format(
"RecoverablePduException while sending the ENQURE_LINK for ESME SystemId=%s",
esme.getSystemId()), e);
// Recoverabel exception is ok
// all ok lets schedule another ENQUIRE_LINK
this.scheduleEnquireLink(esme);
return;
} catch (Exception e) {
logger.error(
String.format(
"Exception while trying to send ENQUIRE_LINK for ESME SystemId=%s",
esme.getSystemId()), e);
// For all other exceptions lets close session and re-try
// connect
smppSession.close();
this.scheduleConnect(esme);
}
} else {
// This should never happen
logger.warn(String
.format("Sending ENQURE_LINK fialed for ESME SystemId=%s as SmppSession is =%s !",
esme.getSystemId(), (smppSession == null ? null
: smppSession.getStateName())));
if (smppSession != null) {
smppSession.close();
}
this.scheduleConnect(esme);
}
}
private void initiateConnection(Smpp esme) {
// If Esme is stopped, don't try to initiate connect
if (!esme.isStarted()) {
return;
}
SmppSession smppSession = esme.getSmppSession();
if ((smppSession != null && smppSession.isBound())
|| (smppSession != null && smppSession.isBinding())) {
// If process has already begun lets not do it again
return;
}
SmppSession session0 = null;
try {
SmppSessionConfiguration config0 = new SmppSessionConfiguration();
config0.setWindowSize(esme.getWindowSize());
config0.setName(esme.getSystemId());
config0.setType(esme.getSmppBindType());
config0.setSystemType(esme.getSystemType());
config0.setHost(esme.getPeerIp());
config0.setPort(esme.getPeerPort());
config0.setConnectTimeout(esme.getConnectTimeout());
config0.setSystemId(esme.getSystemId());
config0.setPassword(esme.getPassword());
//this will disable Enquire Link heartbeat logs printed to the console
//TODO this can be put into the restcomm.xml for Admin use
config0.getLoggingOptions().setLogBytes(false);
config0.getLoggingOptions().setLogPdu(false);
// to enable monitoring (request expiration)
config0.setRequestExpiryTimeout(esme.getRequestExpiryTimeout());
config0.setWindowMonitorInterval(esme.getWindowMonitorInterval());
config0.setCountersEnabled(esme.isCountersEnabled());
Address address = esme.getAddress();
config0.setAddressRange(address);
SmppSessionHandler sessionHandler = new ClientSmppSessionHandler(
esme);
session0 = clientBootstrap.bind(config0, sessionHandler);
//getting session to be used to process SMS received from Restcomm
getSmppSession = session0;
// Set in ESME
esme.setSmppSession((DefaultSmppSession) session0);
// Finally set Enquire Link schedule
this.scheduleEnquireLink(esme);
} catch (Exception e) {
logger.error(
String.format(
"Exception when trying to bind client SMPP connection for ESME systemId=%s",
esme.getSystemId()), e);
if (session0 != null) {
session0.close();
}
this.scheduleConnect(esme);
}
}
//*************Inner Class******************
protected class ClientSmppSessionHandler implements SmppSessionHandler {
//private final Smpp esme ;
private Smpp esme = null;
/**
* @param esme
*/
public ClientSmppSessionHandler(Smpp esme) {
super();
this.esme = esme;
inboundEncoding = esme.getInboundDefaultEncoding();
outboundEncoding = esme.getOutboundDefaultEncoding();
messagePayloadFlag = esme.getMessagePayloadFlag();
autoDetectDcsFlag = esme.getAutoDetectDcsFlag();
}
@Override
public String lookupResultMessage(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public String lookupTlvTagName(short arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void fireChannelUnexpectedlyClosed() {
logger.error("ChannelUnexpectedlyClosed for Smpp "
+ this.esme.getName()
+ " Closing Smpp session and restrting BIND process again");
this.esme.getSmppSession().close();
// Schedule the connection again
scheduleConnect(this.esme);
}
@Override
public void fireExpectedPduResponseReceived (
PduAsyncResponse pduAsyncResponse) {
// TODO : SMPP Response received. Does RestComm need confirmation
// for this?
logger.info("ExpectedPduResponseReceived received for Smpp "
+ this.esme.getName() + " PduAsyncResponse="
+ pduAsyncResponse);
//forward this to smppMessageHandle so we can potentially update the message status
smppMessageHandler.tell(pduAsyncResponse, null);
}
@Override
public void firePduRequestExpired(PduRequest pduRequest) {
// TODO : SMPP request Expired. RestComm needs to notify Application
// about SMS failure
logger.warn("PduRequestExpired for Smpp " + this.esme.getName()
+ " PduRequest=" + pduRequest);
}
@Override
public PduResponse firePduRequestReceived(PduRequest pduRequest) {
PduResponse response = pduRequest.createResponse();
if (!pduRequest.toString().toLowerCase().contains("enquire_link")) {
try {
DeliverSm deliverSm = (DeliverSm) pduRequest;
byte dcs = deliverSm.getDataCoding();
String destSmppAddress = deliverSm.getDestAddress().getAddress();
String sourceSmppAddress = deliverSm.getSourceAddress().getAddress();
//this default esme encoding only applies to DCS==0
Charset encoding = esme.getInboundDefaultEncoding();
if(dcs == SmppConstants.DATA_CODING_UCS2) {
encoding = CharsetUtil.CHARSET_UCS_2;
}
byte[] pduMessage = deliverSm.getShortMessage();
int smsLength = deliverSm.getShortMessageLength();
byte esmClass = deliverSm.getEsmClass();
byte msgType = (byte)(((esmClass) >> 2) & 0x0f);
if(logger.isDebugEnabled()) {
logger.debug("deliverSm="+deliverSm.toString()+" smsLength="+smsLength+" esmClass="+Byte.toString(esmClass)+" msgType="+Byte.toString(msgType));
}
//check message_payload
if(smsLength > 0) {
if(logger.isInfoEnabled()) {
logger.info("Using message from message body " + Arrays.toString(pduMessage));
}
} else {
Tlv msgPayload = deliverSm.getOptionalParameter(SmppConstants.TAG_MESSAGE_PAYLOAD);
if(msgPayload!=null) {
pduMessage = msgPayload.getValue();
if(logger.isInfoEnabled()) {
logger.info("Using message from TAG_MESSAGE_PAYLOAD " + Arrays.toString(pduMessage));
}
} else {
//TODO: what else do we do?
logger.error("incoming message has no message body nor message_payload");
}
}
String decodedPduMessage = CharsetUtil.decode(pduMessage, encoding);
//send received SMPP PDU message to restcomm only if not DLR
if (msgType == 0x0) {
try {
sendSmppMessageToRestcomm(decodedPduMessage, destSmppAddress, sourceSmppAddress, encoding);
} catch (IOException | ServletException e) {
logger.error("Exception while trying to dispatch incoming SMPP message to Restcomm: " + e);
}
} else {
if(logger.isInfoEnabled()) {
logger.info("Message is not normal request, esmClass:" + esmClass +", Using message from message body " + decodedPduMessage);
}
DlrParser dlrParser = new TelestaxDlrParser();
DLRPayload dlrPayload = dlrParser.parseMessage(decodedPduMessage);
smppMessageHandler.tell(dlrPayload, null);
}
} catch (Exception e) {
logger.error("Exception while trying to process incoming SMPP message to Restcomm: " + e);
}
}
return response;
}
@Override
public void fireRecoverablePduException(RecoverablePduException e) {
logger.warn("RecoverablePduException received for Smpp "
+ this.esme.getName(), e);
}
@Override
public void fireUnexpectedPduResponseReceived(PduResponse pduResponse) {
logger.warn("UnexpectedPduResponseReceived received for Smpp "
+ this.esme.getName() + " PduResponse=" + pduResponse);
}
@Override
public void fireUnknownThrowable(Throwable e) {
logger.error("UnknownThrowable for Smpp " + this.esme.getName()
+ " Closing Smpp session and restarting BIND process again",
e);
// TODO is this ok?
this.esme.getSmppSession().close();
// Schedule the connection again
scheduleConnect(this.esme);
}
@Override
public void fireUnrecoverablePduException(UnrecoverablePduException e) {
logger.error(
"UnrecoverablePduException for Smpp "
+ this.esme.getName()
+ " Closing Smpp session and restrting BIND process again",
e);
this.esme.getSmppSession().close();
// Schedule the connection again
scheduleConnect(this.esme);
}
}
//smpp session to be used for sending SMS from Restcomm to smpp endpoint
public static SmppSession getSmppSession() {
return getSmppSession;
}
public void sendSmppMessageToRestcomm(String smppMessage, String smppTo, String smppFrom, Charset charset) throws IOException, ServletException {
SmppSession smppSession = SmppClientOpsThread.getSmppSession();
String to = smppTo;
String from = smppFrom;
String inboundMessage = smppMessage;
SmppInboundMessageEntity smppInboundMessage = new SmppInboundMessageEntity(to, from, inboundMessage, charset);
smppMessageHandler.tell(smppInboundMessage, null);
}
public static Charset getInboundDefaultEncoding() {
return inboundEncoding;
}
public static Charset getOutboundDefaultEncoding() {
return outboundEncoding;
}
public static boolean getMessagePayloadFlag() {
return messagePayloadFlag;
}
public static boolean getAutoDetectDcsFlag() {
return autoDetectDcsFlag;
}
}
| 19,775 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ChangeRequest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/ChangeRequest.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.sms.smpp;
/**
* @author amit bhayani
*
*/
public final class ChangeRequest {
public static final int CONNECT = 0;
public static final int ENQUIRE_LINK = 2;
private int type;
private Smpp smpp;
private long executionTime;
/**
*
*/
public ChangeRequest(Smpp smpp, int type, long executionTime) {
this.smpp = smpp;
this.type = type;
this.executionTime = executionTime;
}
/**
* @return the type
*/
protected int getType() {
return type;
}
/**
* @return the esme
*/
protected Smpp getSmpp() {
return smpp;
}
/**
* @return the executionTime
*/
protected long getExecutionTime() {
return executionTime;
}
}
| 1,715 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ErrorCodeMapper.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/ErrorCodeMapper.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.sms.smpp;
import com.cloudhopper.smpp.SmppConstants;
import static com.cloudhopper.smpp.SmppConstants.STATUS_DELIVERYFAILURE;
import static com.cloudhopper.smpp.SmppConstants.STATUS_THROTTLED;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
public class ErrorCodeMapper {
private static final Logger logger = Logger.getLogger(ErrorCodeMapper.class);
private static final Map<Integer, org.restcomm.connect.commons.dao.MessageError> errorMap;
static {
errorMap = new HashMap<>();
errorMap.put(STATUS_THROTTLED, org.restcomm.connect.commons.dao.MessageError.LANDLINE_OR_UNREACHABLE_CARRIER);
errorMap.put(STATUS_DELIVERYFAILURE, org.restcomm.connect.commons.dao.MessageError.LANDLINE_OR_UNREACHABLE_CARRIER);
}
public static org.restcomm.connect.commons.dao.MessageError parseRestcommErrorCode(int errCode) {
org.restcomm.connect.commons.dao.MessageError error = null;
if (SmppConstants.STATUS_OK == errCode) {
//set to null so no error is shown
error = null;
} else if (errorMap.containsKey(errCode)) {
error = errorMap.get(errCode);
} else {
//if error is not in mapping table, set it to unknown
error = org.restcomm.connect.commons.dao.MessageError.UNKNOWN_ERROR;
}
if (logger.isDebugEnabled()) {
logger.debug("Mapped to: " + error);
}
return error;
}
}
| 2,315 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmppMessageHandler.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/SmppMessageHandler.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.sms.smpp;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import com.cloudhopper.commons.charset.CharsetUtil;
import com.cloudhopper.smpp.PduAsyncResponse;
import com.cloudhopper.smpp.SmppConstants;
import com.cloudhopper.smpp.impl.DefaultPduAsyncResponse;
import com.cloudhopper.smpp.pdu.SubmitSm;
import com.cloudhopper.smpp.pdu.SubmitSmResp;
import com.cloudhopper.smpp.tlv.Tlv;
import com.cloudhopper.smpp.type.Address;
import com.cloudhopper.smpp.type.RecoverablePduException;
import com.cloudhopper.smpp.type.SmppChannelException;
import com.cloudhopper.smpp.type.SmppInvalidArgumentException;
import com.cloudhopper.smpp.type.SmppTimeoutException;
import com.cloudhopper.smpp.type.UnrecoverablePduException;
import org.apache.commons.configuration.Configuration;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.core.service.RestcommConnectServiceProvider;
import org.restcomm.connect.core.service.util.UriUtils;
import org.restcomm.connect.core.service.api.NumberSelectorService;
import org.restcomm.connect.dao.AccountsDao;
import org.restcomm.connect.dao.ApplicationsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.SmsMessagesDao;
import org.restcomm.connect.dao.entities.Application;
import org.restcomm.connect.dao.entities.IncomingPhoneNumber;
import org.restcomm.connect.dao.entities.Notification;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionFeatureAccessRequest;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
import org.restcomm.connect.extension.controller.ExtensionController;
import org.restcomm.connect.http.client.rcmlserver.resolver.RcmlserverResolver;
import org.restcomm.connect.interpreter.StartInterpreter;
import org.restcomm.connect.monitoringservice.MonitoringService;
import org.restcomm.connect.sms.SmsSession;
import org.restcomm.connect.sms.smpp.dlr.spi.DLRPayload;
import org.restcomm.connect.telephony.api.FeatureAccessRequest;
import org.restcomm.smpp.parameter.TlvSet;
import javax.servlet.ServletContext;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipURI;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import org.restcomm.connect.sms.SmsService;
import org.restcomm.connect.sms.api.SmsSessionInfo;
import org.restcomm.connect.sms.api.SmsStatusUpdated;
public class SmppMessageHandler extends RestcommUntypedActor {
private static final int SEND_TIMEOUT = 10000;
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
private final ServletContext servletContext;
private final DaoManager storage;
private final Configuration configuration;
private final SipFactory sipFactory;
private final ActorRef monitoringService;
private final NumberSelectorService numberSelector;
private final ActorRef smsService;
//List of extensions for SmsService
List<RestcommExtensionGeneric> extensions;
private UriUtils uriUtils;
public SmppMessageHandler(final ServletContext servletContext) {
this.servletContext = servletContext;
this.storage = (DaoManager) servletContext.getAttribute(DaoManager.class.getName());
this.configuration = (Configuration) servletContext.getAttribute(Configuration.class.getName());
this.sipFactory = (SipFactory) servletContext.getAttribute(SipFactory.class.getName());
this.monitoringService = (ActorRef) servletContext.getAttribute(MonitoringService.class.getName());
numberSelector = (NumberSelectorService) servletContext.getAttribute(NumberSelectorService.class.getName());
//FIXME:Should new ExtensionType.SmppMessageHandler be defined?
extensions = ExtensionController.getInstance().getExtensions(ExtensionType.SmsService);
if (logger.isInfoEnabled()) {
logger.info("SmsService extensions: " + (extensions != null ? extensions.size() : "0"));
}
smsService = (ActorRef) servletContext.getAttribute(SmsService.class.getName());
uriUtils = RestcommConnectServiceProvider.getInstance().uriUtils();
}
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef sender = sender();
if (logger.isInfoEnabled()) {
logger.info(" ********** SmppMessageHandler " + self().path() + ", Processing Message: " + klass.getName()
+ " Sender is: " + sender.path() + " Message is: " + message);
}
if (message instanceof SmppInboundMessageEntity) {
if (logger.isInfoEnabled()) {
logger.info("SmppMessageHandler processing Inbound Message " + message.toString());
}
inbound((SmppInboundMessageEntity) message);
} else if (message instanceof SmppOutboundMessageEntity) {
if (logger.isInfoEnabled()) {
logger.info("SmppMessageHandler processing Outbound Message " + message.toString());
}
outbound((SmppOutboundMessageEntity) message);
} else if (message instanceof DLRPayload) {
onDLR((DLRPayload) message);
} else if (message instanceof PduAsyncResponse) {
PduAsyncResponse pduAsyncResponse = (PduAsyncResponse) message;
if (pduAsyncResponse instanceof DefaultPduAsyncResponse && pduAsyncResponse.getResponse() instanceof SubmitSmResp) {
onSubmitResponse(pduAsyncResponse);
} else {
logger.info("PduAsyncResponse not SubmitSmResp " + pduAsyncResponse.getClass().toString());
}
}
}
private void onSubmitResponse(PduAsyncResponse pduAsyncResponse) {
final SubmitSmResp submitSmResp = (SubmitSmResp) pduAsyncResponse.getResponse();
if (logger.isInfoEnabled()) {
logger.info(" ********** SmppMessageHandler received SubmitSmResp: " + submitSmResp + "SubmitSmResp Status:" + submitSmResp.getCommandStatus());
}
final String smppMessageId = submitSmResp.getMessageId();
final Object ref = pduAsyncResponse.getRequest().getReferenceObject();
if (ref != null && ref instanceof Sid) {
// BS-230: Ensure there is no other message sharing same SMPP Message ID
final List<SmsMessage> smsMessages = this.storage.getSmsMessagesDao().findBySmppMessageId(smppMessageId);
// Delete correlation between messages and SMPP Message ID
for (SmsMessage smsMessage : smsMessages) {
SmsMessage.Builder builder = SmsMessage.builder();
builder.copyMessage(smsMessage);
builder.setSmppMessageId(null);
this.storage.getSmsMessagesDao().updateSmsMessage(builder.build());
logger.warning("Correlation between SmsMessage " + smsMessage.getSid() + " and SMPP Message " + smppMessageId + " expired.");
}
// Update status of target message
SmsMessage smsMessage = storage.getSmsMessagesDao().getSmsMessage((Sid) ref);
SmsMessage.Builder builder = SmsMessage.builder();
builder.copyMessage(smsMessage);
if (submitSmResp.getCommandStatus() == SmppConstants.STATUS_OK) {
// Successful reponse: update smppMessageId as well as status to SENT and date sent
builder.setSmppMessageId(smppMessageId).setStatus(SmsMessage.Status.SENT).setDateSent(DateTime.now());
} else {
// Failure response: set status to FAILED and do not correlate to any smppMessageId
logger.warning(String.format("SubmitSmResp Failure! Message could not be sent Status Code %s Result Messages: %s", submitSmResp.getCommandStatus(), submitSmResp.getResultMessage()));
builder.setSmppMessageId(null).setStatus(SmsMessage.Status.FAILED);
org.restcomm.connect.commons.dao.MessageError err = ErrorCodeMapper.parseRestcommErrorCode(submitSmResp.getCommandStatus());
builder.setError(err);
}
SmsMessage msgUpdated = builder.build();
HashMap<String,Object> hashMap = new HashMap();
hashMap.put("record", msgUpdated);
SmsSessionInfo info = new SmsSessionInfo(msgUpdated.getSender(),
msgUpdated.getRecipient(), hashMap);
SmsStatusUpdated smsStatusUpdated = new SmsStatusUpdated(info);
smsService.tell(smsStatusUpdated, self());
} else {
logger.warning("PduAsyncResponse reference is null or not Sid");
}
}
private void onDLR(DLRPayload deliveryReceipt) {
final String smppMessageId = deliveryReceipt.getId();
final SmsMessage.Status deliveryStatus = deliveryReceipt.getStat();
if (logger.isDebugEnabled()) {
logger.debug("DLR Received for SMPP Message " + deliveryReceipt.getId() + " with status " + deliveryStatus);
}
// Find message bound to the SMPP Message ID
// NOTE: We ensure there is only one message bound to any SmppMessageId at this point because uniqueness is enforced on submit_response event
final SmsMessage sms = this.storage.getSmsMessagesDao().getSmsMessageBySmppMessageId(smppMessageId);
// Update status of message and remove correlation with SMPP Message ID
if (sms == null) {
logger.warning("responseMessageId=" + smppMessageId + " was never received!");
} else {
SmsMessage.Builder builder = SmsMessage.builder();
builder.copyMessage(sms);
builder.setSmppMessageId(null);
builder.setStatus(deliveryReceipt.getStat());
builder.setError(deliveryReceipt.getErr());
SmsMessage msgUpdated = builder.build();
HashMap<String,Object> hashMap = new HashMap();
hashMap.put("record", msgUpdated);
SmsSessionInfo info = new SmsSessionInfo(msgUpdated.getSender(),
msgUpdated.getRecipient(), hashMap);
SmsStatusUpdated smsStatusUpdated = new SmsStatusUpdated(info);
smsService.tell(smsStatusUpdated, self());
}
}
private void inbound(final SmppInboundMessageEntity request) throws IOException {
final ActorRef self = self();
String to = request.getSmppTo();
if (redirectToHostedSmsApp(self, request, storage.getAccountsDao(), storage.getApplicationsDao(), to)) {
if (logger.isInfoEnabled()) {
logger.info("SMPP Message Accepted - A Restcomm Hosted App is Found for Number : " + to);
}
return;
} else {
logger.warning("SMPP Message Rejected : No Restcomm Hosted App Found for inbound number : " + to);
}
}
static final int ERROR_NOTIFICATION = 0;
static final int WARNING_NOTIFICATION = 1;
private static final int CONTENT_LENGTH_MAX = 140;
private static final int DATA_CODING_AUTODETECT = 0x80;
// used for sending warning and error logs to notification engine and to the console
private void sendNotification(String errMessage, int errCode, String errType, boolean createNotification) {
NotificationsDao notifications = storage.getNotificationsDao();
Notification notification;
if (errType == "warning") {
logger.warning(errMessage); // send message to console
if (createNotification) {
notification = notification(WARNING_NOTIFICATION, errCode, errMessage);
notifications.addNotification(notification);
}
} else if (errType == "error") {
logger.error(errMessage); // send message to console
if (createNotification) {
notification = notification(ERROR_NOTIFICATION, errCode, errMessage);
notifications.addNotification(notification);
}
} else if (errType == "info") {
if (logger.isInfoEnabled()) {
logger.info(errMessage); // send message to console
}
}
}
private Notification notification(final int log, final int error, final String message) {
String version = configuration.subset("runtime-settings").getString("api-version");
Sid accountId = new Sid("ACae6e420f425248d6a26948c17a9e2acf");
// Sid callSid = new Sid("CA00000000000000000000000000000000");
final Notification.Builder builder = Notification.builder();
final Sid sid = Sid.generate(Sid.Type.NOTIFICATION);
builder.setSid(sid);
// builder.setAccountSid(accountId);
builder.setAccountSid(accountId);
// builder.setCallSid(callSid);
builder.setApiVersion(version);
builder.setLog(log);
builder.setErrorCode(error);
final String base = configuration.subset("runtime-settings").getString("error-dictionary-uri");
StringBuilder buffer = new StringBuilder();
buffer.append(base);
if (!base.endsWith("/")) {
buffer.append("/");
}
buffer.append(error).append(".html");
final URI info = URI.create(buffer.toString());
builder.setMoreInfo(info);
builder.setMessageText(message);
final DateTime now = DateTime.now();
builder.setMessageDate(now);
try {
builder.setRequestUrl(new URI(""));
} catch (URISyntaxException e) {
e.printStackTrace();
}
/**
* if (response != null) { builder.setRequestUrl(request.getUri());
* builder.setRequestMethod(request.getMethod());
* builder.setRequestVariables(request.getParametersAsString()); }
*
*/
builder.setRequestMethod("");
builder.setRequestVariables("");
buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/Notifications/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
return builder.build();
}
private boolean redirectToHostedSmsApp(final ActorRef self, final SmppInboundMessageEntity request, final AccountsDao accounts,
final ApplicationsDao applications, String id) throws IOException {
boolean isFoundHostedApp = false;
String to = request.getSmppTo();
String phone = to;
// Try to find an application defined for the phone number.
IncomingPhoneNumber number = numberSelector.searchNumber(phone, null, null, null);
try {
if (number != null) {
ExtensionController ec = ExtensionController.getInstance();
IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.INBOUND_SMS, number.getAccountSid());
ExtensionResponse er = ec.executePreInboundAction(far, extensions);
if (er.isAllowed()) {
ActorRef interpreter = null;
URI appUri = number.getSmsUrl();
final SmppInterpreterParams.Builder builder = new SmppInterpreterParams.Builder();
builder.setSmsService(smsService);
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setAccountId(number.getAccountSid());
builder.setVersion(number.getApiVersion());
final Sid sid = number.getSmsApplicationSid();
boolean isApplicationNull = true;
if (sid != null) {
final Application application = applications.getApplication(sid);
if (application != null) {
isApplicationNull = false;
RcmlserverConfigurationSet rcmlserverConfig = RestcommConfiguration.getInstance().getRcmlserver();
RcmlserverResolver resolver = RcmlserverResolver.getInstance(rcmlserverConfig.getBaseUrl(), rcmlserverConfig.getApiPath());
builder.setUrl(uriUtils.resolve(resolver.resolveRelative(application.getRcmlUrl()), number.getAccountSid()));
}
}
if (isApplicationNull && appUri != null) {
builder.setUrl(uriUtils.resolve(appUri, number.getAccountSid()));
} else if (isApplicationNull) {
logger.warning("the matched number doesn't have SMS application attached, number: " + number.getPhoneNumber());
return false;
}
builder.setMethod(number.getSmsMethod());
URI appFallbackUrl = number.getSmsFallbackUrl();
if (appFallbackUrl != null) {
builder.setFallbackUrl(uriUtils.resolve(number.getSmsFallbackUrl(), number.getAccountSid()));
builder.setFallbackMethod(number.getSmsFallbackMethod());
}
final Props props = SmppInterpreter.props(builder.build());
interpreter = getContext().actorOf(props);
Sid organizationSid = storage.getOrganizationsDao().getOrganization(storage.getAccountsDao().getAccount(number.getAccountSid()).getOrganizationSid()).getSid();
if (logger.isDebugEnabled()) {
logger.debug("redirectToHostedSmsApp organizationSid = " + organizationSid);
}
Configuration cfg = this.configuration;
//Extension
final ActorRef session = session(cfg, organizationSid);
session.tell(request, self);
final StartInterpreter start = new StartInterpreter(session);
interpreter.tell(start, self);
isFoundHostedApp = true;
ec.executePostOutboundAction(far, extensions);
} else {
if (logger.isDebugEnabled()) {
final String errMsg = "Inbound SMS is not Allowed";
logger.debug(errMsg);
}
String errMsg = "Inbound SMS to Number: " + number.getPhoneNumber()
+ " is not allowed";
sendNotification(errMsg, 11001, "warning", true);
ec.executePostOutboundAction(far, extensions);
return false;
}
}
} catch (Exception e) {
logger.error("Error processing inbound SMPP Message. There is no locally hosted Restcomm app for the number :" + e);
}
return isFoundHostedApp;
}
@SuppressWarnings("unchecked")
private SipURI outboundInterface() {
SipURI result = null;
final List<SipURI> uris = (List<SipURI>) servletContext.getAttribute(SipServlet.OUTBOUND_INTERFACES);
for (final SipURI uri : uris) {
final String transport = uri.getTransportParam();
if ("udp".equalsIgnoreCase(transport)) {
result = uri;
}
}
return result;
}
private ActorRef session(final Configuration p_configuration, final Sid organizationSid) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new SmsSession(p_configuration, sipFactory, outboundInterface(), storage, monitoringService, servletContext, organizationSid);
}
});
return getContext().actorOf(props);
}
public void outbound(SmppOutboundMessageEntity request) throws SmppInvalidArgumentException, IOException {
// if(logger.isInfoEnabled()) {
// logger.info("Message is Received by the SmppSessionOutbound Class");
// }
SmsMessagesDao smsDao = storage.getSmsMessagesDao();
SmsMessage msg = smsDao.getSmsMessage(request.getMessageSid());
byte[] textBytes;
int smppTonNpiValue = Integer.parseInt(SmppService.getSmppTonNpiValue());
boolean autodetectdcs = SmppClientOpsThread.getAutoDetectDcsFlag();
// add delivery receipt
//submit0.setRegisteredDelivery(SmppConstants.REGISTERED_DELIVERY_SMSC_RECEIPT_REQUESTED);
SubmitSm submit0 = new SubmitSm();
submit0.setSourceAddress(new Address((byte) smppTonNpiValue, (byte) smppTonNpiValue, request.getSmppFrom()));
submit0.setDestAddress(new Address((byte) smppTonNpiValue, (byte) smppTonNpiValue, request.getSmppTo()));
if (CharsetUtil.CHARSET_UCS_2 == request.getSmppEncoding()) {
submit0.setDataCoding(SmppConstants.DATA_CODING_UCS2);
textBytes = CharsetUtil.encode(request.getSmppContent(), CharsetUtil.CHARSET_UCS_2);
} else {
submit0.setDataCoding(SmppConstants.DATA_CODING_DEFAULT);
textBytes = CharsetUtil.encode(request.getSmppContent(), SmppClientOpsThread.getOutboundDefaultEncoding());
}
if (autodetectdcs) {
submit0.setDataCoding((byte) DATA_CODING_AUTODETECT);
}
boolean payloadFlag = SmppClientOpsThread.getMessagePayloadFlag();
int contentLength = request.getSmppContent().length();
//set the delivery flag to true
submit0.setRegisteredDelivery((byte) 1);
TlvSet tlvSet = request.getTlvSet();
if (logger.isDebugEnabled()) {
logger.debug("msg.body=" + msg.getBody() + " msg.getStatus()=" + msg.getStatus() + " payloadFlag=" + payloadFlag + " contentLength=" + contentLength + " textBytes=" + Arrays.toString(textBytes));
}
if (payloadFlag || (contentLength > CONTENT_LENGTH_MAX)) {
tlvSet.addOptionalParameter(new Tlv(SmppConstants.TAG_MESSAGE_PAYLOAD, textBytes));
} else {
submit0.setShortMessage(textBytes);
}
if (tlvSet != null) {
for (Tlv tlv : (Collection<Tlv>) tlvSet.getOptionalParameters()) {
submit0.setOptionalParameter(tlv);
}
} else if (logger.isInfoEnabled()) {
logger.info("TlvSet is null");
}
try {
if (logger.isInfoEnabled()) {
logger.info("Sending SubmitSM for " + request + " messageSid=" + request.getMessageSid());
}
submit0.setReferenceObject(request.getMessageSid());
SmppClientOpsThread.getSmppSession().sendRequestPdu(submit0, SEND_TIMEOUT, false);
} catch (RecoverablePduException | UnrecoverablePduException | SmppTimeoutException | SmppChannelException | InterruptedException e) {
logger.error("SMPP message cannot be sent : " + e);
}
}
}
| 24,636 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DLRPayload.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/dlr/spi/DLRPayload.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.sms.smpp.dlr.spi;
import org.joda.time.DateTime;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.commons.dao.MessageError;
public class DLRPayload {
private String id;
private String sub;
private String dlvrd;
private DateTime submitDate;
private DateTime doneDate;
private SmsMessage.Status stat;
private MessageError err;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSub() {
return sub;
}
public void setSub(String sub) {
this.sub = sub;
}
public String getDlvrd() {
return dlvrd;
}
public void setDlvrd(String dlvrd) {
this.dlvrd = dlvrd;
}
public DateTime getSubmitDate() {
return submitDate;
}
public void setSubmitDate(DateTime submitDate) {
this.submitDate = submitDate;
}
public DateTime getDoneDate() {
return doneDate;
}
public void setDoneDate(DateTime doneDate) {
this.doneDate = doneDate;
}
public SmsMessage.Status getStat() {
return stat;
}
public void setStat(SmsMessage.Status stat) {
this.stat = stat;
}
public MessageError getErr() {
return err;
}
public void setErr(MessageError err) {
this.err = err;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Override
public String toString() {
return "DLRPayload{" + "id=" + id + ", sub=" + sub + ", dlvrd=" + dlvrd + ", submitDate=" + submitDate + ", doneDate=" + doneDate + ", stat=" + stat + ", err=" + err + ", text=" + text + '}';
}
}
| 2,633 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DlrParser.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/dlr/spi/DlrParser.java | package org.restcomm.connect.sms.smpp.dlr.spi;
public interface DlrParser {
DLRPayload parseMessage(String message);
} | 124 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
TelestaxDlrParser.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms/src/main/java/org/restcomm/connect/sms/smpp/dlr/provider/TelestaxDlrParser.java | package org.restcomm.connect.sms.smpp.dlr.provider;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.dao.entities.SmsMessage.Status;
import org.restcomm.connect.sms.smpp.dlr.spi.DLRPayload;
import org.restcomm.connect.sms.smpp.dlr.spi.DlrParser;
import org.restcomm.connect.commons.dao.MessageError;
public class TelestaxDlrParser implements DlrParser {
private static final Logger logger = Logger.getLogger(TelestaxDlrParser.class);
private static final Map<String, SmsMessage.Status> statusMap;
private static final Map<String, MessageError> errorMap;
private static final String TAG_SEPARATOR = " ";
private static final String TAG_VALUE_SEPARATOR = ":";
private static final String ID_TAG = "id" + TAG_VALUE_SEPARATOR;
private static final String SUBMIT_TAG = "submit date" + TAG_VALUE_SEPARATOR;
private static final String DONE_TAG = "done date" + TAG_VALUE_SEPARATOR;
private static final String STAT_TAG = "stat" + TAG_VALUE_SEPARATOR;
private static final String ERR_TAG = "err" + TAG_VALUE_SEPARATOR;
private static final String DLVRD_TAG = "dlvrd" + TAG_VALUE_SEPARATOR;
private static final String SUB_TAG = "sub" + TAG_VALUE_SEPARATOR;
private static final DateTimeFormatter DLR_SENT_FORMAT = DateTimeFormat.forPattern("yyMMddHHmm");
private static final String SUCCESS_CODE = "000";
static {
statusMap = new HashMap<String, SmsMessage.Status>();
statusMap.put("ACCEPTD", SmsMessage.Status.SENT);
statusMap.put("UNDELIV", SmsMessage.Status.UNDELIVERED);
statusMap.put("EXPIRED", SmsMessage.Status.FAILED);
statusMap.put("DELETED", SmsMessage.Status.FAILED);
statusMap.put("REJECTD", SmsMessage.Status.FAILED);
statusMap.put("DELIVRD", SmsMessage.Status.DELIVERED);
statusMap.put("UNKNOWN", SmsMessage.Status.SENT);
errorMap = new HashMap<String, MessageError>();
errorMap.put("001", MessageError.UNKNOWN_DESTINATION_HANDSET);
errorMap.put("002", MessageError.UNKNOWN_DESTINATION_HANDSET);
errorMap.put("003", MessageError.UNKNOWN_DESTINATION_HANDSET);
errorMap.put("004", MessageError.MESSAGE_BLOCKED);
errorMap.put("005", MessageError.MESSAGE_BLOCKED);
errorMap.put("007", MessageError.MESSAGE_BLOCKED);
errorMap.put("008", MessageError.UNREACHABLE_DESTINATION_HANDSET);
errorMap.put("010", MessageError.LANDLINE_OR_UNREACHABLE_CARRIER);
errorMap.put("011", MessageError.UNREACHABLE_DESTINATION_HANDSET);
errorMap.put("012", MessageError.UNKNOWN_ERROR);
errorMap.put("013", MessageError.UNKNOWN_ERROR);
errorMap.put("014", MessageError.UNKNOWN_ERROR);
errorMap.put("022", MessageError.MESSAGE_BLOCKED);
errorMap.put("023", MessageError.UNREACHABLE_DESTINATION_HANDSET);
errorMap.put("034", MessageError.UNKNOWN_ERROR);
errorMap.put("038", MessageError.UNKNOWN_DESTINATION_HANDSET);
errorMap.put("039", MessageError.UNKNOWN_DESTINATION_HANDSET);
errorMap.put("040", MessageError.UNKNOWN_ERROR);
errorMap.put("045", MessageError.UNKNOWN_ERROR);
errorMap.put("051", MessageError.UNKNOWN_ERROR);
errorMap.put("194", MessageError.UNKNOWN_ERROR);
errorMap.put("224", MessageError.MESSAGE_BLOCKED);
errorMap.put("225", MessageError.MESSAGE_BLOCKED);
errorMap.put("226", MessageError.UNKNOWN_ERROR);
errorMap.put("227", MessageError.UNKNOWN_ERROR);
errorMap.put("228", MessageError.UNREACHABLE_DESTINATION_HANDSET);
errorMap.put("229", MessageError.MESSAGE_BLOCKED);
errorMap.put("230", MessageError.MESSAGE_BLOCKED);
errorMap.put("231", MessageError.CARRIER_VIOLATION);
errorMap.put("232", MessageError.UNKNOWN_DESTINATION_HANDSET);
}
private String parseTagValue(String message, String tagName) {
String tagValue = null;
int startPos = message.indexOf(tagName);
if (startPos >= 0) {
int tagStartPos = startPos + tagName.length();
final int endPos = message.indexOf(TAG_SEPARATOR, tagStartPos);
if (endPos >= 0) {
tagValue = message.substring(tagStartPos, endPos);
}
}
return tagValue;
}
/**
* Parses given string following this format
* https://help.nexmo.com/hc/en-us/articles/204015663-What-is-Nexmo-s-SMPP-DLR-format-
*
* @param message
* @return the parsed DLR
*/
@Override
public DLRPayload parseMessage(String message) {
//"id:XXXXXXXXXX sub:001 dlvrd:000 submit date:YYMMDDHHMM done date:YYMMDDHHMM stat:ZZZZZZZ err:YYY text:none
DLRPayload dlr = new DLRPayload();
final String messageId = parseTagValue(message, ID_TAG);
dlr.setId(messageId);
final String submit_date = parseTagValue(message, SUBMIT_TAG);
DateTime parsedDate = parseDate(submit_date);
dlr.setSubmitDate(parsedDate);
final String done_date = parseTagValue(message, DONE_TAG);
DateTime doneDate = parseDate(done_date);
dlr.setDoneDate(doneDate);
final String stat = parseTagValue(message, STAT_TAG);
Status parsedStatus = parseRestcommStatus(stat);
dlr.setStat(parsedStatus);
final String err = parseTagValue(message, ERR_TAG);
MessageError parsedError = parseRestcommErrorCode(err);
dlr.setErr(parsedError);
final String sub = parseTagValue(message, SUB_TAG);
dlr.setSub(sub);
final String dlv = parseTagValue(message, DLVRD_TAG);
dlr.setDlvrd(dlv);
if (logger.isDebugEnabled()) {
logger.debug("Parsed DLR is:" + dlr);
}
return dlr;
}
private DateTime parseDate(String message) {
//FIXME: should we actually have this default?
DateTime date = DateTime.now();
try {
DateTime.parse(message, DLR_SENT_FORMAT);
} catch (Exception e) {
logger.debug("failed to parse date", e);
}
return date;
}
private Status parseRestcommStatus(String message) {
/*
https://help.nexmo.com/hc/en-us/articles/204015663-What-is-Nexmo-s-SMPP-DLR-format-
DELIVRD Message is delivered to destination
EXPIRED Message validity period has expired
DELETED Message has been deleted
ACCEPTD Message is in accepted state
UNDELIV Message is undeliverable
UNKNOWN Message is in invalid state
REJECTD Message is in a rejected state
*/
Status status = null;
if (statusMap.containsKey(message)) {
status = statusMap.get(message);
} else {
logger.debug("received an unexpected Status message " + message);
}
return status;
}
private MessageError parseRestcommErrorCode(String errCode) {
MessageError error = null;
if (SUCCESS_CODE.equals(errCode)) {
//set to null so no error is shown
error = null;
} else if (errorMap.containsKey(errCode)) {
error = errorMap.get(errCode);
} else {
//if error is not in mapping table, set it to unknown
error = MessageError.UNKNOWN_ERROR;
}
if (logger.isDebugEnabled()) {
logger.debug("Mapped to: " + error);
}
return error;
}
}
| 7,671 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
VoipInnovationsBody.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/VoipInnovationsBody.java | package org.restcomm.connect.provisioning.number.vi;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
@Immutable
public final class VoipInnovationsBody {
private final Object content;
public VoipInnovationsBody(final Object content) {
super();
this.content = content;
}
public Object content() {
return content;
}
}
| 386 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
GetDIDListResponse.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/GetDIDListResponse.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.vi;
import java.util.List;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected]
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class GetDIDListResponse {
private final String name;
private final String status;
private final int code;
private final List<State> states;
public GetDIDListResponse(final String name, final String status, final int code, final List<State> states) {
super();
this.name = name;
this.status = status;
this.code = code;
this.states = states;
}
public String name() {
return name;
}
public String status() {
return status;
}
public int code() {
return code;
}
public List<State> states() {
return states;
}
}
| 1,725 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
VoipInnovationsResponse.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/VoipInnovationsResponse.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.vi;
/**
* @author [email protected] (Thomas Quintana)
*/
public final class VoipInnovationsResponse {
private final VoipInnovationsHeader header;
private final VoipInnovationsBody body;
public VoipInnovationsResponse(final VoipInnovationsHeader header, final VoipInnovationsBody body) {
super();
this.header = header;
this.body = body;
}
public VoipInnovationsHeader header() {
return header;
}
public VoipInnovationsBody body() {
return body;
}
}
| 1,394 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
LATA.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/LATA.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.vi;
import java.util.List;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class LATA {
private final String name;
private final List<RateCenter> centers;
public LATA(final String name, final List<RateCenter> centers) {
super();
this.name = name;
this.centers = centers;
}
public String name() {
return name;
}
public List<RateCenter> centers() {
return centers;
}
}
| 1,415 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
NXX.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/NXX.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.vi;
import java.util.List;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class NXX {
private final String name;
private final List<TN> tns;
public NXX(final String name, final List<TN> tns) {
super();
this.name = name;
this.tns = tns;
}
public String name() {
return name;
}
public List<TN> tns() {
return tns;
}
}
| 1,365 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
VoipInnovationsHeader.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/VoipInnovationsHeader.java | package org.restcomm.connect.provisioning.number.vi;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
@Immutable
public final class VoipInnovationsHeader {
private final String id;
public VoipInnovationsHeader(final String id) {
super();
this.id = id;
}
public String id() {
return id;
}
}
| 360 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
State.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/State.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.vi;
import java.util.List;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class State {
private final String name;
private final List<LATA> latas;
public State(final String name, final List<LATA> latas) {
super();
this.name = name;
this.latas = latas;
}
public String name() {
return name;
}
public List<LATA> latas() {
return latas;
}
}
| 1,387 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
NPA.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/NPA.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.vi;
import java.util.List;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class NPA {
private final String name;
private final List<NXX> nxxs;
public NPA(final String name, final List<NXX> nxxs) {
super();
this.name = name;
this.nxxs = nxxs;
}
public String name() {
return name;
}
public List<NXX> nxxs() {
return nxxs;
}
}
| 1,374 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
VoIPInnovationsNumberProvisioningManager.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/VoIPInnovationsNumberProvisioningManager.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.vi;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import javax.servlet.sip.SipURI;
import org.apache.commons.configuration.Configuration;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.restcomm.connect.provisioning.number.api.ContainerConfiguration;
import org.restcomm.connect.provisioning.number.api.PhoneNumberParameters;
import org.restcomm.connect.provisioning.number.api.PhoneNumberSearchFilters;
import org.restcomm.connect.provisioning.number.api.PhoneNumber;
import org.restcomm.connect.provisioning.number.api.PhoneNumberProvisioningManager;
import org.restcomm.connect.provisioning.number.api.ProvisionProvider;
import org.restcomm.connect.provisioning.number.vi.converter.GetDIDListResponseConverter;
import org.restcomm.connect.provisioning.number.vi.converter.LATAConverter;
import org.restcomm.connect.provisioning.number.vi.converter.NPAConverter;
import org.restcomm.connect.provisioning.number.vi.converter.NXXConverter;
import org.restcomm.connect.provisioning.number.vi.converter.RateCenterConverter;
import org.restcomm.connect.provisioning.number.vi.converter.StateConverter;
import org.restcomm.connect.provisioning.number.vi.converter.TNConverter;
import org.restcomm.connect.provisioning.number.vi.converter.VoipInnovationsBodyConverter;
import org.restcomm.connect.provisioning.number.vi.converter.VoipInnovationsHeaderConverter;
import org.restcomm.connect.provisioning.number.vi.converter.VoipInnovationsResponseConverter;
import org.restcomm.connect.commons.util.StringUtils;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.thoughtworks.xstream.XStream;
/**
* @author jean
*/
public class VoIPInnovationsNumberProvisioningManager implements PhoneNumberProvisioningManager {
private static final Logger logger = Logger.getLogger(VoIPInnovationsNumberProvisioningManager.class);
private XStream xstream;
private String header;
protected Boolean telestaxProxyEnabled;
protected String uri, username, password, endpoint;
protected Configuration activeConfiguration;
protected ContainerConfiguration containerConfiguration;
public VoIPInnovationsNumberProvisioningManager() {
}
/*
* (non-Javadoc)
*
* @see
* PhoneNumberProvisioningManager#init(org.apache.commons.configuration
* .Configuration, boolean)
*/
@Override
public void init(Configuration phoneNumberProvisioningConfiguration, 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");
endpoint = telestaxProxyConfiguration.getString("endpoint");
activeConfiguration = telestaxProxyConfiguration;
} else {
Configuration viConf = phoneNumberProvisioningConfiguration.subset("voip-innovations");
uri = viConf.getString("uri");
username = viConf.getString("login");
password = viConf.getString("password");
endpoint = viConf.getString("endpoint");
activeConfiguration = viConf;
}
this.header = header(username, password);
xstream = new XStream();
xstream.alias("response", VoipInnovationsResponse.class);
xstream.alias("header", VoipInnovationsHeader.class);
xstream.alias("body", VoipInnovationsBody.class);
xstream.alias("lata", LATAConverter.class);
xstream.alias("npa", NPAConverter.class);
xstream.alias("nxx", NXXConverter.class);
xstream.alias("rate_center", RateCenterConverter.class);
xstream.alias("state", StateConverter.class);
xstream.alias("tn", TNConverter.class);
xstream.registerConverter(new VoipInnovationsResponseConverter());
xstream.registerConverter(new VoipInnovationsHeaderConverter());
xstream.registerConverter(new VoipInnovationsBodyConverter());
xstream.registerConverter(new GetDIDListResponseConverter());
xstream.registerConverter(new LATAConverter());
xstream.registerConverter(new NPAConverter());
xstream.registerConverter(new NXXConverter());
xstream.registerConverter(new RateCenterConverter());
xstream.registerConverter(new StateConverter());
xstream.registerConverter(new TNConverter());
}
private String header(final String login, final String password) {
final StringBuilder buffer = new StringBuilder();
buffer.append("<header><sender>");
buffer.append("<login>").append(login).append("</login>");
buffer.append("<password>").append(password).append("</password>");
buffer.append("</sender></header>");
return buffer.toString();
}
private String getFriendlyName(final String number) {
try {
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
final com.google.i18n.phonenumbers.Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(number, "US");
String friendlyName = phoneNumberUtil.format(phoneNumber, PhoneNumberFormat.E164);
return friendlyName;
} catch (final Exception ignored) {
return number;
}
}
private List<PhoneNumber> toAvailablePhoneNumbers(final GetDIDListResponse response, PhoneNumberSearchFilters listFilters) {
Pattern searchPattern = listFilters.getFilterPattern();
final List<PhoneNumber> numbers = new ArrayList<PhoneNumber>();
final List<State> states = response.states();
for (final State state : states) {
if(listFilters.getInRegion() == null || (listFilters.getInRegion() != null && !listFilters.getInRegion().isEmpty() && listFilters.getInRegion().equals(state.name()))) {
for (final LATA lata : state.latas()) {
for (final RateCenter center : lata.centers()) {
for (final NPA npa : center.npas()) {
for (final NXX nxx : npa.nxxs()) {
for (final TN tn : nxx.tns()) {
final String name = getFriendlyName(tn.number());
final String phoneNumber = name;
if(searchPattern == null || (searchPattern != null && searchPattern.matcher(tn.number()).matches())) {
if(listFilters.getFaxEnabled() == null || (listFilters.getFaxEnabled() != null && listFilters.getFaxEnabled() == tn.t38())) {
// XXX Cannot know whether DID is SMS capable. Need to update to VI API 3.0 - hrosa
final PhoneNumber number = new PhoneNumber(name, phoneNumber, Integer.parseInt(lata.name()),
center.name(), null, null, state.name(), null, "US", null, true, null, null, tn.t38(), null);
numbers.add(number);
}
}
}
}
}
}
}
}
}
return numbers;
}
/*
* (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) {
if(logger.isDebugEnabled()) {
logger.debug("searchPattern " + listFilters.getFilterPattern());
}
String areaCode = listFilters.getAreaCode();
Pattern filterPattern = listFilters.getFilterPattern();
String searchPattern = null;
if(filterPattern != null) {
searchPattern = filterPattern.toString();
}
if ((areaCode == null || !areaCode.isEmpty() || areaCode.length() < 3) &&
(searchPattern != null && !searchPattern.toString().isEmpty() && searchPattern.toString().length() >= 5)) {
areaCode = searchPattern.toString().substring(2, 5);
if(logger.isDebugEnabled()) {
logger.debug("areaCode derived from searchPattern " + searchPattern);
}
}
if (areaCode != null && !areaCode.isEmpty() && (areaCode.length() == 3)) {
final StringBuilder buffer = new StringBuilder();
buffer.append("<request id=\""+generateId()+"\">");
buffer.append(header);
buffer.append("<body>");
buffer.append("<requesttype>").append("getDIDs").append("</requesttype>");
buffer.append("<item>");
buffer.append("<npa>").append(areaCode).append("</npa>");
buffer.append("</item>");
buffer.append("</body>");
buffer.append("</request>");
final String body = buffer.toString();
final HttpPost post = new HttpPost(uri);
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("apidata", body));
try {
post.setEntity(new UrlEncodedFormEntity(parameters));
final DefaultHttpClient client = new DefaultHttpClient();
if (telestaxProxyEnabled) {
addTelestaxProxyHeaders(post, ProvisionProvider.REQUEST_TYPE.GETDIDS.name());
}
final HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final String content = StringUtils.toString(response.getEntity().getContent());
final VoipInnovationsResponse result = (VoipInnovationsResponse) xstream.fromXML(content);
final GetDIDListResponse dids = (GetDIDListResponse) result.body().content();
if (dids.code() == 100) {
final List<PhoneNumber> numbers = toAvailablePhoneNumbers(dids, listFilters);
return numbers;
}
} else {
logger.warn("Couldn't reach uri for getting DIDs. Response status was: "+response.getStatusLine().getStatusCode());
}
} catch (final Exception e) {
logger.warn("Couldn't reach uri for getting DIDs " + uri, e);
}
}
return new ArrayList<PhoneNumber>();
}
private String generateId() {
return UUID.randomUUID().toString().replace("-", "");
}
/*
* (non-Javadoc)
* @see PhoneNumberProvisioningManager#buyNumber(java.lang.String, PhoneNumberParameters)
*/
@Override
public boolean buyNumber(PhoneNumber phoneNumberObject, PhoneNumberParameters phoneNumberParameters) {
String phoneNumber = phoneNumberObject.getPhoneNumber();
phoneNumber = phoneNumber.substring(2);
// Provision the number from VoIP Innovations if they own it.
if (isValidDid(phoneNumber)) {
if (phoneNumber != null && !phoneNumber.isEmpty()) {
final StringBuilder buffer = new StringBuilder();
buffer.append("<request id=\""+generateId()+"\">");
buffer.append(header);
buffer.append("<body>");
buffer.append("<requesttype>").append("assignDID").append("</requesttype>");
buffer.append("<item>");
buffer.append("<did>").append(phoneNumber).append("</did>");
buffer.append("<endpointgroup>").append(endpoint).append("</endpointgroup>");
buffer.append("</item>");
buffer.append("</body>");
buffer.append("</request>");
final String body = buffer.toString();
final HttpPost post = new HttpPost(uri);
try {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("apidata", body));
post.setEntity(new UrlEncodedFormEntity(parameters));
final DefaultHttpClient client = new DefaultHttpClient();
if(telestaxProxyEnabled) {
addTelestaxProxyHeaders(post, ProvisionProvider.REQUEST_TYPE.ASSIGNDID.name());
}
final HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final String content = StringUtils.toString(response.getEntity().getContent());
if (content.contains("<statuscode>100</statuscode>")) {
return true;
}
}
} catch (final Exception ignored) {
}
}
}
return false;
}
protected boolean isValidDid(final String did) {
if (did != null && !did.isEmpty()) {
final StringBuilder buffer = new StringBuilder();
buffer.append("<request id=\""+generateId()+"\">");
buffer.append(header);
buffer.append("<body>");
buffer.append("<requesttype>").append("queryDID").append("</requesttype>");
buffer.append("<item>");
buffer.append("<did>").append(did).append("</did>");
buffer.append("</item>");
buffer.append("</body>");
buffer.append("</request>");
final String body = buffer.toString();
final HttpPost post = new HttpPost(uri);
try {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("apidata", body));
post.setEntity(new UrlEncodedFormEntity(parameters));
final DefaultHttpClient client = new DefaultHttpClient();
if(telestaxProxyEnabled) {
addTelestaxProxyHeaders(post, ProvisionProvider.REQUEST_TYPE.QUERYDID.name());
}
final HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final String content = StringUtils.toString(response.getEntity().getContent());
if (content.contains("<statusCode>100</statusCode>")) {
return true;
}
}
} catch (final Exception ignored) {
}
}
return false;
}
/*
* (non-Javadoc)
* @see PhoneNumberProvisioningManager#updateNumber(java.lang.String, PhoneNumberParameters)
*/
@Override
public boolean updateNumber(PhoneNumber phoneNumberObj, PhoneNumberParameters phoneNumberParameters) {
return true;
}
/*
* (non-Javadoc)
* @see PhoneNumberProvisioningManager#cancelNumber(java.lang.String)
*/
@Override
public boolean cancelNumber(PhoneNumber phoneNumberObj) {
String phoneNumber = phoneNumberObj.getPhoneNumber();
String numberToRemoveFromVi = phoneNumber;
if(numberToRemoveFromVi.startsWith("+1")){
numberToRemoveFromVi = numberToRemoveFromVi.replaceFirst("\\+1", "");
}
phoneNumber = numberToRemoveFromVi;
if (!isValidDid(phoneNumber))
return false;
if (phoneNumber != null && !phoneNumber.isEmpty()) {
final StringBuilder buffer = new StringBuilder();
buffer.append("<request id=\""+generateId()+"\">");
buffer.append(header);
buffer.append("<body>");
buffer.append("<requesttype>").append("releaseDID").append("</requesttype>");
buffer.append("<item>");
buffer.append("<did>").append(phoneNumber).append("</did>");
buffer.append("</item>");
buffer.append("</body>");
buffer.append("</request>");
final String body = buffer.toString();
final HttpPost post = new HttpPost(uri);
try {
List<NameValuePair> parameters = new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("apidata", body));
post.setEntity(new UrlEncodedFormEntity(parameters));
final DefaultHttpClient client = new DefaultHttpClient();
if(telestaxProxyEnabled) {
addTelestaxProxyHeaders(post, ProvisionProvider.REQUEST_TYPE.RELEASEDID.name());
}
final HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final String content = StringUtils.toString(response.getEntity().getContent());
if (content.contains("<statuscode>100</statuscode>")) {
return true;
}
}
} catch (final Exception ignored) {
}
}
return false;
}
@Override
public List<String> getAvailableCountries() {
List<String> countries = new ArrayList<String>();
countries.add("US");
return countries;
}
private void addTelestaxProxyHeaders(HttpPost post, String requestType) {
//This will work as a flag for LB that this request will need to be modified and proxied to VI
post.addHeader("TelestaxProxy", "true");
//Adds the Provision provider class name
post.addHeader("Provider", ProvisionProvider.voipinnovationsClass);
//This will tell LB that this request is a getAvailablePhoneNumberByAreaCode request
post.addHeader("RequestType", requestType);
//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) {
post.addHeader("OutboundIntf", uri.getHost()+":"+uri.getPort()+":"+uri.getTransportParam());
}
}
}
| 19,887 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
TN.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/TN.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.vi;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class TN {
private final String tier;
private final boolean t38;
private final boolean cnam;
private final String number;
public TN(final String tier, final boolean t38, final boolean cnam, final String number) {
super();
this.tier = tier;
this.t38 = t38;
this.cnam = cnam;
this.number = number;
}
public String tier() {
return tier;
}
public boolean t38() {
return t38;
}
public boolean cnam() {
return cnam;
}
public String number() {
return number;
}
}
| 1,613 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RateCenter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/RateCenter.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.vi;
import java.util.List;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class RateCenter {
private final String name;
private final List<NPA> npas;
public RateCenter(final String name, final List<NPA> npas) {
super();
this.name = name;
this.npas = npas;
}
public String name() {
return name;
}
public List<NPA> npas() {
return npas;
}
}
| 1,388 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
VoipInnovationsResponseConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/VoipInnovationsResponseConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import org.restcomm.connect.provisioning.number.vi.VoipInnovationsBody;
import org.restcomm.connect.provisioning.number.vi.VoipInnovationsHeader;
import org.restcomm.connect.provisioning.number.vi.VoipInnovationsResponse;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class VoipInnovationsResponseConverter extends AbstractConverter {
public VoipInnovationsResponseConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return VoipInnovationsResponseConverter.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
VoipInnovationsHeader header = null;
VoipInnovationsBody body = null;
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("header".equals(child)) {
header = (VoipInnovationsHeader) context.convertAnother(null, VoipInnovationsHeader.class);
} else if ("body".equals(child)) {
body = (VoipInnovationsBody) context.convertAnother(null, VoipInnovationsBody.class);
}
reader.moveUp();
}
return new VoipInnovationsResponse(header, body);
}
}
| 1,493 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
VoipInnovationsBodyConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/VoipInnovationsBodyConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import org.restcomm.connect.provisioning.number.vi.GetDIDListResponse;
import org.restcomm.connect.provisioning.number.vi.VoipInnovationsBody;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class VoipInnovationsBodyConverter extends AbstractConverter {
public VoipInnovationsBodyConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return VoipInnovationsBody.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
Object content = null;
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("search".equals(child)) {
content = (GetDIDListResponse) context.convertAnother(null, GetDIDListResponse.class);
}
reader.moveUp();
}
return new VoipInnovationsBody(content);
}
}
| 1,175 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
StateConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/StateConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import java.util.ArrayList;
import java.util.List;
import org.restcomm.connect.provisioning.number.vi.LATA;
import org.restcomm.connect.provisioning.number.vi.State;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class StateConverter extends AbstractConverter {
public StateConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return State.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
String name = null;
final List<LATA> latas = new ArrayList<LATA>();
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("name".equals(child)) {
name = reader.getValue();
} else if ("lata".equals(child)) {
final LATA lata = (LATA) context.convertAnother(null, LATA.class);
latas.add(lata);
}
reader.moveUp();
}
return new State(name, latas);
}
}
| 1,300 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
TNConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/TNConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import org.restcomm.connect.provisioning.number.vi.TN;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class TNConverter extends AbstractConverter {
public TNConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return TN.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
final String tier = reader.getAttribute("tier");
boolean t38 = false;
String value = reader.getAttribute("t38");
if ("1".equals(value)) {
t38 = true;
}
boolean cnam = false;
value = reader.getAttribute("cnamStorage");
if ("1".equals(value)) {
cnam = true;
}
String number = reader.getValue();
return new TN(tier, t38, cnam, number);
}
}
| 1,074 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
NPAConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/NPAConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import java.util.ArrayList;
import java.util.List;
import org.restcomm.connect.provisioning.number.vi.NPA;
import org.restcomm.connect.provisioning.number.vi.NXX;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class NPAConverter extends AbstractConverter {
public NPAConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return NPA.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
String name = null;
final List<NXX> nxxs = new ArrayList<NXX>();
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("name".equals(child)) {
name = reader.getValue();
} else if ("nxx".equals(child)) {
final NXX nxx = (NXX) context.convertAnother(null, NXX.class);
nxxs.add(nxx);
}
reader.moveUp();
}
return new NPA(name, nxxs);
}
}
| 1,278 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
LATAConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/LATAConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import java.util.ArrayList;
import java.util.List;
import org.restcomm.connect.provisioning.number.vi.LATA;
import org.restcomm.connect.provisioning.number.vi.RateCenter;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class LATAConverter extends AbstractConverter {
public LATAConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return LATA.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
String name = null;
final List<RateCenter> centers = new ArrayList<RateCenter>();
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("name".equals(child)) {
name = reader.getValue();
} else if ("rate_center".equals(child)) {
final RateCenter center = (RateCenter) context.convertAnother(null, RateCenter.class);
centers.add(center);
}
reader.moveUp();
}
return new LATA(name, centers);
}
}
| 1,348 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
NXXConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/NXXConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import java.util.ArrayList;
import java.util.List;
import org.restcomm.connect.provisioning.number.vi.NXX;
import org.restcomm.connect.provisioning.number.vi.TN;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class NXXConverter extends AbstractConverter {
public NXXConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return NXX.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
String name = null;
final List<TN> tns = new ArrayList<TN>();
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("name".equals(child)) {
name = reader.getValue();
} else if ("tn".equals(child)) {
final TN tn = (TN) context.convertAnother(null, TN.class);
tns.add(tn);
}
reader.moveUp();
}
return new NXX(name, tns);
}
}
| 1,266 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RateCenterConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/RateCenterConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import java.util.ArrayList;
import java.util.List;
import org.restcomm.connect.provisioning.number.vi.NPA;
import org.restcomm.connect.provisioning.number.vi.RateCenter;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class RateCenterConverter extends AbstractConverter {
public RateCenterConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return RateCenter.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
String name = null;
final List<NPA> npas = new ArrayList<NPA>();
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("name".equals(child)) {
name = reader.getValue();
} else if ("npa".equals(child)) {
final NPA npa = (NPA) context.convertAnother(null, NPA.class);
npas.add(npa);
}
reader.moveUp();
}
return new RateCenter(name, npas);
}
}
| 1,313 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
AbstractConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/AbstractConverter.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.vi.converter;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
/**
* @author [email protected] (Thomas Quintana)
*/
public abstract class AbstractConverter implements Converter {
public AbstractConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public abstract boolean canConvert(final Class klass);
@Override
public void marshal(final Object object, HierarchicalStreamWriter writer, MarshallingContext context) {
// We will not be marshalling these objects.
}
@Override
public abstract Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context);
protected int getInteger(final String number) {
if (number != null && !number.isEmpty()) {
try {
return Integer.parseInt(number);
} catch (final Exception exception) {
return -1;
}
}
return -1;
}
}
| 2,067 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
VoipInnovationsHeaderConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/VoipInnovationsHeaderConverter.java | package org.restcomm.connect.provisioning.number.vi.converter;
import org.restcomm.connect.provisioning.number.vi.VoipInnovationsHeader;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public final class VoipInnovationsHeaderConverter extends AbstractConverter {
public VoipInnovationsHeaderConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(final Class klass) {
return VoipInnovationsHeader.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
String id = null;
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("sessionid".equals(child)) {
id = reader.getValue();
}
reader.moveUp();
}
return new VoipInnovationsHeader(id);
}
}
| 1,044 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
GetDIDListResponseConverter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.vi/src/main/java/org/restcomm/connect/provisioning/number/vi/converter/GetDIDListResponseConverter.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.vi.converter;
import java.util.ArrayList;
import java.util.List;
import org.restcomm.connect.provisioning.number.vi.GetDIDListResponse;
import org.restcomm.connect.provisioning.number.vi.State;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
/**
* @author [email protected]
* @author [email protected] (Thomas Quintana)
*/
public final class GetDIDListResponseConverter extends AbstractConverter {
public GetDIDListResponseConverter() {
super();
}
@SuppressWarnings("rawtypes")
@Override
public boolean canConvert(Class klass) {
return GetDIDListResponse.class.equals(klass);
}
@Override
public Object unmarshal(final HierarchicalStreamReader reader, final UnmarshallingContext context) {
String name = null;
String status = null;
int code = -1;
final List<State> states = new ArrayList<State>();
while (reader.hasMoreChildren()) {
reader.moveDown();
final String child = reader.getNodeName();
if ("name".equals(child)) {
name = reader.getValue();
} else if ("status".equals(child)) {
status = reader.getValue();
} else if ("statuscode".equals(child)) {
final String value = reader.getValue();
code = getInteger(value);
} else if ("state".equals(child)) {
final State lata = (State) context.convertAnother(null, State.class);
states.add(lata);
}
reader.moveUp();
}
return new GetDIDListResponse(name, status, code, states);
}
}
| 2,592 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
EmailServiceTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.email/src/test/java/org/restcomm/connect/email/EmailServiceTest.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.email;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActorFactory;
import akka.testkit.JavaTestKit;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.XMLConfiguration;
import org.junit.After;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.restcomm.connect.email.api.EmailRequest;
import org.restcomm.connect.email.api.EmailResponse;
import org.restcomm.connect.email.api.Mail;
import scala.concurrent.duration.FiniteDuration;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetupTest;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* @author [email protected] (Lefteris Banos)
*/
public final class EmailServiceTest {
private ActorSystem system;
private ActorRef emailService;
private GreenMail mailServer;
public EmailServiceTest() {
super();
}
@Before
public void before() throws Exception {
mailServer = new GreenMail(ServerSetupTest.SMTP);
mailServer.start();
mailServer.setUser("hascode@localhost", "hascode", "abcdef123");
system = ActorSystem.create();
final URL input = getClass().getResource("/emailServiceTest.xml");
final XMLConfiguration configuration = new XMLConfiguration(input);
emailService = emailService(configuration);
}
@After
public void after() throws Exception {
system.shutdown();
mailServer.stop();
}
private ActorRef emailService(final Configuration configuration) {
return system.actorOf(new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public Actor create() throws Exception {
return new EmailService(configuration);
}
}));
}
@Test
public void testSendEmail() {
new JavaTestKit(system) {
{
final ActorRef observer = getRef();
// Send the email.
final Mail emailMsg = new Mail("hascode@localhost", "[email protected]","Testing Email Service" ,"This is the subject of the email service testing", "[email protected], [email protected], [email protected]", "[email protected], [email protected]");
emailService.tell(new EmailRequest(emailMsg), observer);
final EmailResponse response = expectMsgClass(FiniteDuration.create(60, TimeUnit.SECONDS), EmailResponse.class);
assertTrue(response.succeeded());
// fetch messages from server
MimeMessage[] messages = mailServer.getReceivedMessages();
assertNotNull(messages);
assertEquals(6, messages.length);
MimeMessage m = messages[0];
try {
assertEquals(emailMsg.subject(), m.getSubject());
assertTrue(String.valueOf(m.getContent()).contains(emailMsg.body()));
assertEquals(emailMsg.from(), m.getFrom()[0].toString());
assertEquals(emailMsg.contentType(), "text/plain");
} catch(Exception e){
assertTrue(false);
}
}
};
}
@Test
public void testSendHTMLEmail() throws IOException, MessagingException {
new JavaTestKit(system) {
{
final ActorRef observer = getRef();
// Send the email.
final Mail emailMsg = new Mail("hascode@localhost", "[email protected]","Testing Email Service" ,"This is the subject of the email service testing", "[email protected], [email protected], [email protected]", "[email protected], [email protected]", null, null, "text/html");
emailService.tell(new EmailRequest(emailMsg), observer);
final EmailResponse response = expectMsgClass(FiniteDuration.create(60, TimeUnit.SECONDS), EmailResponse.class);
assertTrue(response.succeeded());
// fetch messages from server
MimeMessage[] messages = mailServer.getReceivedMessages();
assertNotNull(messages);
assertEquals(6, messages.length);
MimeMessage m = messages[0];
assertEquals(emailMsg.subject(), m.getSubject());
assertTrue(String.valueOf(m.getContent()).contains(emailMsg.body()));
assertEquals(emailMsg.from(), m.getFrom()[0].toString());
assertEquals(emailMsg.contentType(), "text/html");
}
};
}
}
| 5,698 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
EmailService.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.email/src/main/java/org/restcomm/connect/email/EmailService.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.email;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.apache.commons.configuration.Configuration;
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 org.restcomm.connect.email.api.EmailRequest;
import org.restcomm.connect.email.api.EmailResponse;
import org.restcomm.connect.email.api.Mail;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* @author [email protected] (Lefteris Banos)
*/
public class EmailService extends RestcommUntypedActor {
final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
private final List<ActorRef> observers;
private Configuration configuration;
private Session session;
private String host;
private String port;
private String user;
private String password;
private Transport transport;
private final Properties properties = System.getProperties();
private boolean isSslEnabled = false;
public EmailService(final Configuration config) {
this.observers = new ArrayList<ActorRef>();
configuration = config;
this.host = configuration.getString("host");
this.port = configuration.getString("port");
this.user = configuration.getString("user");
this.password = configuration.getString("password");
if ((user != null && !user.isEmpty()) || (password != null && !password.isEmpty()) ||
(port != null && !port.isEmpty()) || (host != null && !host.isEmpty()) ){
//allow smtp over ssl if port is set to 465
if ("465".equals(port)){
this.isSslEnabled = true;
useSSLSmtp();
}else{
//TLS uses port 587
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.user", user);
properties.setProperty("mail.smtp.password", password);
properties.setProperty("mail.smtp.port", port);
}
properties.setProperty("mail.smtp.starttls.enable", "true");
properties.setProperty("mail.transport.protocol", "smtps");
// properties.setProperty("mail.smtp.ssl.enable", "true");
properties.setProperty("mail.smtp.auth", "true");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
}
}
private void useSSLSmtp() {
properties.put("mail.transport.protocol", "smtps");
properties.put("mail.smtps.ssl.enable", "true");
properties.put("mail.smtps.host", host);
properties.put("mail.smtps.user", user);
properties.put("mail.smtps.password", password);
properties.put("mail.smtps.port", port);
properties.put("mail.smtps.auth", "true");
session = Session.getDefaultInstance(properties);
try {
this.transport = session.getTransport();
} catch (NoSuchProviderException ex) {
logger.error(EmailService.class.getName() , ex);
}
}
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);
}
}
private void stopObserving(final Object message) {
final StopObserving request = (StopObserving) message;
final ActorRef observer = request.observer();
if (observer != null) {
observers.remove(observer);
}
}
@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)) {
observe(message);
} else if (StopObserving.class.equals(klass)) {
stopObserving(message);
}else if (EmailRequest.class.equals(klass)) {
EmailRequest request = (EmailRequest)message;
if(isSslEnabled){
sender.tell(sendEmailSsL(request.getObject()), self);
}else{
sender.tell(send(request.getObject()), self);
}
}
}
EmailResponse sendEmailSsL (final Mail mail) {
try {
InternetAddress from;
if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
from = new InternetAddress(mail.from());
} else {
from = new InternetAddress(user);
}
final InternetAddress to = new InternetAddress(mail.to());
final MimeMessage email = new MimeMessage(session);
email.setFrom(from);
email.addRecipient(Message.RecipientType.TO, to);
email.setSubject(mail.subject());
email.setContent(mail.body(), mail.contentType());
email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
email.addRecipients(Message.RecipientType.BCC,InternetAddress.parse(mail.bcc(),false));
//Transport.send(email);
transport.connect (host, Integer.parseInt(port), user, password);
transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO));
return new EmailResponse(mail);
} catch (final MessagingException exception) {
logger.error(exception.getMessage(), exception);
return new EmailResponse(exception,exception.getMessage());
}
}
EmailResponse send(final Mail mail) {
try {
InternetAddress from;
if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
from = new InternetAddress(mail.from());
} else {
from = new InternetAddress(user);
}
final InternetAddress to = new InternetAddress(mail.to());
final MimeMessage email = new MimeMessage(session);
email.setFrom(from);
email.addRecipient(Message.RecipientType.TO, to);
email.setSubject(mail.subject());
email.setContent(mail.body(), mail.contentType());
email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
email.addRecipients(Message.RecipientType.BCC,InternetAddress.parse(mail.bcc(),false));
Transport.send(email);
return new EmailResponse(mail);
} catch (final MessagingException exception) {
logger.error(exception.getMessage(), exception);
return new EmailResponse(exception,exception.getMessage());
}
}
}
| 8,300 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
NexmoPhoneNumberProvisioningManager.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.nexmo/src/main/java/org/restcomm/connect/provisioning/number/nexmo/NexmoPhoneNumberProvisioningManager.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.nexmo;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.configuration.Configuration;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.commons.util.StringUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
/**
* @author [email protected]
*/
public class NexmoPhoneNumberProvisioningManager implements PhoneNumberProvisioningManager {
private static final Logger logger = Logger.getLogger(NexmoPhoneNumberProvisioningManager.class);
protected Boolean telestaxProxyEnabled;
protected String uri, apiKey, apiSecret, smppSystemType;
protected String searchURI, buyURI, updateURI, cancelURI;
protected Configuration activeConfiguration;
protected ContainerConfiguration containerConfiguration;
public NexmoPhoneNumberProvisioningManager() {}
/*
* (non-Javadoc)
*
* @see
* PhoneNumberProvisioningManager#init(org.apache.commons.configuration
* .Configuration, boolean)
*/
@Override
public void init(Configuration phoneNumberProvisioningConfiguration, Configuration telestaxProxyConfiguration, ContainerConfiguration containerConfiguration) {
this.containerConfiguration = containerConfiguration;
telestaxProxyEnabled = telestaxProxyConfiguration.getBoolean("enabled", false);
if (telestaxProxyEnabled) {
uri = telestaxProxyConfiguration.getString("uri");
apiKey = telestaxProxyConfiguration.getString("api-key");
apiSecret = telestaxProxyConfiguration.getString("api-secret");
smppSystemType = telestaxProxyConfiguration.getString("smpp-system-type", "inbound");
activeConfiguration = telestaxProxyConfiguration;
} else {
Configuration nexmoConfiguration = phoneNumberProvisioningConfiguration.subset("nexmo");
uri = nexmoConfiguration.getString("uri");
apiKey = nexmoConfiguration.getString("api-key");
apiSecret = nexmoConfiguration.getString("api-secret");
smppSystemType = nexmoConfiguration.getString("smpp-system-type", "inbound");
activeConfiguration = nexmoConfiguration;
}
searchURI = uri + "/number/search/" + apiKey + "/" + apiSecret + "/";
buyURI = uri + "/number/buy/" + apiKey + "/" + apiSecret + "/";
updateURI = uri + "/number/update/" + apiKey + "/" + apiSecret + "/";
cancelURI = uri + "/number/cancel/" + apiKey + "/" + apiSecret + "/";
}
private String getFriendlyName(final String number, String countryCode) {
try {
final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
final com.google.i18n.phonenumbers.Phonenumber.PhoneNumber phoneNumber = phoneNumberUtil.parse(number, countryCode);
String friendlyName = phoneNumberUtil.format(phoneNumber, PhoneNumberFormat.E164);
return friendlyName;
} catch (final Exception ignored) {
return number;
}
}
private List<PhoneNumber> toAvailablePhoneNumbers(final JsonArray phoneNumbers, PhoneNumberSearchFilters listFilters) {
Pattern searchPattern = listFilters.getFilterPattern();
final List<PhoneNumber> numbers = new ArrayList<PhoneNumber>();
for (int i = 0; i < phoneNumbers.size(); i++) {
JsonObject number = phoneNumbers.get(i).getAsJsonObject();
String countryCode = number.get("country").getAsString();
String features = null;
if(number.get("features") != null) {
features = number.get("features").toString();
}
boolean isVoiceCapable = false;
boolean isSmsCapable = false;
if(features.contains("SMS")) {
isSmsCapable = true;
}
if(features.contains("VOICE")) {
isVoiceCapable = true;
}
final PhoneNumber phoneNumber = new PhoneNumber(
getFriendlyName(number.get("msisdn").getAsString(), countryCode),
number.get("msisdn").getAsString(),
null, null, null, null, null, null,
countryCode, number.get("cost").getAsString(), isVoiceCapable, isSmsCapable, null, null, null);
numbers.add(phoneNumber);
}
return numbers;
}
/*
* (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) {
if(logger.isDebugEnabled()) {
logger.debug("searchPattern " + listFilters.getFilterPattern());
}
Pattern filterPattern = listFilters.getFilterPattern();
String filterPatternString = null;
if(filterPattern != null) {
filterPatternString = filterPattern.toString().replaceAll("[^\\d]", "");
}
if(logger.isDebugEnabled()) {
logger.debug("searchPattern simplified for nexmo " + filterPatternString);
}
String queryUri = searchURI + country;
boolean queryParamAdded = false;
if(("US".equalsIgnoreCase(country) || "CA".equalsIgnoreCase(country)) && listFilters.getAreaCode() != null) {
// https://github.com/Mobicents/RestComm/issues/551 fixing the search pattern for US when Area Code is selected
// https://github.com/Mobicents/RestComm/issues/602 fixing the search pattern for CA when Area Code is selected
queryUri = queryUri + "?pattern=1" + listFilters.getAreaCode() + "&search_pattern=0";
queryParamAdded = true;
} else if(filterPatternString != null) {
queryUri = queryUri + "?pattern=" + filterPatternString + "&search_pattern=1";
queryParamAdded = true;
}
if(listFilters.getSmsEnabled() != null || listFilters.getVoiceEnabled() != null) {
if(!queryParamAdded) {
queryUri = queryUri + "?";
queryParamAdded = true;
} else {
queryUri = queryUri + "&";
}
if(listFilters.getSmsEnabled() != null && listFilters.getVoiceEnabled() != null) {
queryUri = queryUri + "features=SMS,VOICE";
} else if(listFilters.getSmsEnabled() != null) {
queryUri = queryUri + "features=SMS";
} else {
queryUri = queryUri + "features=VOICE";
}
}
if(listFilters.getRangeIndex() != -1) {
if(!queryParamAdded) {
queryUri = queryUri + "?";
queryParamAdded = true;
} else {
queryUri = queryUri + "&";
}
queryUri = queryUri + "index=" + listFilters.getRangeIndex();
}
if(listFilters.getRangeSize() != -1) {
if(!queryParamAdded) {
queryUri = queryUri + "?";
queryParamAdded = true;
} else {
queryUri = queryUri + "&";
}
queryUri = queryUri + "size=" + listFilters.getRangeSize();
}
final HttpGet get = new HttpGet(queryUri);
try {
final DefaultHttpClient client = new DefaultHttpClient();
// if (telestaxProxyEnabled) {
// // This will work as a flag for LB that this request will need to be modified and proxied to VI
// get.addHeader("TelestaxProxy", String.valueOf(telestaxProxyEnabled));
// // This will tell LB that this request is a getAvailablePhoneNumberByAreaCode request
// get.addHeader("RequestType", "GetAvailablePhoneNumbersByAreaCode");
// //This will let LB match the DID to a node based on the node host+port
// for (SipURI uri: containerConfiguration.getOutboundInterfaces()) {
// get.addHeader("OutboundIntf", uri.getHost()+":"+uri.getPort()+":"+uri.getTransportParam());
// }
// }
if(logger.isDebugEnabled()) {
logger.debug("Nexmo query " + queryUri);
}
final HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final String content = StringUtils.toString(response.getEntity().getContent());
JsonParser parser = new JsonParser();
JsonObject jsonResponse = parser.parse(content).getAsJsonObject();
if(logger.isDebugEnabled()) {
logger.debug("Nexmo response " + jsonResponse.toString());
}
JsonPrimitive countPrimitive = jsonResponse.getAsJsonPrimitive("count");
if(countPrimitive == null) {
if(logger.isDebugEnabled()) {
logger.debug("No numbers found");
}
return new ArrayList<PhoneNumber>();
}
long count = countPrimitive.getAsLong();
if(logger.isDebugEnabled()) {
logger.debug("Number of numbers found : "+count);
}
JsonArray nexmoNumbers = jsonResponse.getAsJsonArray("numbers");
final List<PhoneNumber> numbers = toAvailablePhoneNumbers(nexmoNumbers, listFilters);
return numbers;
} else {
logger.warn("Couldn't reach uri for getting Phone Numbers. Response status was: "+response.getStatusLine().getStatusCode());
}
} catch (final Exception e) {
logger.warn("Couldn't reach uri for getting Phone Numbers" + uri, e);
}
return new ArrayList<PhoneNumber>();
}
@Override
public boolean buyNumber(PhoneNumber phoneNumberObject, PhoneNumberParameters phoneNumberParameters) {
String phoneNumber = phoneNumberObject.getPhoneNumber();
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
String country = null;
try {
// phone must begin with '+'
com.google.i18n.phonenumbers.Phonenumber.PhoneNumber numberProto = null;
if(phoneNumber.startsWith("+")) {
numberProto = phoneUtil.parse(phoneNumber, "US");
} else {
numberProto = phoneUtil.parse("+" + phoneNumber, "US");
}
int countryCode = numberProto.getCountryCode();
country = phoneUtil.getRegionCodeForNumber(numberProto);
} catch (NumberParseException e) {
if(logger.isDebugEnabled())
logger.debug("problem parsing phone number " + phoneNumber, e);
return false;
}
String queryUri = null;
if(phoneNumber.startsWith("+")) {
queryUri = buyURI + country + "/" + phoneNumber.substring(1, phoneNumber.length());
} else {
queryUri = buyURI + country + "/" + phoneNumber;
}
final HttpPost post = new HttpPost(queryUri);
try {
final DefaultHttpClient client = new DefaultHttpClient();
// if (telestaxProxyEnabled) {
// // This will work as a flag for LB that this request will need to be modified and proxied to VI
// get.addHeader("TelestaxProxy", String.valueOf(telestaxProxyEnabled));
// // This will tell LB that this request is a getAvailablePhoneNumberByAreaCode request
// get.addHeader("RequestType", "GetAvailablePhoneNumbersByAreaCode");
// //This will let LB match the DID to a node based on the node host+port
// for (SipURI uri: containerConfiguration.getOutboundInterfaces()) {
// get.addHeader("OutboundIntf", uri.getHost()+":"+uri.getPort()+":"+uri.getTransportParam());
// }
// }
final HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
updateNumber(phoneNumberObject, phoneNumberParameters);
// we always return true as the phone number was bought
return true;
} else {
if(logger.isDebugEnabled())
logger.debug("Couldn't buy Phone Number " + phoneNumber + ". Response status was: "+ response.getStatusLine().getStatusCode());
}
} catch (final Exception e) {
logger.warn("Couldn't reach uri for buying Phone Numbers" + uri, e);
}
return false;
}
@Override
public boolean updateNumber(PhoneNumber phoneNumberObj, PhoneNumberParameters phoneNumberParameters) {
String phoneNumber = phoneNumberObj.getPhoneNumber();
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
String country = null;
try {
// phone must begin with '+'
com.google.i18n.phonenumbers.Phonenumber.PhoneNumber numberProto = null;
if(phoneNumber.startsWith("+")) {
numberProto = phoneUtil.parse(phoneNumber, "US");
} else {
numberProto = phoneUtil.parse("+" + phoneNumber, "US");
}
int countryCode = numberProto.getCountryCode();
country = phoneUtil.getRegionCodeForCountryCode(countryCode);
} catch (NumberParseException e) {
if(logger.isDebugEnabled())
logger.debug("problem parsing phone number " + phoneNumber, e);
return false;
}
String updateUri = null;
if(phoneNumber.startsWith("+")) {
updateUri = updateURI + country + "/" + phoneNumber.substring(1, phoneNumber.length());
} else {
updateUri = updateURI + country + "/" + phoneNumber;
}
try {
if((phoneNumberParameters.getVoiceUrl() != null && !phoneNumberParameters.getVoiceUrl().isEmpty()) ||
(phoneNumberParameters.getSmsUrl() != null && phoneNumberParameters.getSmsUrl().isEmpty())) {
updateUri = updateUri + "?";
if(phoneNumberParameters.getSmsUrl() != null && !phoneNumberParameters.getSmsUrl().isEmpty()
&& phoneNumberParameters.getVoiceUrl() != null && !phoneNumberParameters.getVoiceUrl().isEmpty()) {
updateUri = updateUri + "voiceCallbackValue=" + URLEncoder.encode(phoneNumber+"@"+phoneNumberParameters.getVoiceUrl(), "UTF-8") + "&voiceCallbackType=sip" +
"&moHttpUrl=" + URLEncoder.encode(phoneNumber+"@"+phoneNumberParameters.getSmsUrl(), "UTF-8") + "&moSmppSysType=" + smppSystemType;
} else if(phoneNumberParameters.getVoiceUrl() != null && !phoneNumberParameters.getVoiceUrl().isEmpty()) {
updateUri = updateUri + "voiceCallbackValue=" + URLEncoder.encode(phoneNumber+"@"+phoneNumberParameters.getVoiceUrl(), "UTF-8") + "&voiceCallbackType=sip" + "&moSmppSysType=" + smppSystemType;
} else {
updateUri = updateUri + "moHttpUrl=" + URLEncoder.encode(phoneNumber+"@"+phoneNumberParameters.getSmsUrl(), "UTF-8") + "&moSmppSysType=" + smppSystemType ;
}
}
final HttpPost updatePost = new HttpPost(updateUri);
final DefaultHttpClient client = new DefaultHttpClient();
final HttpResponse updateResponse = client.execute(updatePost);
if (updateResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return true;
} else {
if(logger.isDebugEnabled())
logger.debug("Couldn't update Phone Number " + phoneNumber + ". Response status was: "+ updateResponse.getStatusLine().getStatusCode());
return false;
}
} catch (final Exception e) {
logger.warn("Couldn't reach uri for update Phone Numbers" + uri, e);
}
return false;
}
@Override
public boolean cancelNumber(PhoneNumber phoneNumberObj) {
String phoneNumber = phoneNumberObj.getPhoneNumber();
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
String country = null;
try {
// phone must begin with '+'
com.google.i18n.phonenumbers.Phonenumber.PhoneNumber numberProto = null;
if(phoneNumber.startsWith("+")) {
numberProto = phoneUtil.parse(phoneNumber, "US");
} else {
numberProto = phoneUtil.parse("+" + phoneNumber, "US");
}
int countryCode = numberProto.getCountryCode();
country = phoneUtil.getRegionCodeForCountryCode(countryCode);
} catch (NumberParseException e) {
if(logger.isDebugEnabled())
logger.debug("problem parsing phone number " + phoneNumber, e);
return false;
}
String queryUri = null;
if(phoneNumber.startsWith("+")) {
queryUri = cancelURI + country + "/" + phoneNumber.substring(1, phoneNumber.length());
} else {
queryUri = cancelURI + country + "/" + phoneNumber;
}
final HttpPost post = new HttpPost(queryUri);
try {
final DefaultHttpClient client = new DefaultHttpClient();
// if (telestaxProxyEnabled) {
// // This will work as a flag for LB that this request will need to be modified and proxied to VI
// get.addHeader("TelestaxProxy", String.valueOf(telestaxProxyEnabled));
// // This will tell LB that this request is a getAvailablePhoneNumberByAreaCode request
// get.addHeader("RequestType", "GetAvailablePhoneNumbersByAreaCode");
// //This will let LB match the DID to a node based on the node host+port
// for (SipURI uri: containerConfiguration.getOutboundInterfaces()) {
// get.addHeader("OutboundIntf", uri.getHost()+":"+uri.getPort()+":"+uri.getTransportParam());
// }
// }
final HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return true;
} else {
if(logger.isDebugEnabled())
logger.debug("Couldn't cancel Phone Number " + phoneNumber + ". Response status was: "+response.getStatusLine().getStatusCode());
}
} catch (final Exception e) {
logger.warn("Couldn't reach uri for cancelling Phone Numbers" + uri, e);
}
return false;
}
@Override
public List<String> getAvailableCountries() {
List<String> countries = new ArrayList<String>();
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
countries.add(countryCode);
}
return countries;
}
}
| 21,063 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DestroySmsSession.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/DestroySmsSession.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.sms.api;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import akka.actor.ActorRef;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class DestroySmsSession {
private final ActorRef session;
public DestroySmsSession(final ActorRef session) {
super();
this.session = session;
}
public ActorRef session() {
return session;
}
}
| 1,276 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsSessionRequest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/SmsSessionRequest.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.sms.api;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.sip.SipServletRequest;
import org.restcomm.smpp.parameter.TlvSet;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class SmsSessionRequest {
private final String from;
private final String to;
private final String body;
private final Encoding encoding;
private final SipServletRequest origRequest;
private final ConcurrentHashMap<String, String> customHeaders;
public enum Encoding {
UCS_2("UCS-2"),
UTF_8("UTF-8"),
GSM("GSM");
private final String name;
Encoding(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
//FIXME: all signatures should be changed, encoding, sipReq, tlvSet are optional and should come after headers
//(from, to, body, headers, encoding, sipReq, tlvSet)
//(from, to, body, headers, encoding, sipReq)
//(from, to, body, headers, encoding, tlvSet)
//(from, to, body, headers, sipReq, tlvSet)
//(from, to, body, headers, encoding)
//(from, to, body, headers, sipReq)
//(from, to, body, headers, tlvSet)
//(from, to, body)
public SmsSessionRequest(final String from, final String to, final String body, final Encoding encoding, final SipServletRequest origRequest, TlvSet tlvSet, final ConcurrentHashMap<String, String> customHeaders) {
super();
this.from = from;
this.to = to;
this.origRequest = origRequest;
this.body = body;
this.customHeaders = customHeaders;
this.encoding = encoding;
}
//TODO need to check which is using the SmsSessionRequest and modify accordingly to include or not the custom headers
public SmsSessionRequest(final String from, final String to, final String body, final Encoding encoding, final SipServletRequest origRequest, final ConcurrentHashMap<String, String> customHeaders) {
this(from, to, body, encoding, origRequest, null, customHeaders);
}
public SmsSessionRequest(final String from, final String to, final String body, final Encoding encoding, final TlvSet tlvSet, final ConcurrentHashMap<String, String> customHeaders) {
this(from, to, body, encoding, null, tlvSet, customHeaders);
}
public SmsSessionRequest(final String from, final String to, final String body, final SipServletRequest origRequest, final TlvSet tlvSet, final ConcurrentHashMap<String, String> customHeaders) {
this(from, to, body, Encoding.GSM, origRequest, customHeaders);
}
public SmsSessionRequest(final String from, final String to, final String body, final SipServletRequest origRequest, final ConcurrentHashMap<String, String> customHeaders) {
this(from, to, body, Encoding.GSM, origRequest, null, customHeaders);
}
public SmsSessionRequest(final String from, final String to, final String body, final Encoding encoding, final ConcurrentHashMap<String, String> customHeaders) {
this(from, to, body, encoding, null, null, customHeaders);
}
public SmsSessionRequest(final String from, final String to, final String body, final TlvSet tlvSet, final ConcurrentHashMap<String, String> customHeaders) {
this(from, to, body, Encoding.GSM, null, null, customHeaders);
}
public SmsSessionRequest(final String from, final String to, final String body, final ConcurrentHashMap<String, String> customHeaders) {
this(from, to, body, Encoding.GSM, null, null, customHeaders);
}
public SmsSessionRequest(final String from, final String to, final String body) {
this(from, to, body, Encoding.GSM, null, null, null);
}
public String from() {
return from;
}
public String to() {
return to;
}
public String body() {
return body;
}
public Encoding encoding() {
return encoding;
}
public SipServletRequest getOrigRequest() {
return origRequest;
}
public ConcurrentHashMap<String, String> headers() {
return customHeaders;
}
}
| 5,066 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsSessionInfo.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/SmsSessionInfo.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.sms.api;
import java.util.Map;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class SmsSessionInfo {
private final String from;
private final String to;
private final Map<String, Object> attributes;
public SmsSessionInfo(final String from, final String to, final Map<String, Object> attributes) {
super();
this.from = from;
this.to = to;
this.attributes = attributes;
}
public String from() {
return from;
}
public String to() {
return to;
}
public Map<String, Object> attributes() {
return attributes;
}
}
| 1,565 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsSessionAttribute.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/SmsSessionAttribute.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.sms.api;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class SmsSessionAttribute {
private final String name;
private final Object value;
public SmsSessionAttribute(final String name, final Object value) {
super();
this.name = name;
this.value = value;
}
public String name() {
return name;
}
public Object value() {
return value;
}
}
| 1,364 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsServiceResponse.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/SmsServiceResponse.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.sms.api;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.commons.patterns.StandardResponse;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class SmsServiceResponse<T> extends StandardResponse<T> {
public SmsServiceResponse(final T object) {
super(object);
}
public SmsServiceResponse(final Throwable cause, final String message) {
super(cause, message);
}
public SmsServiceResponse(final Throwable cause) {
super(cause);
}
}
| 1,408 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CreateSmsSession.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/CreateSmsSession.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.sms.api;
import org.apache.commons.configuration.Configuration;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.extension.api.IExtensionCreateSmsSessionRequest;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class CreateSmsSession implements IExtensionCreateSmsSessionRequest {
private final String from;
private final String to;
private final String accountSid;
private final boolean isFromApi;
private Configuration configuration;
private boolean allowed = true;
//This will be used to create SmsSession from
// 1. REST API SmsMessageEndpoint - Send SMS from REST API
// 2. BaseVoiceInterpreter.CreatingSmsSession - Send SMS using "SMS" RCML verb in voice application
// 3. SmsInterpreter.CreatingSmsSession - Send SMS using "SMS" RCML verb in sms application
// 4. SmppInterpreter.CreatingSmsSession - Send SMS using "SMS" RCML verb when SMPP link is activated
public CreateSmsSession(final String from, final String to, final String accountSid, final boolean isFromApi) {
this.from = from;
this.to = to;
this.accountSid = accountSid;
this.isFromApi = isFromApi;
}
public String getFrom() {
return from;
}
public String getTo() {
return to;
}
public boolean isFromApi() {
return isFromApi;
}
@Override
public String toString() {
return "From: "+from+" , To: "+to+" , AccountSid: "+accountSid+" , isFromApi: "+isFromApi;
}
/**
* IExtensionRequest
* @return accountSid
*/
@Override
public String getAccountSid() {
return accountSid;
}
/**
* IExtensionRequest
* @return if allowed
*/
@Override
public boolean isAllowed() {
return this.allowed;
}
/**
* IExtensionRequest
* @param set allowed
*/
@Override
public void setAllowed(boolean allowed) {
this.allowed = allowed;
}
/**
* IExtensionCreateSmsSessionRequest
* @param set Configuration object
*/
@Override
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
/**
* IExtensionCreateSmsSessionRequest
* @return Configuration object
*/
@Override
public Configuration getConfiguration() {
return this.configuration;
}
}
| 3,304 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsStatusUpdated.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/SmsStatusUpdated.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.sms.api;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* This event is triggered when a message status has been updated from the network.
*
* @author
*/
@Immutable
public final class SmsStatusUpdated {
private final SmsSessionInfo info;
public SmsStatusUpdated(SmsSessionInfo info) {
this.info = info;
}
public SmsSessionInfo getInfo() {
return info;
}
}
| 1,271 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsSessionResponse.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/SmsSessionResponse.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.sms.api;
/**
* @author [email protected] (Thomas Quintana)
*/
public final class SmsSessionResponse {
private final SmsSessionInfo info;
private final boolean success;
public SmsSessionResponse(final SmsSessionInfo info, final boolean success) {
super();
this.info = info;
this.success = success;
}
public SmsSessionInfo info() {
return info;
}
public boolean succeeded() {
return success;
}
}
| 1,320 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
GetLastSmsRequest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sms.api/src/main/java/org/restcomm/connect/sms/api/GetLastSmsRequest.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.sms.api;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class GetLastSmsRequest {
public GetLastSmsRequest() {
super();
}
}
| 1,096 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
AllowingExtensionMockTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/test/java/org/restcomm/connect/extension/mock/AllowingExtensionMockTest.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.extension.mock;
import javax.servlet.ServletContext;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.ExtensionsConfigurationDao;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
/**
*
* @author
*/
public class AllowingExtensionMockTest {
public AllowingExtensionMockTest() {
}
class ExtensionCollaborators {
ServletContext sCtx = Mockito.mock(ServletContext.class);
DaoManager daoMng = Mockito.mock(DaoManager.class);
ExtensionsConfigurationDao extDao = Mockito.mock(ExtensionsConfigurationDao.class);
public ExtensionCollaborators() {
when(sCtx.getAttribute(DaoManager.class.getName())).
thenReturn(daoMng);
when(daoMng.getExtensionsConfigurationDao()).
thenReturn(extDao);
when(extDao.getConfigurationByName("allowing")).thenReturn(null);
}
}
@Test
public void testAllowingExtension() throws Exception {
ExtensionCollaborators mocks = new ExtensionCollaborators();
AllowingExtensionMock extension = new AllowingExtensionMock();
extension.init(mocks.sCtx);
final ExtensionRequest far = new ExtensionRequest("aacountSid", true);
ExtensionResponse response = extension.preInboundAction(far);
Assert.assertTrue(response.isAllowed());
response = extension.postInboundAction(far);
Assert.assertTrue(response.isAllowed());
response = extension.preOutboundAction(far);
Assert.assertTrue(response.isAllowed());
response = extension.postOutboundAction(far);
Assert.assertTrue(response.isAllowed());
ApiRequest apiReq = new ApiRequest("aacountSid", null, ApiRequest.Type.CREATE_SUBACCOUNT);
response = extension.preApiAction(apiReq);
Assert.assertTrue(response.isAllowed());
response = extension.postApiAction(apiReq);
Assert.assertTrue(response.isAllowed());
}
}
| 3,072 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
OutboundBlockingExtensionMockTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/test/java/org/restcomm/connect/extension/mock/OutboundBlockingExtensionMockTest.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.extension.mock;
import javax.servlet.ServletContext;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.ExtensionsConfigurationDao;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
/**
*
* @author
*/
public class OutboundBlockingExtensionMockTest {
public OutboundBlockingExtensionMockTest() {
}
class ExtensionCollaborators {
ServletContext sCtx = Mockito.mock(ServletContext.class);
DaoManager daoMng = Mockito.mock(DaoManager.class);
ExtensionsConfigurationDao extDao = Mockito.mock(ExtensionsConfigurationDao.class);
public ExtensionCollaborators() {
when(sCtx.getAttribute(DaoManager.class.getName())).
thenReturn(daoMng);
when(daoMng.getExtensionsConfigurationDao()).
thenReturn(extDao);
when(extDao.getConfigurationByName("outbound_blocking")).thenReturn(null);
}
}
@Test
public void testExtension() throws Exception {
ExtensionCollaborators mocks = new ExtensionCollaborators();
OutboundBlockingExtensionMock extension = new OutboundBlockingExtensionMock();
extension.init(mocks.sCtx);
final ExtensionRequest far = new ExtensionRequest("accountSid", true);
ExtensionResponse response = extension.preInboundAction(far);
Assert.assertTrue(response.isAllowed());
response = extension.postInboundAction(far);
Assert.assertTrue(response.isAllowed());
response = extension.preOutboundAction(far);
Assert.assertFalse(response.isAllowed());
response = extension.postOutboundAction(far);
Assert.assertFalse(response.isAllowed());
ApiRequest apiReq = new ApiRequest("accountSid", null, ApiRequest.Type.CREATE_SUBACCOUNT);
response = extension.preApiAction(apiReq);
Assert.assertTrue(response.isAllowed());
response = extension.postApiAction(apiReq);
Assert.assertTrue(response.isAllowed());
}
}
| 3,097 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
BlockingExtensionMockTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/test/java/org/restcomm/connect/extension/mock/BlockingExtensionMockTest.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.extension.mock;
import javax.servlet.ServletContext;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.ExtensionsConfigurationDao;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
/**
*
* @author
*/
public class BlockingExtensionMockTest {
public BlockingExtensionMockTest() {
}
class ExtensionCollaborators {
ServletContext sCtx = Mockito.mock(ServletContext.class);
DaoManager daoMng = Mockito.mock(DaoManager.class);
ExtensionsConfigurationDao extDao = Mockito.mock(ExtensionsConfigurationDao.class);
public ExtensionCollaborators() {
when(sCtx.getAttribute(DaoManager.class.getName())).
thenReturn(daoMng);
when(daoMng.getExtensionsConfigurationDao()).
thenReturn(extDao);
when(extDao.getConfigurationByName("blocking")).thenReturn(null);
}
}
@Test
public void testAllowingExtension() throws Exception {
ExtensionCollaborators mocks = new ExtensionCollaborators();
BlockingExtensionMock extension = new BlockingExtensionMock();
extension.init(mocks.sCtx);
final ExtensionRequest far = new ExtensionRequest("accountSid", true);
ExtensionResponse response = extension.preInboundAction(far);
Assert.assertFalse(response.isAllowed());
response = extension.postInboundAction(far);
Assert.assertFalse(response.isAllowed());
response = extension.preOutboundAction(far);
Assert.assertFalse(response.isAllowed());
response = extension.postOutboundAction(far);
Assert.assertFalse(response.isAllowed());
ApiRequest apiReq = new ApiRequest("accountSid", null, ApiRequest.Type.CREATE_SUBACCOUNT);
response = extension.preApiAction(apiReq);
Assert.assertFalse(response.isAllowed());
response = extension.postApiAction(apiReq);
Assert.assertFalse(response.isAllowed());
}
}
| 3,068 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DBExtensionMockTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/test/java/org/restcomm/connect/extension/mock/DBExtensionMockTest.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.extension.mock;
import java.util.Calendar;
import javax.servlet.ServletContext;
import org.joda.time.DateTime;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import static org.mockito.Mockito.when;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.ExtensionsConfigurationDao;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionConfiguration;
import static org.restcomm.connect.extension.api.ExtensionConfiguration.configurationType.JSON;
import org.restcomm.connect.extension.api.ExtensionRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
/**
*
* @author
*/
public class DBExtensionMockTest {
private static final String EXT_CONF="{}";
public DBExtensionMockTest() {
}
class ExtensionCollaborators {
ServletContext sCtx = Mockito.mock(ServletContext.class);
DaoManager daoMng = Mockito.mock(DaoManager.class);
ExtensionsConfigurationDao extDao = Mockito.mock(ExtensionsConfigurationDao.class);
public ExtensionCollaborators(String confJson) {
when(sCtx.getAttribute(DaoManager.class.getName())).
thenReturn(daoMng);
when(daoMng.getExtensionsConfigurationDao()).
thenReturn(extDao);
ExtensionConfiguration extConf = new ExtensionConfiguration(Sid.
generate(Sid.Type.EXTENSION_CONFIGURATION),
"simple_db",
true,
confJson,
JSON,
new DateTime(),new DateTime());
when(extDao.getConfigurationByName("simple_db")).thenReturn(null);
}
}
@Test
public void testAllowingExtension() throws Exception {
ExtensionCollaborators mocks = new ExtensionCollaborators(EXT_CONF);
DBExtensionMock extension = new DBExtensionMock();
extension.init(mocks.sCtx);
final ExtensionRequest far = new ExtensionRequest("accountSid", true);
ExtensionResponse response = extension.preInboundAction(far);
Assert.assertTrue(response.isAllowed());
response = extension.postInboundAction(far);
Assert.assertTrue(response.isAllowed());
response = extension.preOutboundAction(far);
Assert.assertTrue(response.isAllowed());
response = extension.postOutboundAction(far);
Assert.assertTrue(response.isAllowed());
ApiRequest apiReq = new ApiRequest("accountSid", null, ApiRequest.Type.CREATE_SUBACCOUNT);
response = extension.preApiAction(apiReq);
Assert.assertTrue(response.isAllowed());
response = extension.postApiAction(apiReq);
Assert.assertTrue(response.isAllowed());
}
}
| 3,682 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ExtensionsControllerTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/test/java/org.restcomm.connect.extension.controller/ExtensionsControllerTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2018, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.restcomm.connect.extension.controller;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionRequest;
import org.restcomm.connect.extension.api.RestcommExtension;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
public class ExtensionsControllerTest {
private static Logger logger = Logger.getLogger(ExtensionsControllerTest.class);
private RestcommExtensionGeneric testExtension = new TestExtension();
@After
public void resteController() {
//reset the singleton after each test to provide isolation and
//predictibiltiy when full test class is executed
ExtensionController.getInstance().reset();
}
@Test
public void extensionRegistry() {
ExtensionController extensionController = ExtensionController.getInstance();
extensionController.registerExtension(testExtension);
List<RestcommExtensionGeneric> callManagerExts = extensionController.getExtensions(ExtensionType.CallManager);
logger.info("CallManagerExtensions list size: "+callManagerExts.size());
for (RestcommExtensionGeneric ext: callManagerExts) {
logger.info("ExtensionName: "+ext.getName());
}
Assert.assertEquals(1, callManagerExts.size());
Assert.assertEquals(1, extensionController.getExtensions(ExtensionType.FeatureAccessControl).size());
Assert.assertEquals(1, extensionController.getExtensions(ExtensionType.RestApi).size());
Assert.assertEquals(1, extensionController.getExtensions(ExtensionType.SmsService).size());
Assert.assertEquals(1, extensionController.getExtensions(ExtensionType.UssdCallManager).size());
}
@Test
public void preInboundActionTest() {
ExtensionController extensionController = ExtensionController.getInstance();
extensionController.registerExtension(testExtension);
List<RestcommExtensionGeneric> extensions = extensionController.getExtensions(ExtensionType.FeatureAccessControl);
IExtensionRequest request = new ExtensionRequest();
ExtensionResponse er = extensionController.executePreInboundAction(request, extensions);
Assert.assertNotNull(er);
Assert.assertTrue(er.isAllowed());
}
@Test
public void postInboundActionTest() {
ExtensionController extensionController = ExtensionController.getInstance();
extensionController.registerExtension(testExtension);
List<RestcommExtensionGeneric> extensions = extensionController.getExtensions(ExtensionType.FeatureAccessControl);
IExtensionRequest request = new ExtensionRequest();
ExtensionResponse er = extensionController.executePostInboundAction(request, extensions);
Assert.assertNotNull(er);
Assert.assertTrue(er.isAllowed());
}
@Test
public void preOutboundActionTest() {
ExtensionController extensionController = ExtensionController.getInstance();
extensionController.registerExtension(testExtension);
List<RestcommExtensionGeneric> extensions = extensionController.getExtensions(ExtensionType.FeatureAccessControl);
IExtensionRequest request = new ExtensionRequest();
ExtensionResponse er = extensionController.executePreOutboundAction(request, extensions);
Assert.assertNotNull(er);
Assert.assertTrue(er.isAllowed());
}
@Test
public void postOutboundActionTest() {
ExtensionController extensionController = ExtensionController.getInstance();
extensionController.registerExtension(testExtension);
List<RestcommExtensionGeneric> extensions = extensionController.getExtensions(ExtensionType.FeatureAccessControl);
IExtensionRequest request = new ExtensionRequest();
ExtensionResponse er = extensionController.executePostOutboundAction(request, extensions);
Assert.assertNotNull(er);
Assert.assertTrue(er.isAllowed());
}
@Test
public void preApiActionTest() {
ExtensionController extensionController = ExtensionController.getInstance();
extensionController.registerExtension(testExtension);
List<RestcommExtensionGeneric> extensions = extensionController.getExtensions(ExtensionType.FeatureAccessControl);
Sid accSid = Sid.generate(Sid.Type.ACCOUNT);
ApiRequest apiRequest = new ApiRequest(accSid.toString(), null, ApiRequest.Type.CREATE_SUBACCOUNT);
ExtensionResponse er = extensionController.executePreApiAction(apiRequest, extensions);
Assert.assertNotNull(er);
Assert.assertTrue(er.isAllowed());
}
@Test
public void postApiActionTest() {
ExtensionController extensionController = ExtensionController.getInstance();
extensionController.registerExtension(testExtension);
List<RestcommExtensionGeneric> extensions = extensionController.getExtensions(ExtensionType.FeatureAccessControl);
Sid accSid = Sid.generate(Sid.Type.ACCOUNT);
ApiRequest apiRequest = new ApiRequest(accSid.toString(), null, ApiRequest.Type.CREATE_SUBACCOUNT);
ExtensionResponse er = extensionController.executePostApiAction(apiRequest, extensions);
Assert.assertNotNull(er);
Assert.assertTrue(er.isAllowed());
}
@RestcommExtension(author = "TestExtension", version = "1.0.0.Alpha", type = {ExtensionType.CallManager, ExtensionType.SmsService, ExtensionType.UssdCallManager, ExtensionType.FeatureAccessControl, ExtensionType.RestApi})
private class TestExtension implements RestcommExtensionGeneric {
@Override
public void init (ServletContext context) {
}
@Override
public boolean isEnabled () {
return true;
}
@Override
public ExtensionResponse preInboundAction (IExtensionRequest extensionRequest) {
return null;
}
@Override
public ExtensionResponse postInboundAction (IExtensionRequest extensionRequest) {
return null;
}
@Override
public ExtensionResponse preOutboundAction (IExtensionRequest extensionRequest) {
return null;
}
@Override
public ExtensionResponse postOutboundAction (IExtensionRequest extensionRequest) {
return null;
}
@Override
public ExtensionResponse preApiAction (ApiRequest apiRequest) {
return null;
}
@Override
public ExtensionResponse postApiAction (ApiRequest apiRequest) {
return null;
}
@Override
public String getName () {
return "TestExtension";
}
@Override
public String getVersion () {
return null;
}
}
}
| 8,039 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
OutboundBlockingExtensionMock.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/main/java/org/restcomm/connect/extension/mock/OutboundBlockingExtensionMock.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.extension.mock;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionRequest;
import org.restcomm.connect.extension.api.RestcommExtension;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
/**
* Extension that rejects any execution point. Provided for testing purposes
* @author
*/
@RestcommExtension(author = "restcomm", version = "1.0.0.Alpha", type = {ExtensionType.CallManager, ExtensionType.SmsService, ExtensionType.UssdCallManager, ExtensionType.FeatureAccessControl, ExtensionType.RestApi})
public class OutboundBlockingExtensionMock implements RestcommExtensionGeneric {
private static Logger logger = Logger.getLogger(OutboundBlockingExtensionMock.class);
private String extensionName = "outbound_blocking";
private final String localConfigPath = "/outbound_blocking_default_configuration.json";
private MockConfiguration config;
@Override
public void init(ServletContext context) {
try {
DaoManager daoManager = (DaoManager) context.getAttribute(DaoManager.class.getName());
config = new MockConfiguration(daoManager, extensionName, localConfigPath);
config.init(daoManager, extensionName, localConfigPath);
} catch (Exception configurationException) {
logger.error("Exception during init", configurationException);
}
}
@Override
public ExtensionResponse preInboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public ExtensionResponse postInboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public ExtensionResponse preOutboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(false);
return response;
}
@Override
public ExtensionResponse postOutboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(false);
return response;
}
@Override
public ExtensionResponse preApiAction(ApiRequest apiRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public ExtensionResponse postApiAction(ApiRequest apiRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public String getName() {
return this.extensionName;
}
@Override
public String getVersion() {
return ((RestcommExtension) OutboundBlockingExtensionMock.class.getAnnotation(RestcommExtension.class)).version();
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
}
| 4,171 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DBExtensionMock.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/main/java/org/restcomm/connect/extension/mock/DBExtensionMock.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.extension.mock;
import com.google.gson.JsonObject;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionRequest;
import org.restcomm.connect.extension.api.RestcommExtension;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
/**
* Extension that rejects any execution point. Provided for testing purposes
* @author
*/
@RestcommExtension(author = "restcomm", version = "1.0.0.Alpha", type = {ExtensionType.CallManager, ExtensionType.SmsService, ExtensionType.UssdCallManager, ExtensionType.FeatureAccessControl, ExtensionType.RestApi})
public class DBExtensionMock implements RestcommExtensionGeneric {
private static Logger logger = Logger.getLogger(DBExtensionMock.class);
private String extensionName = "simple_db";
private final String localConfigPath = "/simple_db_default_configuration.json";
private MockConfiguration config;
@Override
public void init(ServletContext context) {
try {
DaoManager daoManager = (DaoManager) context.getAttribute(DaoManager.class.getName());
config = new MockConfiguration(daoManager, extensionName, localConfigPath);
config.init(daoManager, extensionName, localConfigPath);
} catch (Exception configurationException) {
logger.error("Exception during init", configurationException);
}
}
private boolean queryRequestAllowed(String req) {
JsonObject currentConf = config.getCurrentConf();
JsonObject jsonFound = currentConf.getAsJsonObject(req);
return jsonFound != null;
}
@Override
public ExtensionResponse preInboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(queryRequestAllowed("pre-inbound-" + extensionRequest.getClass().getSimpleName()));
return response;
}
@Override
public ExtensionResponse postInboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(queryRequestAllowed("post-inbound-" + extensionRequest.getClass().getSimpleName()));
return response;
}
@Override
public ExtensionResponse preOutboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(queryRequestAllowed("pre-outbound-" + extensionRequest.getClass().getSimpleName()));
return response;
}
@Override
public ExtensionResponse postOutboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(queryRequestAllowed("post-outbound-" + extensionRequest.getClass().getSimpleName()));
return response;
}
@Override
public ExtensionResponse preApiAction(ApiRequest apiRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(queryRequestAllowed("pre-api-" + apiRequest.getType()));
return response;
}
@Override
public ExtensionResponse postApiAction(ApiRequest apiRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(queryRequestAllowed("post-api-" + apiRequest.getType()));
return response;
}
@Override
public String getName() {
return this.extensionName;
}
@Override
public String getVersion() {
return ((RestcommExtension) DBExtensionMock.class.getAnnotation(RestcommExtension.class)).version();
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
}
| 4,777 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MockConfiguration.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/main/java/org/restcomm/connect/extension/mock/MockConfiguration.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.extension.mock;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.extension.api.ConfigurationException;
import org.restcomm.connect.extension.configuration.DefaultExtensionConfiguration;
public class MockConfiguration extends DefaultExtensionConfiguration{
public MockConfiguration(){
super();
}
public MockConfiguration(DaoManager daoManager, String extensionName, String localConfigPath)
throws ConfigurationException {
super(daoManager, extensionName, localConfigPath);
}
}
| 1,390 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
AllowingExtensionMock.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/main/java/org/restcomm/connect/extension/mock/AllowingExtensionMock.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.extension.mock;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionRequest;
import org.restcomm.connect.extension.api.RestcommExtension;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
/**
* Extension that allows any execution point. Provided for testing purposes
* @author
*/
@RestcommExtension(author = "restcomm", version = "1.0.0.Alpha", type = {ExtensionType.CallManager, ExtensionType.SmsService, ExtensionType.UssdCallManager, ExtensionType.FeatureAccessControl, ExtensionType.RestApi})
public class AllowingExtensionMock implements RestcommExtensionGeneric {
private static Logger logger = Logger.getLogger(AllowingExtensionMock.class);
private String extensionName = "allowing";
private final String localConfigPath = "/allowing_default_configuration.json";
private MockConfiguration config;
@Override
public void init(ServletContext context) {
try {
DaoManager daoManager = (DaoManager) context.getAttribute(DaoManager.class.getName());
config = new MockConfiguration(daoManager, extensionName, localConfigPath);
config.init(daoManager, extensionName, localConfigPath);
} catch (Exception configurationException) {
logger.error("Exception during init", configurationException);
}
}
@Override
public ExtensionResponse preInboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public ExtensionResponse postInboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public ExtensionResponse preOutboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public ExtensionResponse postOutboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public ExtensionResponse preApiAction(ApiRequest apiRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public ExtensionResponse postApiAction(ApiRequest apiRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(true);
return response;
}
@Override
public String getName() {
return this.extensionName;
}
@Override
public String getVersion() {
return ((RestcommExtension) AllowingExtensionMock.class.getAnnotation(RestcommExtension.class)).version();
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
}
| 4,126 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
BlockingExtensionMock.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/main/java/org/restcomm/connect/extension/mock/BlockingExtensionMock.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.extension.mock;
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionRequest;
import org.restcomm.connect.extension.api.RestcommExtension;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
/**
* Extension that rejects any execution point. Provided for testing purposes
* @author
*/
@RestcommExtension(author = "restcomm", version = "1.0.0.Alpha", type = {ExtensionType.CallManager, ExtensionType.SmsService, ExtensionType.UssdCallManager, ExtensionType.FeatureAccessControl, ExtensionType.RestApi})
public class BlockingExtensionMock implements RestcommExtensionGeneric {
private static Logger logger = Logger.getLogger(BlockingExtensionMock.class);
private String extensionName = "blocking";
private final String localConfigPath = "/blocking_default_configuration.json";
private MockConfiguration config;
@Override
public void init(ServletContext context) {
try {
DaoManager daoManager = (DaoManager) context.getAttribute(DaoManager.class.getName());
config = new MockConfiguration(daoManager, extensionName, localConfigPath);
config.init(daoManager, extensionName, localConfigPath);
} catch (Exception configurationException) {
logger.error("Exception during init", configurationException);
}
}
@Override
public ExtensionResponse preInboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(false);
return response;
}
@Override
public ExtensionResponse postInboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(false);
return response;
}
@Override
public ExtensionResponse preOutboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(false);
return response;
}
@Override
public ExtensionResponse postOutboundAction(IExtensionRequest extensionRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(false);
return response;
}
@Override
public ExtensionResponse preApiAction(ApiRequest apiRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(false);
return response;
}
@Override
public ExtensionResponse postApiAction(ApiRequest apiRequest) {
ExtensionResponse response = new ExtensionResponse();
response.setAllowed(false);
return response;
}
@Override
public String getName() {
return this.extensionName;
}
@Override
public String getVersion() {
return ((RestcommExtension) BlockingExtensionMock.class.getAnnotation(RestcommExtension.class)).version();
}
@Override
public boolean isEnabled() {
return config.isEnabled();
}
}
| 4,133 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ExtensionController.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/main/java/org/restcomm/connect/extension/controller/ExtensionController.java | package org.restcomm.connect.extension.controller;
import org.restcomm.connect.extension.api.ApiRequest;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionRequest;
import org.restcomm.connect.extension.api.RestcommExtension;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
import org.apache.log4j.Logger;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Created by gvagenas on 21/09/16.
*/
public class ExtensionController {
private static Logger logger = Logger.getLogger(ExtensionController.class);
private static ExtensionController instance;
private List callManagerExtensions;
private List smsSessionExtensions;
private List ussdCallManagerExtensions;
private List restApiExtensions;
private List featureAccessControlExtensions;
private ExtensionController(){
this.callManagerExtensions = new CopyOnWriteArrayList();
this.smsSessionExtensions = new CopyOnWriteArrayList();
this.ussdCallManagerExtensions = new CopyOnWriteArrayList();
this.restApiExtensions = new CopyOnWriteArrayList();
this.featureAccessControlExtensions = new CopyOnWriteArrayList();
}
public static ExtensionController getInstance() {
if (instance == null) {
instance = new ExtensionController();
}
return instance;
}
/**
* allow to reset the singleton. Mainly for testing purposes.
* TODO should we reset the singleton if app is shutdown...?
*/
public void reset() {
instance = null;
}
public List<RestcommExtensionGeneric> getExtensions(final ExtensionType type) {
//Check the sender's class and return the extensions that are supported for this class
if (type.equals(ExtensionType.CallManager) && (callManagerExtensions != null && callManagerExtensions.size() > 0)) {
return callManagerExtensions;
} else if (type.equals(ExtensionType.SmsService) && (smsSessionExtensions != null && smsSessionExtensions.size() > 0)) {
return smsSessionExtensions;
} else if (type.equals(ExtensionType.UssdCallManager) && (ussdCallManagerExtensions != null && ussdCallManagerExtensions.size() > 0)) {
return ussdCallManagerExtensions;
} else if (type.equals(ExtensionType.RestApi) && (restApiExtensions != null && restApiExtensions.size() > 0)) {
return restApiExtensions;
} else if (type.equals(ExtensionType.FeatureAccessControl) && (featureAccessControlExtensions != null && featureAccessControlExtensions.size() > 0)) {
return featureAccessControlExtensions;
} else {
return null;
}
}
public void registerExtension(final RestcommExtensionGeneric extension) {
//scan the annotation to see what this extension supports
ExtensionType[] types = extension.getClass().getAnnotation(RestcommExtension.class).type();
String extensionName = extension.getClass().getName();
for (ExtensionType type : types) {
if (type.equals(ExtensionType.CallManager)) {
callManagerExtensions.add(extension);
if (logger.isDebugEnabled()) {
logger.debug("CallManager extension added: "+extensionName);
}
}
if (type.equals(ExtensionType.SmsService)) {
smsSessionExtensions.add(extension);
if (logger.isDebugEnabled()) {
logger.debug("SmsService extension added: "+extensionName);
}
}
if (type.equals(ExtensionType.UssdCallManager)) {
ussdCallManagerExtensions.add(extension);
if (logger.isDebugEnabled()) {
logger.debug("UssdCallManager extension added: "+extensionName);
}
}
if (type.equals(ExtensionType.RestApi)) {
restApiExtensions.add(extension);
if (logger.isDebugEnabled()) {
logger.debug("RestApi extension added: "+extensionName);
}
}
if (type.equals(ExtensionType.FeatureAccessControl)) {
featureAccessControlExtensions.add(extension);
if (logger.isDebugEnabled()) {
logger.debug("FeatureAccesControl extension added: "+extensionName);
}
}
}
}
public ExtensionResponse executePreOutboundAction(final IExtensionRequest ier, List<RestcommExtensionGeneric> extensions) {
//FIXME: if we have more than one extension in chain
// and all of them are successful, we only receive the last
// extensionResponse
ExtensionResponse response = new ExtensionResponse();
if (extensions != null && extensions.size() > 0) {
for (RestcommExtensionGeneric extension : extensions) {
if(logger.isInfoEnabled()) {
logger.info( extension.getName()+" is enabled="+extension.isEnabled());
}
if (extension.isEnabled()) {
try {
ExtensionResponse tempResponse = extension.preOutboundAction(ier);
if (tempResponse != null) {
response = tempResponse;
//fail fast
if (!tempResponse.isAllowed()) {
break;
}
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) {
String msg = String.format("There was an exception while executing preInboundAction from extension %s", extension.getName());
logger.debug(msg, t);
}
}
}
}
}
return response;
}
public ExtensionResponse executePostOutboundAction(final IExtensionRequest er, List<RestcommExtensionGeneric> extensions) {
ExtensionResponse response = new ExtensionResponse();
if (extensions != null && extensions.size() > 0) {
for (RestcommExtensionGeneric extension : extensions) {
if(logger.isInfoEnabled()) {
logger.info( extension.getName()+" is enabled="+extension.isEnabled());
}
if (extension.isEnabled()) {
try {
ExtensionResponse tempResponse = extension.postOutboundAction(er);
if (tempResponse != null) {
response = tempResponse;
//fail fast
if (!tempResponse.isAllowed()) {
break;
}
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) {
String msg = String.format("There was an exception while executing preInboundAction from extension %s", extension.getName());
logger.debug(msg, t);
}
}
}
}
}
return response;
}
public ExtensionResponse executePreInboundAction(final IExtensionRequest er, List<RestcommExtensionGeneric> extensions) {
ExtensionResponse response = new ExtensionResponse();
if (extensions != null && extensions.size() > 0) {
for (RestcommExtensionGeneric extension : extensions) {
if(logger.isInfoEnabled()) {
logger.info( extension.getName()+" is enabled="+extension.isEnabled());
}
if (extension.isEnabled()) {
try {
ExtensionResponse tempResponse = extension.preInboundAction(er);
if (tempResponse != null) {
response = tempResponse;
//fail fast
if (!tempResponse.isAllowed()) {
break;
}
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) {
String msg = String.format("There was an exception while executing preInboundAction from extension %s", extension.getName());
logger.debug(msg, t);
}
}
}
}
}
return response;
}
public ExtensionResponse executePostInboundAction(final IExtensionRequest er, List<RestcommExtensionGeneric> extensions) {
ExtensionResponse response = new ExtensionResponse();
if (extensions != null && extensions.size() > 0) {
for (RestcommExtensionGeneric extension : extensions) {
if(logger.isInfoEnabled()) {
logger.info( extension.getName()+" is enabled="+extension.isEnabled());
}
if (extension.isEnabled()) {
try {
ExtensionResponse tempResponse = extension.postInboundAction(er);
if (tempResponse != null) {
response = tempResponse;
//fail fast
if (!tempResponse.isAllowed()) {
break;
}
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) {
String msg = String.format("There was an exception while executing preInboundAction from extension %s", extension.getName());
logger.debug(msg, t);
}
}
}
}
}
return response;
}
public ExtensionResponse executePreApiAction(final ApiRequest apiRequest, List<RestcommExtensionGeneric> extensions) {
ExtensionResponse response = new ExtensionResponse();
if (extensions != null && extensions.size() > 0) {
for (RestcommExtensionGeneric extension : extensions) {
if(logger.isInfoEnabled()) {
logger.info( extension.getName()+" is enabled="+extension.isEnabled());
}
if (extension.isEnabled()) {
try {
ExtensionResponse tempResponse = extension.preApiAction(apiRequest);
if (tempResponse != null) {
response = tempResponse;
//fail fast
if (!tempResponse.isAllowed()) {
break;
}
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) {
String msg = String.format("There was an exception while executing preInboundAction from extension %s", extension.getName());
logger.debug(msg, t);
}
}
}
}
}
return response;
}
public ExtensionResponse executePostApiAction(final ApiRequest apiRequest, List<RestcommExtensionGeneric> extensions) {
ExtensionResponse response = new ExtensionResponse();
if (extensions != null && extensions.size() > 0) {
for (RestcommExtensionGeneric extension : extensions) {
if(logger.isInfoEnabled()) {
logger.info( extension.getName()+" is enabled="+extension.isEnabled());
}
if (extension.isEnabled()) {
try {
ExtensionResponse tempResponse = extension.postApiAction(apiRequest);
if (tempResponse != null) {
response = tempResponse;
//fail fast
if (!tempResponse.isAllowed()) {
break;
}
}
} catch (Throwable t) {
if (logger.isDebugEnabled()) {
String msg = String.format("There was an exception while executing preInboundAction from extension %s", extension.getName());
logger.debug(msg, t);
}
}
}
}
}
return response;
}
}
| 12,892 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ExtensionBootstrapper.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/main/java/org/restcomm/connect/extension/controller/ExtensionBootstrapper.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.extension.controller;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public class ExtensionBootstrapper {
private Logger logger = Logger.getLogger(ExtensionBootstrapper.class);
private Configuration configuration;
private ServletContext context;
List<Object> extensions = new ArrayList<Object>();
public ExtensionBootstrapper(final ServletContext context, final Configuration configuration) {
this.configuration = configuration;
this.context = context;
}
public void start() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
List<HierarchicalConfiguration> exts = ((XMLConfiguration)configuration).configurationsAt("extensions.extension");
for (HierarchicalConfiguration ext: exts) {
String name = ext.getString("[@name]");
String className = ext.getString("class");
boolean enabled = ext.getBoolean("enabled");
if (enabled) {
try {
Class<RestcommExtensionGeneric> klass = (Class<RestcommExtensionGeneric>) Class.forName(className);
RestcommExtensionGeneric extension = klass.newInstance();
extension.init(this.context);
//Store it in the context using the extension name
context.setAttribute(name, extension);
ExtensionController.getInstance().registerExtension(extension);
if (logger.isInfoEnabled()) {
logger.info("Stated Extension: " + name);
}
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Exception during initialization of extension \""+name+"\", exception: "+e.getStackTrace());
}
}
}
}
}
}
| 3,226 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DefaultExtensionConfiguration.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.controller/src/main/java/org/restcomm/connect/extension/configuration/DefaultExtensionConfiguration.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2016, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package org.restcomm.connect.extension.configuration;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.ibatis.exceptions.PersistenceException;
import org.apache.log4j.Logger;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.ExtensionsConfigurationDao;
import org.restcomm.connect.extension.api.ConfigurationException;
import org.restcomm.connect.extension.api.ExtensionConfiguration;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
public class DefaultExtensionConfiguration {
public enum PropertyType {
VERSION("version");
private String value;
private PropertyType(String value) {
this.value = value;
}
};
private static final Logger logger = Logger.getLogger(DefaultExtensionConfiguration.class);
private boolean workingWithLocalConf;
private ExtensionsConfigurationDao extensionConfigurationDao;
private ExtensionConfiguration extensionConfiguration;
private JsonObject configurationJsonObj;
private JsonParser jsonParser;
private DaoManager daoManager;
private Gson gson;
private JsonObject defaultConfigurationJsonObj;
private String extensionName;
private DefaultArtifactVersion defVersion;
private HashMap<String, String> specificConfigurationMap;
private Sid sid;
private String localConfigPath;
public DefaultExtensionConfiguration() {
this.sid = new Sid("EX00000000000000000000000000000001");
this.localConfigPath = "";
}
public DefaultExtensionConfiguration(final DaoManager daoManager, String extensionName, String localConfigPath) {
try {
init(daoManager, extensionName, localConfigPath);
} catch (Exception e) {
logger.error("Exception initializing");
}
}
public void init(final DaoManager daoManager, String extensionName, String localConfigPath) throws ConfigurationException {
try {
this.setDaoManager(daoManager);
this.extensionConfigurationDao = daoManager.getExtensionsConfigurationDao();
if (extensionName.isEmpty() && localConfigPath.isEmpty()) {
throw new ConfigurationException("extensionName or local config cant be empty");
}
if (!extensionName.isEmpty()) {
this.extensionName = extensionName;
}
if (!localConfigPath.isEmpty()) {
// Load the default extensionConfiguration from file
this.defaultConfigurationJsonObj = loadDefaultConfiguration(localConfigPath);
configurationJsonObj = this.defaultConfigurationJsonObj;
// Get the extension name from default extensionConfiguration
String temp = defaultConfigurationJsonObj.get("extension_name").getAsString();
if (!temp.isEmpty()) {
extensionName = temp;
}
defVersion = new DefaultArtifactVersion(defaultConfigurationJsonObj.get("version").getAsString());
}
// Load extensionConfiguration from DB
extensionConfiguration = extensionConfigurationDao.getConfigurationByName(extensionName);
// try fetch sid from name
if (extensionConfiguration == null) {
// If extensionConfiguration from DB is null then add the default values to DB
this.sid = Sid.generate(Sid.Type.EXTENSION_CONFIGURATION);
extensionConfiguration = new ExtensionConfiguration(sid, this.extensionName, true,
defaultConfigurationJsonObj.toString(), ExtensionConfiguration.configurationType.JSON, DateTime.now());
extensionConfigurationDao.addConfiguration(extensionConfiguration);
} else {
// Get configuration object
this.sid = extensionConfiguration.getSid();
// try get default config data
JsonObject dbConfiguration = null;
DefaultArtifactVersion currentVersion = null;
try {
dbConfiguration = (JsonObject) jsonParser.parse((String) extensionConfiguration.getConfigurationData());
if (dbConfiguration.get("version") != null) {
currentVersion = new DefaultArtifactVersion(dbConfiguration.get("version").getAsString());
}
if (dbConfiguration != null && (currentVersion == null || currentVersion.compareTo(defVersion) < 0)) {
if (logger.isInfoEnabled()) {
logger.info("Configuration found in the DB is older version than the default one: "
+ defVersion.toString());
}
for (Map.Entry<String, JsonElement> jsonElementEntry : defaultConfigurationJsonObj.entrySet()) {
if (!jsonElementEntry.getKey().equalsIgnoreCase("specifics_configuration")
&& dbConfiguration.get(jsonElementEntry.getKey()) == null) {
dbConfiguration.add(jsonElementEntry.getKey(), jsonElementEntry.getValue());
}
}
if (dbConfiguration.get("version") != null) {
dbConfiguration.remove("version");
}
dbConfiguration.addProperty("version", defaultConfigurationJsonObj.get("version").getAsString());
extensionConfiguration = new ExtensionConfiguration(extensionConfiguration.getSid(), extensionName,
extensionConfiguration.isEnabled(), dbConfiguration.toString(),
ExtensionConfiguration.configurationType.JSON, DateTime.now());
extensionConfigurationDao.updateConfiguration(extensionConfiguration);
}
configurationJsonObj = dbConfiguration;
// Load Specific Configuration Map
// loadSpecificConfigurationMap(configurationJsonObj);
} catch (Exception e) {
}
}
if (logger.isInfoEnabled()) {
logger.info("Finished loading configuration for extension: " + extensionName);
}
} catch (ConfigurationException configurationException) {
String errorMessage = "Exception during " + this.getClass() + " Configuration constructor ";
if (logger.isDebugEnabled()) {
logger.debug(errorMessage + configurationException);
}
throw new ConfigurationException(errorMessage);
} catch (PersistenceException persistenceException) {
if (logger.isDebugEnabled()) {
logger.debug("PersistenceException during " + this.getClass() + " init, will fallback to default configuration");
}
workingWithLocalConf = true;
} catch (IOException e) {
logger.debug("IOException during " + this.getClass());
}
}
public JsonObject loadDefaultConfiguration(String localConfigFilePath) throws IOException {
JsonObject jsonObj = null;
jsonParser = new JsonParser();
InputStream in = (InputStream) getClass().getResourceAsStream(localConfigFilePath);
BufferedReader inReader = new BufferedReader(new InputStreamReader(in));
JsonReader reader = new JsonReader(inReader);
JsonElement jsonElement = jsonParser.parse(reader);
jsonObj = (JsonObject) jsonElement;
in.close();
inReader.close();
reader.close();
return jsonObj;
}
public void reloadConfiguration() {
if (!workingWithLocalConf) {
if (extensionConfigurationDao.isLatestVersionByName(extensionName, extensionConfiguration.getDateUpdated())) {
extensionConfiguration = extensionConfigurationDao.getConfigurationByName(extensionName);
String updatedConf = (String) extensionConfiguration.getConfigurationData();
configurationJsonObj = (JsonObject) jsonParser.parse(updatedConf);
// loadSpecificConfigurationMap(configurationJsonObj);
if (logger.isInfoEnabled()) {
logger.info(this.extensionName + " extension configuration reloaded");
}
}
}
}
public boolean isEnabled() {
reloadConfiguration();
if (extensionConfiguration != null) {
return extensionConfiguration.isEnabled();
} else {
return true;
}
}
public String getVersion() {
reloadConfiguration();
String ver = configurationJsonObj.get(PropertyType.VERSION.value).getAsString();
return ver;
}
public Sid getSid() {
return this.sid;
}
public void loadSpecificConfigurationMap(final JsonObject json) {
JsonArray specificConfJsonArray = json.getAsJsonArray();
// JsonArray specificConfJsonArray = json.getAsJsonArray("specifics_configuration");
// if (specificConfJsonArray != null) {
// specificConfigurationMap = new HashMap<String,String>();
// Iterator<JsonElement> iter = specificConfJsonArray.iterator();
// while (iter.hasNext()) {
// JsonElement elem = iter.next();
// if (elem.getAsJsonObject().get("sid") != null) {
// specificConfigurationMap.put(sid, value);
// }
// }
// }
// return map
}
// getConfigAsJson
// getConfigAsConfiguration
// getConfigAsHashMap
/*public void getSpecificConfigurationMapAsXml() {
}*/
/**
* @return the daoManager
*/
public DaoManager getDaoManager() {
return daoManager;
}
/**
* @param daoManager the daoManager to set
*/
public void setDaoManager(DaoManager daoManager) {
this.daoManager = daoManager;
}
public JsonObject getCurrentConf() {
return configurationJsonObj;
}
}
| 11,689 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MmsBridgeController.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.mms/src/main/java/org/restcomm/connect/mscontrol/mms/MmsBridgeController.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.mscontrol.mms;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.apache.commons.configuration.Configuration;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.dao.Sid;
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.fsm.TransitionFailedException;
import org.restcomm.connect.commons.fsm.TransitionNotFoundException;
import org.restcomm.connect.commons.fsm.TransitionRollbackException;
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.util.WavUtils;
import org.restcomm.connect.core.service.RestcommConnectServiceProvider;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.RecordingsDao;
import org.restcomm.connect.dao.entities.MediaAttributes;
import org.restcomm.connect.dao.entities.Recording;
import org.restcomm.connect.mgcp.CreateConferenceEndpoint;
import org.restcomm.connect.mgcp.DestroyEndpoint;
import org.restcomm.connect.mgcp.EndpointState;
import org.restcomm.connect.mgcp.EndpointStateChanged;
import org.restcomm.connect.mgcp.MediaGatewayResponse;
import org.restcomm.connect.mgcp.MediaResourceBrokerResponse;
import org.restcomm.connect.mgcp.MediaSession;
import org.restcomm.connect.mrb.api.GetMediaGateway;
import org.restcomm.connect.mscontrol.api.MediaServerController;
import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession;
import org.restcomm.connect.mscontrol.api.messages.JoinBridge;
import org.restcomm.connect.mscontrol.api.messages.JoinCall;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupStateChanged;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged.MediaServerControllerState;
import org.restcomm.connect.mscontrol.api.messages.Record;
import org.restcomm.connect.mscontrol.api.messages.StartMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.StartRecording;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Henrique Rosa ([email protected])
* @author [email protected] (Maria Farooq)
*
*/
public class MmsBridgeController extends MediaServerController {
// Logging
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Finite State Machine
private final FiniteStateMachine fsm;
private final State uninitialized;
private final State getMediaGatewayFromMRB;
private final State active;
private final State acquiringMediaSession;
private final State acquiringEndpoint;
private final State creatingMediaGroup;
private final State stopping;
private final State inactive;
private final State failed;
private Boolean fail;
// MGCP runtime stuff
private ActorRef mediaGateway;
private MediaSession mediaSession;
private ActorRef endpoint;
private final ActorRef mrb;
// Conference runtime stuff
private ActorRef bridge;
private ActorRef mediaGroup;
// Call Recording
private Boolean recording;
private DateTime recordStarted;
private StartRecording recordingRequest;
private boolean stoppingStatePending;
// Observers
private final List<ActorRef> observers;
private Sid callSid;
public MmsBridgeController(final ActorRef mrb) {
final ActorRef self = self();
// Finite states
this.uninitialized = new State("uninitialized", null, null);
this.getMediaGatewayFromMRB = new State("get media gateway from mrb", new GetMediaGatewayFromMRB(self), null);
this.active = new State("active", new Active(self), null);
this.acquiringMediaSession = new State("acquiring media session", new AcquiringMediaSession(self), null);
this.acquiringEndpoint = new State("acquiring endpoint", new AcquiringEndpoint(self), null);
this.creatingMediaGroup = new State("creating media group", new CreatingMediaGroup(self), null);
this.stopping = new State("stopping", new Stopping(self));
this.inactive = new State("inactive", new Inactive(self));
this.failed = new State("failed", new Failed(self));
// Finite State Machine
final Set<Transition> transitions = new HashSet<Transition>();
transitions.add(new Transition(uninitialized, getMediaGatewayFromMRB));
transitions.add(new Transition(getMediaGatewayFromMRB, acquiringMediaSession));
transitions.add(new Transition(acquiringMediaSession, acquiringEndpoint));
transitions.add(new Transition(acquiringMediaSession, inactive));
transitions.add(new Transition(acquiringEndpoint, creatingMediaGroup));
transitions.add(new Transition(acquiringEndpoint, inactive));
transitions.add(new Transition(creatingMediaGroup, active));
transitions.add(new Transition(creatingMediaGroup, stopping));
transitions.add(new Transition(creatingMediaGroup, failed));
transitions.add(new Transition(active, stopping));
transitions.add(new Transition(stopping, inactive));
transitions.add(new Transition(stopping, stopping));
this.fsm = new FiniteStateMachine(uninitialized, transitions);
this.fail = Boolean.FALSE;
// Media Components
//this.mediaGateway = mediaGateway;
this.mrb = mrb;
// Media Operations
this.recording = Boolean.FALSE;
// Observers
this.observers = new ArrayList<ActorRef>(1);
}
private boolean is(State state) {
return this.fsm.state().equals(state);
}
private void broadcast(Object message) {
if (!this.observers.isEmpty()) {
final ActorRef self = self();
synchronized (this.observers) {
for (ActorRef observer : observers) {
observer.tell(message, self);
}
}
}
}
private void saveRecording() {
final Sid accountId = recordingRequest.getAccountId();
final Sid callId = recordingRequest.getCallId();
final DaoManager daoManager = recordingRequest.getDaoManager();
final Sid recordingSid = recordingRequest.getRecordingSid();
final URI recordingUri = recordingRequest.getRecordingUri();
final Configuration runtimeSettings = recordingRequest.getRuntimeSetting();
Double duration;
try {
duration = WavUtils.getAudioDuration(recordingUri);
} catch (UnsupportedAudioFileException | IOException e) {
logger.error("Could not measure recording duration: " + e.getMessage(), e);
duration = 0.0;
}
if (!duration.equals(0.0)) {
if(logger.isInfoEnabled()) {
logger.info("Call wraping up recording. File already exists, duration: " + duration);
}
final Recording.Builder builder = Recording.builder();
builder.setSid(recordingSid);
builder.setAccountSid(accountId);
builder.setCallSid(callId);
builder.setDuration(duration);
String apiVersion = runtimeSettings.getString("api-version");
builder.setApiVersion(apiVersion);
StringBuilder buffer = new StringBuilder();
buffer.append("/").append(apiVersion).append("/Accounts/").append(accountId.toString());
buffer.append("/Recordings/").append(recordingSid.toString());
builder.setUri(URI.create(buffer.toString()));
builder.setFileUri(RestcommConnectServiceProvider.getInstance().recordingService()
.prepareFileUrl(apiVersion, accountId.toString(), recordingSid.toString(), MediaAttributes.MediaType.AUDIO_ONLY));
URI s3Uri = RestcommConnectServiceProvider.getInstance().recordingService().storeRecording(recordingSid, MediaAttributes.MediaType.AUDIO_ONLY);
if (s3Uri != null) {
builder.setS3Uri(s3Uri);
}
final Recording recording = builder.build();
RecordingsDao recordsDao = daoManager.getRecordingsDao();
recordsDao.addRecording(recording);
getContext().system().eventStream().publish(recording);
} else {
if(logger.isInfoEnabled()) {
logger.info("Call wraping up recording. File doesn't exist since duration is 0");
}
}
}
/*
* Events
*/
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
final State state = fsm.state();
if(logger.isInfoEnabled()) {
logger.info("********** Bridge Controller " + self().path() + " State: \"" + state.toString());
logger.info("********** Bridge Controller " + self().path() + " Processing: \"" + klass.getName() + " Sender: "
+ sender.path());
}
if (Observe.class.equals(klass)) {
onObserve((Observe) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
onStopObserving((StopObserving) message, self, sender);
} else if (CreateMediaSession.class.equals(klass)) {
onCreateMediaSession((CreateMediaSession) message, self, sender);
} else if (JoinCall.class.equals(klass)) {
onJoinCall((JoinCall) message, self, sender);
} else if (Stop.class.equals(klass)) {
onStop((Stop) message, self, sender);
} else if (MediaGatewayResponse.class.equals(klass)) {
onMediaGatewayResponse((MediaGatewayResponse<?>) message, self, sender);
} else if (MediaGroupStateChanged.class.equals(klass)) {
onMediaGroupStateChanged((MediaGroupStateChanged) message, self, sender);
} else if (StartRecording.class.equals(klass)) {
onStartRecording((StartRecording) message, self, sender);
} else if(EndpointStateChanged.class.equals(klass)) {
onEndpointStateChanged((EndpointStateChanged) message, self, sender);
} else if (MediaResourceBrokerResponse.class.equals(klass)) {
onMediaResourceBrokerResponse((MediaResourceBrokerResponse<?>) message, self, sender);
} else if (MediaGroupResponse.class.equals(klass)) {
onMediaGroupResponse((MediaGroupResponse)message);
}
}
private void onMediaGroupResponse(MediaGroupResponse message) throws TransitionNotFoundException, TransitionFailedException, TransitionRollbackException {
if (logger.isInfoEnabled()) {
logger.info("Received MgcpGroupResponse: "+message.toString());
}
if (recording && stoppingStatePending) {
recording = Boolean.FALSE;
stoppingStatePending = false;
fsm.transition(message, stopping);
}
}
private void onMediaResourceBrokerResponse(MediaResourceBrokerResponse<?> message, ActorRef self, ActorRef sender) throws Exception {
this.mediaGateway = (ActorRef) message.get();
fsm.transition(message, acquiringMediaSession);
}
private void onObserve(Observe message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
synchronized (this.observers) {
this.observers.add(observer);
observer.tell(new Observing(self), self);
}
}
}
private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
this.observers.remove(observer);
}
}
private void onCreateMediaSession(CreateMediaSession message, ActorRef self, ActorRef sender) throws Exception {
if (is(uninitialized)) {
this.bridge = sender;
this.fsm.transition(message, getMediaGatewayFromMRB);
}
}
private void onJoinCall(JoinCall message, ActorRef self, ActorRef sender) {
// Tell call to join bridge by passing reference to the media mixer
final JoinBridge join = new JoinBridge(this.endpoint, message.getConnectionMode());
message.getCall().tell(join, sender);
}
private void onStop(Stop message, ActorRef self, ActorRef sender) throws Exception {
if (is(acquiringMediaSession) || is(acquiringEndpoint)) {
this.fsm.transition(message, inactive);
} else if (is(creatingMediaGroup) || is(active)) {
this.fsm.transition(message, stopping);
}
}
private void onMediaGatewayResponse(MediaGatewayResponse<?> message, ActorRef self, ActorRef sender) throws Exception {
// XXX Check if message successful
if (is(acquiringMediaSession)) {
this.mediaSession = (MediaSession) message.get();
this.fsm.transition(message, acquiringEndpoint);
} else if (is(acquiringEndpoint)) {
this.endpoint = (ActorRef) message.get();
this.endpoint.tell(new Observe(self), self);
this.fsm.transition(message, creatingMediaGroup);
}
}
private void onMediaGroupStateChanged(MediaGroupStateChanged message, ActorRef self, ActorRef sender) throws Exception {
switch (message.state()) {
case ACTIVE:
if (is(creatingMediaGroup)) {
fsm.transition(message, active);
}
break;
case INACTIVE:
if (is(creatingMediaGroup)) {
this.fail = Boolean.TRUE;
fsm.transition(message, failed);
} else if (is(stopping)) {
// Stop media group actor
this.mediaGroup.tell(new StopObserving(self), self);
context().stop(mediaGroup);
this.mediaGroup = null;
// Save record info in the database
if (recordStarted != null) {
saveRecording();
recordStarted = null;
recordingRequest = null;
}
// Move to next state
if (this.mediaGroup == null && this.endpoint == null) {
this.fsm.transition(message, fail ? failed : inactive);
}
}
break;
default:
break;
}
}
private void onEndpointStateChanged(EndpointStateChanged message, ActorRef self, ActorRef sender) throws Exception {
if (is(stopping)) {
if (sender.equals(this.endpoint) && (EndpointState.DESTROYED.equals(message.getState()) || EndpointState.FAILED.equals(message.getState()))) {
if(EndpointState.FAILED.equals(message.getState()))
logger.error("Could not destroy endpoint on media server. corresponding actor path is: " + this.endpoint.path());
this.endpoint.tell(new StopObserving(self), self);
context().stop(endpoint);
endpoint = null;
if(this.mediaGroup == null && this.endpoint == null) {
this.fsm.transition(message, inactive);
}
}
}
}
private void onStartRecording(StartRecording message, ActorRef self, ActorRef sender) {
if (is(active) && !recording) {
if(logger.isInfoEnabled()) {
logger.info("Start recording bridged call");
}
//14400 = 4hrs to match the max call duration
//By setting timeout to 4hrs, we disable Speech Detection for Dial Record scenario
int maxLength = 14400;
int timeout = 14400;
this.recording = Boolean.TRUE;
this.recordStarted = DateTime.now();
this.recordingRequest = message;
// Tell media group to start recording
Record record = new Record(message.getRecordingUri(), timeout, maxLength, null, MediaAttributes.MediaType.AUDIO_ONLY);
this.mediaGroup.tell(record, self);
}
}
/*
* Actions
*/
private abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
private final class GetMediaGatewayFromMRB extends AbstractAction {
public GetMediaGatewayFromMRB(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mrb.tell(new GetMediaGateway(callSid), self());
}
}
private final class AcquiringMediaSession extends AbstractAction {
public AcquiringMediaSession(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mediaGateway.tell(new org.restcomm.connect.mgcp.CreateMediaSession(), super.source);
}
}
private final class AcquiringEndpoint extends AbstractAction {
public AcquiringEndpoint(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final CreateConferenceEndpoint createEndpoint = new CreateConferenceEndpoint(mediaSession);
mediaGateway.tell(createEndpoint, super.source);
}
}
private final class CreatingMediaGroup extends AbstractAction {
public CreatingMediaGroup(ActorRef source) {
super(source);
}
private ActorRef createMediaGroup(final Object message) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new MgcpMediaGroup(mediaGateway, mediaSession, endpoint);
}
});
return getContext().actorOf(props);
}
@Override
public void execute(Object message) throws Exception {
mediaGroup = createMediaGroup(message);
mediaGroup.tell(new Observe(super.source), super.source);
mediaGroup.tell(new StartMediaGroup(), super.source);
}
}
private final class Active extends AbstractAction {
public Active(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
broadcast(new MediaServerControllerStateChanged(MediaServerControllerState.ACTIVE));
}
}
private final class Stopping extends AbstractAction {
public Stopping(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
// Stop Media Group
// Note: Recording will be added to DB after getting response from MG
if (recording) {
mediaGroup.tell(new Stop(), super.source);
stoppingStatePending = true;
} else {
// Destroy Media Group
mediaGroup.tell(new StopMediaGroup(), super.source);
// Destroy Bridge Endpoint and its connections
endpoint.tell(new DestroyEndpoint(), super.source);
}
}
}
@Deprecated
private final class DestroyingMediaGroup extends AbstractAction {
public DestroyingMediaGroup(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
// Stop Media Group
// Note: Recording will be added to DB after getting response from MG
if (recording) {
mediaGroup.tell(new Stop(), super.source);
recording = Boolean.FALSE;
} else {
// Destroy Media Group
mediaGroup.tell(new StopMediaGroup(), super.source);
}
}
}
private abstract class FinalState extends AbstractAction {
private final MediaServerControllerState state;
public FinalState(ActorRef source, final MediaServerControllerState state) {
super(source);
this.state = state;
}
@Override
public void execute(Object message) throws Exception {
// Cleanup resources
if (endpoint != null) {
mediaGateway.tell(new DestroyEndpoint(endpoint), super.source);
endpoint = null;
}
// Notify observers the controller has stopped
broadcast(new MediaServerControllerStateChanged(state));
// Clean observers
observers.clear();
// Terminate actor
getContext().stop(super.source);
}
}
private final class Inactive extends FinalState {
public Inactive(final ActorRef source) {
super(source, MediaServerControllerState.INACTIVE);
}
}
private final class Failed extends FinalState {
public Failed(final ActorRef source) {
super(source, MediaServerControllerState.FAILED);
}
}
@Override
public void postStop() {
this.mediaSession = null;
this.observers.clear();
super.postStop();
}
}
| 23,437 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MmsControllerFactory.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.mms/src/main/java/org/restcomm/connect/mscontrol/mms/MmsControllerFactory.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.mscontrol.mms;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActorFactory;
import org.apache.log4j.Logger;
import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory;
/**
* Provides controllers for Mobicents Media Server.
*
* @author Henrique Rosa ([email protected])
*
*/
public class MmsControllerFactory implements MediaServerControllerFactory {
private static Logger logger = Logger.getLogger(MmsControllerFactory.class);
private final CallControllerFactory callControllerFactory;
private final ConferenceControllerFactory conferenceControllerFactory;
private final BridgeControllerFactory bridgeControllerFactory;
private final ActorRef mrb;
public MmsControllerFactory(ActorRef mrb) {
super();
this.callControllerFactory = new CallControllerFactory();
this.conferenceControllerFactory = new ConferenceControllerFactory();
this.bridgeControllerFactory = new BridgeControllerFactory();
this.mrb = mrb;
}
@Override
public Props provideCallControllerProps() {
return new Props(this.callControllerFactory);
}
@Override
public Props provideConferenceControllerProps() {
return new Props(this.conferenceControllerFactory);
}
@Override
public Props provideBridgeControllerProps() {
return new Props(this.bridgeControllerFactory);
}
private final class CallControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = -4649683839304615853L;
@Override
public Actor create() throws Exception {
return new MmsCallController(mrb);
}
}
private final class ConferenceControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = -919317656354678281L;
@Override
public Actor create() throws Exception {
//return new MmsConferenceController(mediaGateways, configuration);
return new MmsConferenceController(mrb);
}
}
private final class BridgeControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = 8999152285760508857L;
@Override
public Actor create() throws Exception {
return new MmsBridgeController(mrb);
}
}
}
| 3,360 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MmsCallController.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.mms/src/main/java/org/restcomm/connect/mscontrol/mms/MmsCallController.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.mscontrol.mms;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
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 org.apache.commons.configuration.Configuration;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.dao.Sid;
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 org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.entities.MediaAttributes;
import org.restcomm.connect.mgcp.CloseConnection;
import org.restcomm.connect.mgcp.CloseLink;
import org.restcomm.connect.mgcp.ConnectionStateChanged;
import org.restcomm.connect.mgcp.CreateBridgeEndpoint;
import org.restcomm.connect.mgcp.CreateConnection;
import org.restcomm.connect.mgcp.CreateLink;
import org.restcomm.connect.mgcp.DestroyEndpoint;
import org.restcomm.connect.mgcp.DestroyLink;
import org.restcomm.connect.mgcp.EndpointState;
import org.restcomm.connect.mgcp.EndpointStateChanged;
import org.restcomm.connect.mgcp.GetMediaGatewayInfo;
import org.restcomm.connect.mgcp.InitializeConnection;
import org.restcomm.connect.mgcp.InitializeLink;
import org.restcomm.connect.mgcp.LinkStateChanged;
import org.restcomm.connect.mgcp.MediaGatewayInfo;
import org.restcomm.connect.mgcp.MediaGatewayResponse;
import org.restcomm.connect.mgcp.MediaResourceBrokerResponse;
import org.restcomm.connect.mgcp.MediaSession;
import org.restcomm.connect.mgcp.OpenConnection;
import org.restcomm.connect.mgcp.OpenLink;
import org.restcomm.connect.mgcp.UpdateConnection;
import org.restcomm.connect.mgcp.UpdateLink;
import org.restcomm.connect.mrb.api.GetMediaGateway;
import org.restcomm.connect.mscontrol.api.MediaServerController;
import org.restcomm.connect.mscontrol.api.messages.CloseMediaSession;
import org.restcomm.connect.mscontrol.api.messages.Collect;
import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession;
import org.restcomm.connect.mscontrol.api.messages.JoinBridge;
import org.restcomm.connect.mscontrol.api.messages.JoinComplete;
import org.restcomm.connect.mscontrol.api.messages.JoinConference;
import org.restcomm.connect.mscontrol.api.messages.Leave;
import org.restcomm.connect.mscontrol.api.messages.Left;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupStateChanged;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged.MediaServerControllerState;
import org.restcomm.connect.mscontrol.api.messages.MediaSessionInfo;
import org.restcomm.connect.mscontrol.api.messages.Mute;
import org.restcomm.connect.mscontrol.api.messages.Play;
import org.restcomm.connect.mscontrol.api.messages.Record;
import org.restcomm.connect.mscontrol.api.messages.StartMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.Unmute;
import org.restcomm.connect.mscontrol.api.messages.UpdateMediaSession;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Henrique Rosa ([email protected])
* @author [email protected] (Maria Farooq)
*
*/
public class MmsCallController extends MediaServerController {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Finite State Machine
private final FiniteStateMachine fsm;
private final State uninitialized;
private final State acquiringMediaGateway;
private final State acquiringMediaGatewayInfo;
private final State acquiringMediaSession;
private final State acquiringBridge;
private final State creatingMediaGroup;
private final State acquiringRemoteConnection;
private final State initializingRemoteConnection;
private final State openingRemoteConnection;
private final State updatingRemoteConnection;
private final State pending;
private final State active;
private final State muting;
private final State unmuting;
private final State acquiringInternalLink;
private final State initializingInternalLink;
private final State openingInternalLink;
private final State updatingInternalLink;
private final State closingInternalLink;
private final State closingRemoteConnection;
private final State stopping;
private final State failed;
private final State inactive;
// Call runtime stuff
private ActorRef call;
private Sid callId;
private String localSdp;
private String remoteSdp;
private String connectionMode;
private boolean callOutbound;
private boolean webrtc;
// CallMediaGroup
private ActorRef mediaGroup;
private ActorRef bridge;
private ActorRef outboundCallBridgeEndpoint;
// MGCP runtime stuff
//private final ActorRef mediaGateway;
// TODO rename following variable to 'mediaGateway'
private ActorRef mediaGateway;
private final ActorRef mrb;
private MediaGatewayInfo gatewayInfo;
private MediaSession session;
private ActorRef bridgeEndpoint;
private ActorRef remoteConn;
private ActorRef internalLink;
private ActorRef internalLinkEndpoint;
private ConnectionMode internalLinkMode;
// Call Recording
private Sid accountId;
private Sid recordingSid;
private URI recordingUri;
private Boolean recording = false;
private DateTime recordStarted;
private DaoManager daoManager;
private Boolean collecting = false;
// Runtime Setting
private Configuration runtimeSettings;
// Observer pattern
private final List<ActorRef> observers;
private ConnectionIdentifier connectionIdentifier;
//public MmsCallController(final List<ActorRef> mediaGateways, final Configuration configuration) {
public MmsCallController(final ActorRef mrb) {
super();
final ActorRef source = self();
// Initialize the states for the FSM.
this.uninitialized = new State("uninitialized", null, null);
this.acquiringMediaGateway = new State("acquiring media gateway from mrb", new AcquiringMediaGateway(source), null);
this.acquiringMediaGatewayInfo = new State("acquiring media gateway info", new AcquiringMediaGatewayInfo(source), null);
this.acquiringMediaSession = new State("acquiring media session", new AcquiringMediaSession(source), null);
this.acquiringBridge = new State("acquiring media bridge", new AcquiringBridge(source), null);
this.creatingMediaGroup = new State("creating media group", new CreatingMediaGroup(source), null);
this.acquiringRemoteConnection = new State("acquiring connection", new AcquiringRemoteConnection(source), null);
this.initializingRemoteConnection = new State("initializing connection", new InitializingRemoteConnection(source), null);
this.openingRemoteConnection = new State("opening connection", new OpeningRemoteConnection(source), null);
this.updatingRemoteConnection = new State("updating connection", new UpdatingRemoteConnection(source), null);
this.pending = new State("pending", new Pending(source), null);
this.active = new State("active", new Active(source), null);
this.muting = new State("muting", new Muting(source), null);
this.unmuting = new State("unmuting", new Unmuting(source), null);
this.acquiringInternalLink = new State("acquiring link", new AcquiringInternalLink(source), null);
this.initializingInternalLink = new State("initializing link", new InitializingInternalLink(source), null);
this.openingInternalLink = new State("opening link", new OpeningInternalLink(source), null);
this.updatingInternalLink = new State("updating link", new UpdatingInternalLink(source), null);
this.closingInternalLink = new State("closing link", new EnterClosingInternalLink(source), new ExitClosingInternalLink(
source));
this.closingRemoteConnection = new State("closing connection", new ClosingRemoteConnection(source), null);
this.stopping = new State("stopping", new Stopping(source));
this.inactive = new State("inactive", new Inactive(source));
this.failed = new State("failed", new Failed(source));
// Transitions for the FSM.
final Set<Transition> transitions = new HashSet<Transition>();
transitions.add(new Transition(this.uninitialized, this.acquiringMediaGateway));
transitions.add(new Transition(this.acquiringMediaGateway, this.acquiringMediaGatewayInfo));
transitions.add(new Transition(this.uninitialized, this.closingRemoteConnection));
transitions.add(new Transition(this.acquiringMediaGatewayInfo, this.acquiringMediaSession));
transitions.add(new Transition(this.acquiringMediaSession, this.acquiringBridge));
transitions.add(new Transition(this.acquiringMediaSession, this.stopping));
transitions.add(new Transition(this.acquiringBridge, this.creatingMediaGroup));
transitions.add(new Transition(this.acquiringBridge, this.stopping));
transitions.add(new Transition(this.creatingMediaGroup, this.acquiringRemoteConnection));
transitions.add(new Transition(this.creatingMediaGroup, this.stopping));
transitions.add(new Transition(this.creatingMediaGroup, this.failed));
transitions.add(new Transition(this.acquiringRemoteConnection, this.initializingRemoteConnection));
transitions.add(new Transition(this.initializingRemoteConnection, this.openingRemoteConnection));
transitions.add(new Transition(this.openingRemoteConnection, this.active));
transitions.add(new Transition(this.openingRemoteConnection, this.failed));
transitions.add(new Transition(this.openingRemoteConnection, this.pending));
transitions.add(new Transition(this.active, this.muting));
transitions.add(new Transition(this.active, this.unmuting));
transitions.add(new Transition(this.active, this.updatingRemoteConnection));
transitions.add(new Transition(this.active, this.stopping));
transitions.add(new Transition(this.active, this.acquiringInternalLink));
transitions.add(new Transition(this.active, this.closingInternalLink));
transitions.add(new Transition(this.active, this.creatingMediaGroup));
transitions.add(new Transition(this.pending, this.active));
transitions.add(new Transition(this.pending, this.failed));
transitions.add(new Transition(this.pending, this.updatingRemoteConnection));
transitions.add(new Transition(this.pending, this.stopping));
transitions.add(new Transition(this.muting, this.active));
transitions.add(new Transition(this.muting, this.closingRemoteConnection));
transitions.add(new Transition(this.unmuting, this.active));
transitions.add(new Transition(this.unmuting, this.closingRemoteConnection));
transitions.add(new Transition(this.updatingRemoteConnection, this.active));
transitions.add(new Transition(this.updatingRemoteConnection, this.stopping));
transitions.add(new Transition(this.updatingRemoteConnection, this.failed));
transitions.add(new Transition(this.closingRemoteConnection, this.inactive));
transitions.add(new Transition(this.closingRemoteConnection, this.closingInternalLink));
transitions.add(new Transition(this.acquiringInternalLink, this.closingRemoteConnection));
transitions.add(new Transition(this.acquiringInternalLink, this.initializingInternalLink));
transitions.add(new Transition(this.initializingInternalLink, this.closingRemoteConnection));
transitions.add(new Transition(this.initializingInternalLink, this.openingInternalLink));
transitions.add(new Transition(this.openingInternalLink, this.stopping));
transitions.add(new Transition(this.openingInternalLink, this.updatingInternalLink));
transitions.add(new Transition(this.updatingInternalLink, this.stopping));
transitions.add(new Transition(this.updatingInternalLink, this.closingInternalLink));
transitions.add(new Transition(this.updatingInternalLink, this.active));
transitions.add(new Transition(this.closingInternalLink, this.closingRemoteConnection));
transitions.add(new Transition(this.closingInternalLink, this.active));
transitions.add(new Transition(this.closingInternalLink, this.inactive));
transitions.add(new Transition(this.stopping, this.inactive));
transitions.add(new Transition(this.stopping, this.failed));
// Initialize the FSM.
this.fsm = new FiniteStateMachine(uninitialized, transitions);
// MGCP runtime stuff
this.mrb = mrb;
// Call runtime stuff
this.localSdp = "";
this.remoteSdp = "";
this.callOutbound = false;
this.connectionMode = "inactive";
this.webrtc = false;
// Observers
this.observers = new ArrayList<ActorRef>(1);
}
/**
* Checks whether the actor is currently in a certain state.
*
* @param state The state to be checked
* @return Returns true if the actor is currently in the state. Returns false otherwise.
*/
private boolean is(State state) {
return this.fsm.state().equals(state);
}
private void broadcast(final Object message) {
if (!this.observers.isEmpty()) {
final ActorRef self = self();
for (ActorRef observer : observers) {
observer.tell(message, self);
}
}
}
private ActorRef createMediaGroup(final Object message) {
// No need to create new media group if current one is active
if (this.mediaGroup != null && !this.mediaGroup.isTerminated()) {
return this.mediaGroup;
}
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new MgcpMediaGroup(mediaGateway, session, bridgeEndpoint);
}
});
return getContext().actorOf(props);
}
private void startRecordingCall() throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Start recording call");
}
String finishOnKey = "1234567890*#";
int maxLength = 3600;
int timeout = 5;
this.recordStarted = DateTime.now();
this.recording = true;
// Tell media group to start recording
Record record = new Record(recordingUri, timeout, maxLength, finishOnKey, MediaAttributes.MediaType.AUDIO_ONLY);
this.mediaGroup.tell(record, self());
}
private void stopCollect(Stop message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Stop DTMF collect");
}
if (this.mediaGroup != null) {
// Tell media group to stop recording
mediaGroup.tell(message, null);
}
collecting = false;
}
private void stopRecordingCall(Stop message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Stop recording call");
}
if (this.mediaGroup != null) {
// Tell media group to stop recording
mediaGroup.tell(message, null);
}
}
/*
* EVENTS
*/
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
final State state = fsm.state();
if(logger.isInfoEnabled()) {
logger.info("********** MmsCallController "+ self.path()+" Current State: \"" + state.toString());
logger.info("********** MmsCallController "+ self.path()+" Processing Message: \"" + klass.getName() + " sender : " + sender.path());
}
if (Observe.class.equals(klass)) {
onObserve((Observe) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
onStopObserving((StopObserving) message, self, sender);
} else if (CreateMediaSession.class.equals(klass)) {
onCreateMediaSession((CreateMediaSession) message, self, sender);
} else if (CloseMediaSession.class.equals(klass)) {
onCloseMediaSession((CloseMediaSession) message, self, sender);
} else if (UpdateMediaSession.class.equals(klass)) {
onUpdateMediaSession((UpdateMediaSession) message, self, sender);
} else if (MediaGatewayResponse.class.equals(klass)) {
onMediaGatewayResponse((MediaGatewayResponse<?>) message, self, sender);
} else if (ConnectionStateChanged.class.equals(klass)) {
onConnectionStateChanged((ConnectionStateChanged) message, self, sender);
} else if (LinkStateChanged.class.equals(klass)) {
onLinkStateChanged((LinkStateChanged) message, self, sender);
} else if (Leave.class.equals(klass)) {
onLeave((Leave) message, self, sender);
} else if (Mute.class.equals(klass)) {
onMute((Mute) message, self, sender);
} else if (Unmute.class.equals(klass)) {
onUnmute((Unmute) message, self, sender);
} else if (Stop.class.equals(klass)) {
onStop((Stop) message, self, sender);
} else if (StopMediaGroup.class.equals(klass)) {
onStopMediaGroup((StopMediaGroup) message, self, sender);
} else if (JoinConference.class.equals(klass)) {
onJoinConference((JoinConference) message, self, sender);
} else if (JoinBridge.class.equals(klass)) {
onJoinBridge((JoinBridge) message, self, sender);
} else if (Leave.class.equals(klass)) {
onLeave((Leave) message, self, sender);
} else if (MediaGroupStateChanged.class.equals(klass)) {
onMediaGroupStateChanged((MediaGroupStateChanged) message, self, sender);
} else if (Record.class.equals(klass)) {
onRecord((Record) message, self, sender);
} else if (Play.class.equals(klass)) {
onPlay((Play) message, self, sender);
} else if (Collect.class.equals(klass)) {
onCollect((Collect) message, self, sender);
} else if (EndpointStateChanged.class.equals(klass)) {
onEndpointStateChanged((EndpointStateChanged) message, self, sender);
} else if (MediaResourceBrokerResponse.class.equals(klass)) {
onMediaResourceBrokerResponse((MediaResourceBrokerResponse<?>) message, self, sender);
}
}
private void onMediaResourceBrokerResponse(MediaResourceBrokerResponse<?> message, ActorRef self, ActorRef sender) throws Exception {
this.mediaGateway = (ActorRef) message.get();
fsm.transition(message, acquiringMediaGatewayInfo);
}
private void onObserve(Observe message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
synchronized (this.observers) {
this.observers.add(observer);
observer.tell(new Observing(self), self);
}
}
}
private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
this.observers.remove(observer);
}
}
private void onCreateMediaSession(CreateMediaSession message, ActorRef self, ActorRef sender) throws Exception {
this.call = sender;
this.connectionMode = message.getConnectionMode();
this.callOutbound = message.isOutbound();
this.remoteSdp = message.getSessionDescription();
this.webrtc = message.isWebrtc();
this.callId = message.callSid();
fsm.transition(message, acquiringMediaGateway);
}
private void onCloseMediaSession (CloseMediaSession message, ActorRef self, ActorRef sender) throws Exception {
if (is(pending) || is(updatingRemoteConnection) || is(active) || is(acquiringInternalLink) || is(updatingInternalLink)
|| is(creatingMediaGroup) || is(acquiringBridge) || is(acquiringMediaSession)) {
fsm.transition(message, stopping);
}
}
private void onUpdateMediaSession(UpdateMediaSession message, ActorRef self, ActorRef sender) throws Exception {
this.remoteSdp = message.getSessionDescription();
this.fsm.transition(message, updatingRemoteConnection);
}
private void onMediaGatewayResponse(MediaGatewayResponse<?> message, ActorRef self, ActorRef sender) throws Exception {
if (is(acquiringMediaGatewayInfo)) {
fsm.transition(message, acquiringMediaSession);
} else if (is(acquiringMediaSession)) {
fsm.transition(message, acquiringBridge);
} else if (is(acquiringBridge)) {
this.bridgeEndpoint = (ActorRef) message.get();
this.bridgeEndpoint.tell(new Observe(self), self);
fsm.transition(message, creatingMediaGroup);
} else if (is(acquiringRemoteConnection)) {
fsm.transition(message, initializingRemoteConnection);
} else if (is(acquiringInternalLink)) {
fsm.transition(message, initializingInternalLink);
}
}
private void onConnectionStateChanged(ConnectionStateChanged message, ActorRef self, ActorRef sender) throws Exception {
switch (message.state()) {
case CLOSED:
if (is(initializingRemoteConnection)) {
fsm.transition(message, openingRemoteConnection);
} else if (is(openingRemoteConnection)) {
fsm.transition(message, failed);
} else if (is(muting) || is(unmuting)) {
fsm.transition(message, closingRemoteConnection);
} else if (is(closingRemoteConnection)) {
remoteConn = null;
if (this.internalLink != null) {
fsm.transition(message, closingInternalLink);
} else {
fsm.transition(message, inactive);
}
} else if (is(updatingRemoteConnection)) {
fsm.transition(message, failed);
}
break;
case HALF_OPEN:
fsm.transition(message, pending);
break;
case OPEN:
fsm.transition(message, active);
break;
default:
break;
}
}
private void onLinkStateChanged(LinkStateChanged message, ActorRef self, ActorRef sender) throws Exception {
switch (message.state()) {
case CLOSED:
if (is(initializingInternalLink)) {
fsm.transition(message, openingInternalLink);
} else if (is(openingInternalLink)) {
fsm.transition(message, stopping);
} else if (is(closingInternalLink)) {
if (remoteConn != null) {
fsm.transition(message, active);
} else {
fsm.transition(message, inactive);
}
}
break;
case OPEN:
if (is(openingInternalLink)) {
fsm.transition(message, updatingInternalLink);
} else if (is(updatingInternalLink)) {
fsm.transition(message, active);
}
break;
default:
break;
}
}
private void onMute(Mute message, ActorRef self, ActorRef sender) throws Exception {
fsm.transition(message, muting);
}
private void onUnmute(Unmute message, ActorRef self, ActorRef sender) throws Exception {
fsm.transition(message, unmuting);
}
private void onStop(Stop message, ActorRef self, ActorRef sender) throws Exception {
if (this.recording) {
stopRecordingCall(message);
} else if (this.collecting) {
stopCollect(message);
}
}
private void onStopMediaGroup(StopMediaGroup message, ActorRef self, ActorRef sender) throws Exception {
if (is(active) && this.mediaGroup != null) {
this.mediaGroup.tell(new Stop(), sender);
}
}
private void onLeave(Leave message, ActorRef self, ActorRef sender) throws Exception {
if ((is(active) && internalLinkEndpoint != null) || is(updatingInternalLink)) {
fsm.transition(message, closingInternalLink);
}
}
private void onJoinBridge(JoinBridge message, ActorRef self, ActorRef sender) throws Exception {
// Get bridge endpoint data
this.bridge = sender;
this.internalLinkEndpoint = (ActorRef) message.getEndpoint();
this.internalLinkMode = message.getConnectionMode();
// Start join operation
this.fsm.transition(message, acquiringInternalLink);
}
private void onJoinConference(JoinConference message, ActorRef self, ActorRef sender) throws Exception {
// Ask the remote media session controller for the bridge endpoint.
//Why ??
this.bridge = sender;
//internalLinkEndpoint is basically conference endpoint.
this.internalLinkEndpoint = (ActorRef) message.getEndpoint();
this.internalLinkMode = message.getConnectionMode();
// Start join operation
this.fsm.transition(message, acquiringInternalLink);
}
private void onMediaGroupStateChanged(MediaGroupStateChanged message, ActorRef self, ActorRef sender) throws Exception {
switch (message.state()) {
case ACTIVE:
if (is(creatingMediaGroup)) {
fsm.transition(message, acquiringRemoteConnection);
}
break;
case INACTIVE:
if (is(creatingMediaGroup)) {
fsm.transition(message, failed);
} else if(is(stopping)) {
this.mediaGroup.tell(new StopObserving(self), self);
context().stop(mediaGroup);
this.mediaGroup = null;
if(this.mediaGroup == null && this.bridgeEndpoint == null) {
fsm.transition(message, inactive);
}
}
break;
default:
break;
}
}
private void onRecord(Record message, ActorRef self, ActorRef sender) {
if (is(active)) {
this.recording = Boolean.TRUE;
this.recordingUri = message.destination();
// Forward message to media group to handle
this.mediaGroup.tell(message, sender);
}
}
private void onPlay(Play message, ActorRef self, ActorRef sender) {
if (is(active) || is(muting)) {
// Forward message to media group to handle
this.mediaGroup.tell(message, sender);
}
}
private void onCollect(Collect message, ActorRef self, ActorRef sender) {
if (is(active)) {
// Forward message to media group to handle
this.mediaGroup.tell(message, sender);
this.collecting = true;
}
}
private void onEndpointStateChanged(EndpointStateChanged message, ActorRef self, ActorRef sender) throws Exception {
if (is(stopping)) {
if (sender.equals(this.bridgeEndpoint) && (EndpointState.DESTROYED.equals(message.getState()) || EndpointState.FAILED.equals(message.getState()))) {
if(EndpointState.FAILED.equals(message.getState()))
logger.error("Could not destroy endpoint on media server. corresponding actor path is: " + this.bridgeEndpoint.path());
this.bridgeEndpoint.tell(new StopObserving(self), self);
context().stop(bridgeEndpoint);
bridgeEndpoint = null;
if(this.mediaGroup == null && this.bridgeEndpoint == null) {
this.fsm.transition(message, inactive);
}
}
}
}
/*
* ACTIONS
*/
private final class AcquiringMediaGateway extends AbstractAction {
public AcquiringMediaGateway(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mrb.tell(new GetMediaGateway(callId), self());
}
}
private final class AcquiringMediaGatewayInfo extends AbstractAction {
public AcquiringMediaGatewayInfo(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mediaGateway.tell(new GetMediaGatewayInfo(), self());
}
}
private final class AcquiringMediaSession extends AbstractAction {
public AcquiringMediaSession(final ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(final Object message) throws Exception {
final MediaGatewayResponse<MediaGatewayInfo> response = (MediaGatewayResponse<MediaGatewayInfo>) message;
gatewayInfo = response.get();
mediaGateway.tell(new org.restcomm.connect.mgcp.CreateMediaSession(), source);
}
}
public final class AcquiringBridge extends AbstractAction {
public AcquiringBridge(final ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(final Object message) throws Exception {
final MediaGatewayResponse<MediaSession> response = (MediaGatewayResponse<MediaSession>) message;
session = response.get();
mediaGateway.tell(new CreateBridgeEndpoint(session), source);
}
}
private final class AcquiringRemoteConnection extends AbstractAction {
public AcquiringRemoteConnection(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mediaGateway.tell(new CreateConnection(session), source);
}
}
private final class InitializingRemoteConnection extends AbstractAction {
public InitializingRemoteConnection(ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(final Object message) throws Exception {
final MediaGatewayResponse<ActorRef> response = (MediaGatewayResponse<ActorRef>) message;
remoteConn = response.get();
remoteConn.tell(new Observe(source), source);
remoteConn.tell(new InitializeConnection(bridgeEndpoint), source);
}
}
private final class OpeningRemoteConnection extends AbstractAction {
public OpeningRemoteConnection(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
OpenConnection open = null;
if (callOutbound) {
open = new OpenConnection(ConnectionMode.SendRecv, webrtc);
} else {
final ConnectionDescriptor descriptor = new ConnectionDescriptor(remoteSdp);
open = new OpenConnection(descriptor, ConnectionMode.SendRecv, webrtc);
}
remoteConn.tell(open, source);
}
}
private final class UpdatingRemoteConnection extends AbstractAction {
public UpdatingRemoteConnection(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final ConnectionDescriptor descriptor = new ConnectionDescriptor(remoteSdp);
final UpdateConnection update = new UpdateConnection(descriptor);
remoteConn.tell(update, source);
}
}
private final class Active extends AbstractAction {
public Active(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if (is(updatingInternalLink)) {
call.tell(new JoinComplete(bridgeEndpoint, session.id(), connectionIdentifier), super.source);
} else if (is(closingInternalLink)) {
call.tell(new Left(), super.source);
} else if (is(openingRemoteConnection) || is(updatingRemoteConnection)) {
ConnectionStateChanged connState = (ConnectionStateChanged) message;
connectionIdentifier = connState.connectionIdentifier();
logger.info("connectionIdentifier: "+connectionIdentifier);
localSdp = connState.descriptor().toString();
MediaSessionInfo mediaSessionInfo = new MediaSessionInfo(gatewayInfo.useNat(), gatewayInfo.externalIP(),
localSdp, remoteSdp);
broadcast(new MediaServerControllerStateChanged(MediaServerControllerState.ACTIVE, mediaSessionInfo));
}
}
}
private final class Pending extends AbstractAction {
public Pending(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
ConnectionStateChanged connState = (ConnectionStateChanged) message;
localSdp = connState.descriptor().toString();
MediaSessionInfo mediaSessionInfo = new MediaSessionInfo(gatewayInfo.useNat(), gatewayInfo.externalIP(), localSdp,
remoteSdp);
broadcast(new MediaServerControllerStateChanged(MediaServerControllerState.PENDING, mediaSessionInfo));
}
}
private final class AcquiringInternalLink extends AbstractAction {
public AcquiringInternalLink(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mediaGateway.tell(new CreateLink(session), source);
}
}
private final class InitializingInternalLink extends AbstractAction {
public InitializingInternalLink(final ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(Object message) throws Exception {
final MediaGatewayResponse<ActorRef> response = (MediaGatewayResponse<ActorRef>) message;
if (self().path().toString().equalsIgnoreCase("akka://RestComm/user/$j")) {
if(logger.isInfoEnabled()) {
logger.info("Initializing Internal Link for the Outbound call");
}
}
if (bridgeEndpoint != null) {
if(logger.isInfoEnabled()) {
logger.info("##################### $$ Bridge for Call " + self().path() + " is terminated: "
+ bridgeEndpoint.isTerminated());
}
if (bridgeEndpoint.isTerminated()) {
// fsm.transition(message, acquiringMediaGatewayInfo);
// return;
if(logger.isInfoEnabled()) {
logger.info("##################### $$ Call :" + self().path() + " bridge is terminated.");
}
// final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS));
// Future<Object> future = (Future<Object>) akka.pattern.Patterns.ask(gateway, new
// CreateBridgeEndpoint(session), expires);
// MediaGatewayResponse<ActorRef> futureResponse = (MediaGatewayResponse<ActorRef>) Await.result(future,
// Duration.create(10, TimeUnit.SECONDS));
// bridge = futureResponse.get();
// if (!bridge.isTerminated() && bridge != null) {
// logger.info("Bridge for call: "+self().path()+" acquired and is not terminated");
// } else {
// logger.info("Bridge endpoint for call: "+self().path()+" is still terminated or null");
// }
}
}
// if (bridge == null || bridge.isTerminated()) {
// System.out.println("##################### $$ Bridge for Call "+self().path()+" is null or terminated: "+bridge.isTerminated());
// }
internalLink = response.get();
internalLink.tell(new Observe(source), source);
internalLink.tell(new InitializeLink(bridgeEndpoint, internalLinkEndpoint), source);
}
}
private final class OpeningInternalLink extends AbstractAction {
public OpeningInternalLink(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
internalLink.tell(new OpenLink(internalLinkMode), source);
}
}
private final class UpdatingInternalLink extends AbstractAction {
public UpdatingInternalLink(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final UpdateLink update = new UpdateLink(ConnectionMode.SendRecv, UpdateLink.Type.PRIMARY);
internalLink.tell(update, source);
}
}
private final class CreatingMediaGroup extends AbstractAction {
public CreatingMediaGroup(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
// Always reuse current media group if active
if (mediaGroup == null) {
mediaGroup = createMediaGroup(message);
// start monitoring state changes in the media group
mediaGroup.tell(new Observe(super.source), super.source);
// start the media group to enable media operations
mediaGroup.tell(new StartMediaGroup(), super.source);
}
}
}
private final class Muting extends AbstractAction {
public Muting(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final UpdateConnection update = new UpdateConnection(ConnectionMode.SendOnly);
remoteConn.tell(update, source);
}
}
private final class Unmuting extends AbstractAction {
public Unmuting(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
final UpdateConnection update = new UpdateConnection(ConnectionMode.SendRecv);
remoteConn.tell(update, source);
}
}
private final class EnterClosingInternalLink extends AbstractAction {
public EnterClosingInternalLink(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
internalLink.tell(new CloseLink(), source);
}
}
private final class ExitClosingInternalLink extends AbstractAction {
public ExitClosingInternalLink(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mediaGateway.tell(new DestroyLink(internalLink), source);
internalLink = null;
internalLinkEndpoint = null;
internalLinkMode = null;
}
}
private class ClosingRemoteConnection extends AbstractAction {
public ClosingRemoteConnection(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
if (remoteConn != null) {
remoteConn.tell(new CloseConnection(), source);
}
}
}
private class Stopping extends AbstractAction {
public Stopping(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
if (mediaGroup != null) {
// Stop the media group
mediaGroup.tell(new StopMediaGroup(), super.source);
}
if (bridgeEndpoint != null) {
// Stop bridge endpoint
bridgeEndpoint.tell(new DestroyEndpoint(), super.source);
}
}
}
private abstract class FinalState extends AbstractAction {
private final MediaServerControllerState state;
public FinalState(ActorRef source, final MediaServerControllerState state) {
super(source);
this.state = state;
}
@Override
public void execute(Object message) throws Exception {
// Notify observers the controller has stopped
broadcast(new MediaServerControllerStateChanged(state));
if (mediaGroup != null) {
// Stop the media group
mediaGroup.tell(new StopMediaGroup(), super.source);
}
if (bridgeEndpoint != null) {
// Stop bridge endpoint
bridgeEndpoint.tell(new DestroyEndpoint(), super.source);
}
}
}
protected void cleanup() {
if(logger.isInfoEnabled()) {
logger.info("De-activating Call Controller");
}
if (mediaGroup != null) {
mediaGroup.tell(new StopObserving(self()), self());
mediaGroup.tell(new StopMediaGroup(), null);
context().stop(mediaGroup);
mediaGroup = null;
}
if (remoteConn != null) {
// mediaGateway.tell(new DestroyConnection(remoteConn), source);
context().stop(remoteConn);
remoteConn = null;
}
if (internalLink != null) {
// mediaGateway.tell(new DestroyLink(internalLink), source);
context().stop(internalLink);
internalLink = null;
}
if (bridgeEndpoint != null) {
if(logger.isInfoEnabled()) {
logger.info("Call Controller: " + self().path() + " about to stop bridge endpoint: " + bridgeEndpoint.path());
}
mediaGateway.tell(new DestroyEndpoint(bridgeEndpoint), self());
context().stop(bridgeEndpoint);
bridgeEndpoint = null;
}
bridge = null;
outboundCallBridgeEndpoint = null;
}
private final class Inactive extends FinalState {
public Inactive(final ActorRef source) {
super(source, MediaServerControllerState.INACTIVE);
}
}
private final class Failed extends FinalState {
public Failed(final ActorRef source){
super(source, MediaServerControllerState.FAILED);
}
}
@Override
public void postStop() {
// Cleanup resources
cleanup();
// Clean observers
observers.clear();
// Terminate actor
getContext().stop(self());
}
}
| 45,426 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MgcpMediaGroup.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.mms/src/main/java/org/restcomm/connect/mscontrol/mms/MgcpMediaGroup.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.mscontrol.mms;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier;
import jain.protocol.ip.mgcp.message.parms.ConnectionMode;
import jain.protocol.ip.mgcp.pkg.MgcpEvent;
import org.apache.commons.configuration.Configuration;
import org.mobicents.protocols.mgcp.jain.pkg.AUMgcpEvent;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
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 org.restcomm.connect.mgcp.AsrSignal;
import org.restcomm.connect.mgcp.CreateIvrEndpoint;
import org.restcomm.connect.mgcp.CreateLink;
import org.restcomm.connect.mgcp.DestroyEndpoint;
import org.restcomm.connect.mgcp.DestroyLink;
import org.restcomm.connect.mgcp.EndpointState;
import org.restcomm.connect.mgcp.EndpointStateChanged;
import org.restcomm.connect.mgcp.InitializeLink;
import org.restcomm.connect.mgcp.IvrEndpointResponse;
import org.restcomm.connect.mgcp.LinkStateChanged;
import org.restcomm.connect.mgcp.MediaGatewayResponse;
import org.restcomm.connect.mgcp.MediaSession;
import org.restcomm.connect.mgcp.OpenLink;
import org.restcomm.connect.mgcp.PlayCollect;
import org.restcomm.connect.mgcp.PlayRecord;
import org.restcomm.connect.mgcp.StopEndpoint;
import org.restcomm.connect.mgcp.UpdateLink;
import org.restcomm.connect.mscontrol.api.MediaGroup;
import org.restcomm.connect.mscontrol.api.messages.Collect;
import org.restcomm.connect.mscontrol.api.messages.CollectedResult;
import org.restcomm.connect.mscontrol.api.messages.Join;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupStateChanged;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupStatus;
import org.restcomm.connect.mscontrol.api.messages.Play;
import org.restcomm.connect.mscontrol.api.messages.Record;
import org.restcomm.connect.mscontrol.api.messages.StartMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (Maria Farooq)
*/
public class MgcpMediaGroup extends MediaGroup {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Finite state machine stuff.
protected final State uninitialized;
protected final State active;
protected final State inactive;
// Special intermediate states.
protected final State acquiringIvr;
protected final State acquiringLink;
protected final State initializingLink;
protected final State openingLink;
protected final State updatingLink;
protected final State deactivating;
// Join Outboundcall Bridge endpoint to the IVR
protected final State acquiringInternalLink;
protected final State initializingInternalLink;
protected final State openingInternalLink;
protected final State updatingInternalLink;
// FSM.
protected FiniteStateMachine fsm;
// The user specific configuration.
Configuration configuration = null;
// MGCP runtime stuff.
protected final ActorRef gateway;
protected final ActorRef endpoint;
protected final MediaSession session;
protected ActorRef link;
protected final String ivrEndpointName;
protected ActorRef ivr;
protected boolean ivrInUse;
protected MgcpEvent lastEvent;
// Runtime stuff.
protected final List<ActorRef> observers;
protected ActorRef originator;
protected ActorRef internalLinkEndpoint;
protected ActorRef internalLink;
protected ConnectionMode internalLinkMode;
protected ConnectionIdentifier ivrConnectionIdentifier;
protected final String primaryEndpointId;
protected final String secondaryEndpointId;
private boolean recording;
public MgcpMediaGroup(final ActorRef gateway, final MediaSession session, final ActorRef endpoint) {
this(gateway, session, endpoint, null, null);
}
public MgcpMediaGroup(final ActorRef gateway, final MediaSession session, final ActorRef endpoint, final String ivrEndpointName) {
this(gateway, session, endpoint, ivrEndpointName, null);
}
public MgcpMediaGroup(final ActorRef gateway, final MediaSession session, final ActorRef endpoint, final String ivrEndpointName, final ConnectionIdentifier ivrConnectionIdentifier) {
this(gateway, session, endpoint, ivrEndpointName, ivrConnectionIdentifier, null, null);
}
public MgcpMediaGroup(final ActorRef gateway, final MediaSession session, final ActorRef endpoint, final String ivrEndpointName, final ConnectionIdentifier ivrConnectionIdentifier, final String primaryEndpointId, final String secondaryEndpointId) {
super();
final ActorRef source = self();
if(logger.isDebugEnabled())
logger.debug("MgcpMediaGroup: "+ source.path() + " gateway: "+gateway
+ " session: "+session + " endpoint: "+endpoint + " ivrEndpointName: "
+ ivrEndpointName + " ivrConnectionIdentifier: "+ivrConnectionIdentifier
+ " primaryEndpointId: "+primaryEndpointId+" secondaryEndpointId: "
+ secondaryEndpointId);
// Initialize the states for the FSM.
uninitialized = new State("uninitialized", null, null);
active = new State("active", new Active(source), null);
inactive = new State("inactive", new Inactive(source), null);
acquiringIvr = new State("acquiring ivr", new AcquiringIvr(source), null);
acquiringLink = new State("acquiring link", new AcquiringLink(source), null);
initializingLink = new State("initializing link", new InitializingLink(source), null);
openingLink = new State("opening link", new OpeningLink(source), null);
updatingLink = new State("updating link", new UpdatingLink(source), null);
deactivating = new State("deactivating", new Deactivating(source), null);
acquiringInternalLink = new State("acquiring internal link", new AcquiringInternalLink(source), null);
initializingInternalLink = new State("initializing internal link", new InitializingInternalLink(source), null);
openingInternalLink = new State("opening internal link", new OpeningInternalLink(source), null);
updatingInternalLink = new State("updating internal link", new UpdatingInternalLink(source), null);
// Initialize the transitions for the FSM.
final Set<Transition> transitions = new HashSet<Transition>();
transitions.add(new Transition(uninitialized, acquiringIvr));
transitions.add(new Transition(acquiringIvr, inactive));
transitions.add(new Transition(acquiringIvr, acquiringLink));
transitions.add(new Transition(acquiringLink, inactive));
transitions.add(new Transition(acquiringLink, initializingLink));
transitions.add(new Transition(initializingLink, inactive));
transitions.add(new Transition(initializingLink, openingLink));
transitions.add(new Transition(openingLink, inactive));
transitions.add(new Transition(openingLink, deactivating));
transitions.add(new Transition(openingLink, updatingLink));
transitions.add(new Transition(updatingLink, active));
transitions.add(new Transition(updatingLink, inactive));
transitions.add(new Transition(updatingLink, deactivating));
transitions.add(new Transition(active, deactivating));
transitions.add(new Transition(deactivating, inactive));
transitions.add(new Transition(active, acquiringIvr));
// Join Outbound call Bridge endpoint to IVR endpoint
transitions.add(new Transition(active, acquiringInternalLink));
transitions.add(new Transition(acquiringInternalLink, initializingInternalLink));
transitions.add(new Transition(initializingInternalLink, openingInternalLink));
transitions.add(new Transition(openingInternalLink, updatingInternalLink));
transitions.add(new Transition(updatingInternalLink, active));
// Initialize the FSM.
this.fsm = new FiniteStateMachine(uninitialized, transitions);
// Initialize the MGCP state.
this.gateway = gateway;
this.session = session;
this.endpoint = endpoint;
this.ivrInUse = false;
this.ivrEndpointName = ivrEndpointName;
this.ivrConnectionIdentifier = ivrConnectionIdentifier;
this.primaryEndpointId = primaryEndpointId;
this.secondaryEndpointId = secondaryEndpointId;
// Initialize the rest of the media group state.
this.observers = new ArrayList<ActorRef>();
}
protected void collect(final Object message) {
final ActorRef self = self();
final Collect request = (Collect) message;
stop(lastEvent);
Object signal;
if (request.type() == Collect.Type.DTMF) {
final PlayCollect.Builder builder = PlayCollect.builder();
for (final URI prompt : request.prompts()) {
builder.addPrompt(prompt);
}
builder.setClearDigitBuffer(true);
builder.setDigitPattern(request.pattern());
builder.setFirstDigitTimer(request.timeout());
builder.setInterDigitTimer(request.timeout());
builder.setEndInputKey(request.endInputKey());
builder.setStartInputKey(request.startInputKey());
builder.setMaxNumberOfDigits(request.numberOfDigits());
signal = builder.build();
this.lastEvent = AUMgcpEvent.aupc;
} else {
this.lastEvent = AsrSignal.REQUEST_ASR;
signal = new AsrSignal(request.getDriver(), request.lang(), request.prompts(), request.endInputKey(), RestcommConfiguration.getInstance().getMgAsr().getAsrMRT(), request.timeout(),
request.timeout(), request.getHints(), request.type().toString() ,request.numberOfDigits(), request.needPartialResult());
}
this.originator = sender();
ivr.tell(signal, self);
ivrInUse = true;
}
protected void play(final Object message) {
final ActorRef self = self();
final Play request = (Play) message;
final List<URI> uris = request.uris();
final int iterations = request.iterations();
final org.restcomm.connect.mgcp.Play play = new org.restcomm.connect.mgcp.Play(uris, iterations);
stop(lastEvent);
this.lastEvent = AUMgcpEvent.aupa;
this.originator = sender();
ivr.tell(play, self);
ivrInUse = true;
}
@SuppressWarnings("unchecked")
protected void notification(final Object message) {
final IvrEndpointResponse response = (IvrEndpointResponse) message;
Object ivrResponse = response.get();
final ActorRef self = self();
MediaGroupResponse<CollectedResult> event;
org.restcomm.connect.mgcp.CollectedResult mgcpCollectedResult = null;
if (response.succeeded()) {
mgcpCollectedResult = (org.restcomm.connect.mgcp.CollectedResult)ivrResponse;
event = new MediaGroupResponse<>(new CollectedResult(mgcpCollectedResult.getResult(), mgcpCollectedResult.isAsr(), mgcpCollectedResult.isPartial()));
} else {
event = new MediaGroupResponse<>(response.cause(), response.error());
}
if (originator != null) {
this.originator.tell(event, self);
if (recording) {
recording = false;
}
}
if (ivrResponse == null || (mgcpCollectedResult != null && !(mgcpCollectedResult.isPartial()))) {
ivrInUse = false;
}
}
protected 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();
final ActorRef sender = sender();
if(logger.isInfoEnabled()) {
logger.info("********** Media Group " + self().path() + " Current State: \"" + state.toString());
logger.info("********** Media Group " + self().path() + " Processing Message: \"" + klass.getName() + " sender : "
+ sender.getClass());
}
if (Observe.class.equals(klass)) {
observe(message);
} else if (StopObserving.class.equals(klass)) {
stopObserving(message);
} else if (MediaGroupStatus.class.equals(klass)) {
if (active.equals(state)) {
sender().tell(new MediaGroupStateChanged(MediaGroupStateChanged.State.ACTIVE, ivr, ivrConnectionIdentifier), self());
} else {
sender().tell(new MediaGroupStateChanged(MediaGroupStateChanged.State.INACTIVE, ivr, ivrConnectionIdentifier), self());
}
} else if (StartMediaGroup.class.equals(klass)) {
if(logger.isInfoEnabled()) {
logger.info("MediaGroup: " + self().path() + " got StartMediaGroup from: " + sender().path() + " endpoint: "
+ endpoint.path() + " isTerminated: " + endpoint.isTerminated());
}
fsm.transition(message, acquiringIvr);
} else if (Join.class.equals(klass)) {
fsm.transition(message, acquiringInternalLink);
} else if (MediaGatewayResponse.class.equals(klass)) {
if (acquiringIvr.equals(state)) {
fsm.transition(message, acquiringLink);
} else if (acquiringLink.equals(state)) {
fsm.transition(message, initializingLink);
} else if (acquiringInternalLink.equals(state)) {
fsm.transition(message, initializingInternalLink);
}
} else if (LinkStateChanged.class.equals(klass)) {
final LinkStateChanged response = (LinkStateChanged) message;
if (LinkStateChanged.State.CLOSED == response.state()) {
if (initializingLink.equals(state)) {
fsm.transition(message, openingLink);
} else if (openingLink.equals(state) || deactivating.equals(state) || updatingLink.equals(state)) {
fsm.transition(message, inactive);
}
if (initializingInternalLink.equals(state)) {
fsm.transition(message, openingInternalLink);
}
} else if (LinkStateChanged.State.OPEN == response.state()) {
ivrConnectionIdentifier = response.connectionIdentifier();
if (openingLink.equals(state)) {
fsm.transition(message, updatingLink);
} else if (updatingLink.equals(state)) {
fsm.transition(message, active);
}
if (openingInternalLink.equals(state)) {
fsm.transition(message, updatingInternalLink);
}
if (updatingInternalLink.equals(state)) {
fsm.transition(message, active);
}
}
} else if (StopMediaGroup.class.equals(klass)) {
if (logger.isInfoEnabled()) {
logger.info("Got StopMediaGroup, current state: "+fsm.state().toString());
}
if (acquiringLink.equals(state) || initializingLink.equals(state)) {
fsm.transition(message, inactive);
} else if (active.equals(state) || openingLink.equals(state) || updatingLink.equals(state)) {
fsm.transition(message, deactivating);
}
} else if (EndpointStateChanged.class.equals(klass)) {
onEndpointStateChanged((EndpointStateChanged) message, self(), sender);
} else if (active.equals(state)) {
if (Play.class.equals(klass)) {
if(logger.isDebugEnabled())
logger.debug("MgcpMediaGroup: got a request to play something at conference ivr..");
play(message);
} else if (Collect.class.equals(klass)) {
collect(message);
} else if (Record.class.equals(klass)) {
record(message);
} else if (Stop.class.equals(klass)) {
stop(lastEvent);
// Send message to originator telling media group has been stopped
// Needed for call bridging scenario, where inbound call must stop
// ringing before attempting to perform join operation.
if (!recording)
sender().tell(new MediaGroupResponse<String>("stopped"), self());
} else if (IvrEndpointResponse.class.equals(klass)) {
notification(message);
}
} else if (ivrInUse) {
if (Stop.class.equals(klass)) {
stop(lastEvent);
}
}
}
protected boolean is(State state) {
return state != null && state.equals(this.fsm.state());
}
protected void onEndpointStateChanged(EndpointStateChanged message, ActorRef self, ActorRef sender) throws Exception {
if (is(deactivating)) {
if (sender.equals(this.ivr) && (EndpointState.DESTROYED.equals(message.getState()) || EndpointState.FAILED.equals(message.getState()))) {
if(EndpointState.FAILED.equals(message.getState()))
logger.error("Could not destroy ivr endpoint on media server: " + this.ivrEndpointName + ". corresponding actor path is: " + this.ivr.path());
this.ivr.tell(new StopObserving(self), self);
this.fsm.transition(message, inactive);
}
}
}
protected void record(final Object message) {
final ActorRef self = self();
final Record request = (Record) message;
final PlayRecord.Builder builder = PlayRecord.builder();
for (final URI prompt : request.prompts()) {
builder.addPrompt(prompt);
}
builder.setClearDigitBuffer(true);
builder.setPreSpeechTimer(request.timeout());
builder.setPostSpeechTimer(request.timeout());
builder.setRecordingLength(request.length());
if (request.endInputKey() != null && !request.endInputKey().equals("-1")) {
builder.setEndInputKey(request.endInputKey());
} else {
builder.setEndInputKey("null");
}
builder.setRecordingId(request.destination());
stop(lastEvent);
this.lastEvent = AUMgcpEvent.aupr;
this.originator = sender();
ivr.tell(builder.build(), self);
ivrInUse = true;
recording = true;
}
protected void stop(MgcpEvent signal) {
if (ivrInUse || (lastEvent != null && lastEvent.getName().equalsIgnoreCase("pr"))) {
if (logger.isInfoEnabled()) {
String msg = String.format("About to stop IVR, with signal %s, last event %s", signal.toString(), lastEvent.toString());
logger.info(msg);
}
final ActorRef self = self();
ivr.tell(new StopEndpoint(signal), self);
ivrInUse = false;
}
}
protected void stopObserving(final Object message) {
final StopObserving request = (StopObserving) message;
final ActorRef observer = request.observer();
if (observer != null) {
observers.remove(observer);
}
}
protected abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
protected final class AcquiringIvr extends AbstractAction {
public AcquiringIvr(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if (ivr != null && !ivr.isTerminated()) {
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path()
+ " got request to create ivr endpoint, will stop the existing one first: " + ivr.path());
}
gateway.tell(new DestroyEndpoint(ivr), null);
getContext().stop(ivr);
ivr = null;
}
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path() + " state: " + fsm.state().toString() + " session: " + session.id()
+ " will ask to get IvrEndpoint: "+ivrEndpointName);
}
gateway.tell(new CreateIvrEndpoint(session, ivrEndpointName), source);
}
}
protected final class AcquiringLink extends AbstractAction {
public AcquiringLink(final ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(final Object message) throws Exception {
final MediaGatewayResponse<ActorRef> response = (MediaGatewayResponse<ActorRef>) message;
ivr = response.get();
ivr.tell(new Observe(source), source);
if (link != null && !link.isTerminated()) {
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path()
+ " got request to create link endpoint, will stop the existing one first: " + link.path());
}
gateway.tell(new DestroyLink(link), null);
getContext().stop(link);
}
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path() + " state: " + fsm.state().toString() + " session: " + session.id()
+ " ivr endpoint: " + ivr.path() + " will ask to get Link");
}
gateway.tell(new CreateLink(session, ivrConnectionIdentifier), source);
}
}
protected final class InitializingLink extends AbstractAction {
public InitializingLink(final ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(final Object message) throws Exception {
final MediaGatewayResponse<ActorRef> response = (MediaGatewayResponse<ActorRef>) message;
link = response.get();
if (endpoint == null)
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path() + " state: " + fsm.state().toString() + " session: " + session.id()
+ " link: " + link.path() + " endpoint is null will have exception");
}
link.tell(new Observe(source), source);
link.tell(new InitializeLink(endpoint, ivr), source);
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path() + " state: " + fsm.state().toString() + " session: " + session.id()
+ " link: " + link.path() + " endpoint: " + endpoint.path()
+ " initializeLink sent, endpoint isTerminated: " + endpoint.isTerminated());
}
}
}
protected final class OpeningLink extends AbstractAction {
public OpeningLink(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path() + " state: " + fsm.state().toString() + " session: " + session.id()
+ " link: " + link.path() + " will ask to open Link with primaryEndpointId: "+ primaryEndpointId+" secondaryEndpointId: "+secondaryEndpointId);
}
link.tell(new OpenLink(ConnectionMode.SendRecv, primaryEndpointId, secondaryEndpointId), source);
}
}
protected final class UpdatingLink extends AbstractAction {
public UpdatingLink(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final UpdateLink update = new UpdateLink(ConnectionMode.SendRecv, UpdateLink.Type.PRIMARY);
link.tell(update, source);
}
}
// Join OutboundCall Bridge endpoint to the IVR endpoint for recording - START
protected final class AcquiringInternalLink extends AbstractAction {
public AcquiringInternalLink(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final Class<?> klass = message.getClass();
if (Join.class.equals(klass)) {
final Join request = (Join) message;
internalLinkEndpoint = request.endpoint();
internalLinkMode = request.mode();
}
gateway.tell(new CreateLink(session, ivrConnectionIdentifier), source);
}
}
protected final class InitializingInternalLink extends AbstractAction {
public InitializingInternalLink(final ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(Object message) throws Exception {
final MediaGatewayResponse<ActorRef> response = (MediaGatewayResponse<ActorRef>) message;
internalLink = response.get();
internalLink.tell(new Observe(source), source);
internalLink.tell(new InitializeLink(internalLinkEndpoint, ivr), source);
}
}
protected final class OpeningInternalLink extends AbstractAction {
public OpeningInternalLink(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
internalLink.tell(new OpenLink(internalLinkMode), source);
}
}
protected final class UpdatingInternalLink extends AbstractAction {
public UpdatingInternalLink(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final UpdateLink update = new UpdateLink(ConnectionMode.SendRecv, UpdateLink.Type.PRIMARY);
internalLink.tell(update, source);
}
}
// Join OutboundCall Bridge endpoint to the IVR endpoint for recording - END
protected final class Active extends AbstractAction {
public Active(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
// Notify the observers.
final MediaGroupStateChanged event = new MediaGroupStateChanged(MediaGroupStateChanged.State.ACTIVE, ivr, ivrConnectionIdentifier);
for (final ActorRef observer : observers) {
observer.tell(event, source);
}
}
}
protected final class Inactive extends AbstractAction {
public Inactive(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if (link != null) {
gateway.tell(new DestroyLink(link), source);
link = null;
}
if (internalLink != null) {
gateway.tell(new DestroyLink(internalLink), source);
internalLink = null;
}
// Notify the observers.
final MediaGroupStateChanged event = new MediaGroupStateChanged(MediaGroupStateChanged.State.INACTIVE, ivr, ivrConnectionIdentifier);
for (final ActorRef observer : observers) {
observer.tell(event, source);
}
}
}
protected final class Deactivating extends AbstractAction {
public Deactivating(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
ivr.tell(new DestroyEndpoint(), super.source);
// if (link != null)
// link.tell(new CloseLink(), source);
// if (internalLink != null)
// internalLink.tell(new CloseLink(), source);
}
}
@Override
public void postStop() {
if (internalLinkEndpoint != null) {
if(logger.isInfoEnabled()) {
logger.info("MediaGroup: " + self().path() + " at postStop, about to stop intenalLinkEndpoint: "
+ internalLinkEndpoint.path() + " sender: " + sender().path());
}
gateway.tell(new DestroyEndpoint(internalLinkEndpoint), null);
getContext().stop(internalLinkEndpoint);
internalLinkEndpoint = null;
}
if (ivr != null) {
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path() + " at postStop, about to stop ivr endpoint :" + ivr.path());
}
gateway.tell(new DestroyEndpoint(ivr), null);
getContext().stop(ivr);
ivr = null;
}
if(link != null) {
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path() + " at postStop, about to stop link :" + link.path());
}
getContext().stop(link);
link = null;
}
if(internalLink != null) {
if(logger.isInfoEnabled()) {
logger.info("MediaGroup :" + self().path() + " at postStop, about to stop internal link :" + internalLink.path());
}
getContext().stop(link);
link = null;
}
getContext().stop(self());
super.postStop();
}
}
| 31,542 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MmsConferenceController.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.mms/src/main/java/org/restcomm/connect/mscontrol/mms/MmsConferenceController.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.mscontrol.mms;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import jain.protocol.ip.mgcp.message.parms.ConnectionMode;
import org.mobicents.servlet.restcomm.mscontrol.messages.MediaServerConferenceControllerStateChanged;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.commons.dao.Sid;
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 org.restcomm.connect.mgcp.CreateConferenceEndpoint;
import org.restcomm.connect.mgcp.DestroyEndpoint;
import org.restcomm.connect.mgcp.EndpointState;
import org.restcomm.connect.mgcp.EndpointStateChanged;
import org.restcomm.connect.mgcp.MediaGatewayResponse;
import org.restcomm.connect.mgcp.MediaResourceBrokerResponse;
import org.restcomm.connect.mgcp.MediaSession;
import org.restcomm.connect.mrb.api.ConferenceMediaResourceControllerStateChanged;
import org.restcomm.connect.mrb.api.GetConferenceMediaResourceController;
import org.restcomm.connect.mrb.api.GetMediaGateway;
import org.restcomm.connect.mrb.api.MediaGatewayForConference;
import org.restcomm.connect.mrb.api.StartConferenceMediaResourceController;
import org.restcomm.connect.mrb.api.StopConferenceMediaResourceController;
import org.restcomm.connect.mscontrol.api.MediaServerController;
import org.restcomm.connect.mscontrol.api.messages.CloseMediaSession;
import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession;
import org.restcomm.connect.mscontrol.api.messages.JoinCall;
import org.restcomm.connect.mscontrol.api.messages.JoinComplete;
import org.restcomm.connect.mscontrol.api.messages.JoinConference;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged.MediaServerControllerState;
import org.restcomm.connect.mscontrol.api.messages.Play;
import org.restcomm.connect.mscontrol.api.messages.StartRecording;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.StopRecording;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Henrique Rosa ([email protected])
* @author Maria Farooq ([email protected])
*/
@Immutable
public final class MmsConferenceController extends MediaServerController {
// Logging
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Finite State Machine
private final FiniteStateMachine fsm;
private final State uninitialized;
private final State acquiringMediaGateway;
private final State acquiringCnfMediaResourceController;
private final State active;
private final State inactive;
private final State failed;
private final State acquiringMediaSession;
private final State acquiringEndpoint;
//private final State creatingMediaGroup;
private final State stopping;
private final State stoppingCMRC;
//private Boolean fail;
// MGCP runtime stuff.
private ActorRef mediaGateway;
private MediaSession mediaSession;
private ActorRef cnfEndpoint;
// Conference runtime stuff
//private ActorRef conference;
//private ActorRef mediaGroup;
private ActorRef conferenceMediaResourceController;
private boolean firstJoinSent = false;
// Runtime media operations
//private Boolean playing;
//private Boolean recording;
//private DateTime recordStarted;
// Observers
private final List<ActorRef> observers;
private final ActorRef mrb;
private String conferenceName;
private Sid conferenceSid;
private String conferenceEndpointIdName;
private ConnectionMode connectionMode;
//public MmsConferenceController(final List<ActorRef> mediaGateways, final Configuration configuration) {
//public MmsConferenceController(final ActorRef mediaGateway) {
public MmsConferenceController(final ActorRef mrb) {
super();
final ActorRef source = self();
// Finite States
this.uninitialized = new State("uninitialized", null, null);
this.acquiringMediaGateway = new State("acquiring media gateway from mrb", new AcquiringMediaGateway(source), null);
this.acquiringCnfMediaResourceController = new State("acquiring Cnf Media Resource Controller", new AcquiringCnfMediaResourceController(source), null);
this.active = new State("active", new Active(source), null);
this.inactive = new State("inactive", new Inactive(source), null);
this.failed = new State("failed", new Failed(source), null);
this.acquiringMediaSession = new State("acquiring media session", new AcquiringMediaSession(source), null);
this.acquiringEndpoint = new State("acquiring endpoint", new AcquiringEndpoint(source), null);
//this.creatingMediaGroup = new State("creating media group", new CreatingMediaGroup(source), null);
this.stoppingCMRC = new State("stopping HA Conference Media Resource Controller", new StoppingCMRC(source), null);
this.stopping = new State("stopping", new Stopping(source), null);
// Initialize the transitions for the FSM.
final Set<Transition> transitions = new HashSet<Transition>();
transitions.add(new Transition(uninitialized, acquiringMediaGateway));
transitions.add(new Transition(acquiringMediaGateway, acquiringMediaSession));
transitions.add(new Transition(acquiringMediaSession, acquiringEndpoint));
transitions.add(new Transition(acquiringMediaSession, inactive));
transitions.add(new Transition(acquiringEndpoint, acquiringCnfMediaResourceController));
transitions.add(new Transition(acquiringEndpoint, inactive));
//transitions.add(new Transition(creatingMediaGroup, gettingCnfMediaResourceController));
transitions.add(new Transition(acquiringCnfMediaResourceController, active));
transitions.add(new Transition(acquiringCnfMediaResourceController, stoppingCMRC));
transitions.add(new Transition(acquiringCnfMediaResourceController, failed));
transitions.add(new Transition(active, stoppingCMRC));
transitions.add(new Transition(stoppingCMRC, stopping));
transitions.add(new Transition(stoppingCMRC, inactive));
transitions.add(new Transition(stopping, inactive));
transitions.add(new Transition(stopping, failed));
// Finite State Machine
this.fsm = new FiniteStateMachine(uninitialized, transitions);
//this.fail = Boolean.FALSE;
// MGCP runtime stuff
//this.mediaGateway = mrb.getNextMediaServerKey();
//this.mediaGateways = new MediaGateways(mediaGateways , configuration);
this.mrb = mrb;
// Runtime media operations
//this.playing = Boolean.FALSE;
//this.recording = Boolean.FALSE;
// Observers
this.observers = new ArrayList<ActorRef>(2);
}
private boolean is(State state) {
return this.fsm.state().equals(state);
}
private void broadcast(Object message) {
if (!this.observers.isEmpty()) {
final ActorRef self = self();
synchronized (this.observers) {
for (ActorRef observer : observers) {
observer.tell(message, self);
}
}
}
}
/*
* EVENTS
*/
@Override
@SuppressWarnings("unchecked")
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef sender = sender();
final ActorRef self = self();
final State state = fsm.state();
if(logger.isInfoEnabled()) {
logger.info(" ********** Conference Controller Current State: " + state.toString());
logger.info(" ********** Conference Controller Processing Message: " + klass.getName());
}
if (Observe.class.equals(klass)) {
onObserve((Observe) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
onStopObserving((StopObserving) message, self, sender);
} else if (CreateMediaSession.class.equals(klass)) {
onCreateMediaSession((CreateMediaSession) message, self, sender);
} else if (CloseMediaSession.class.equals(klass)) {
onCloseMediaSession((CloseMediaSession) message, self, sender);
} else if (MediaGatewayResponse.class.equals(klass)) {
onMediaGatewayResponse((MediaGatewayResponse<?>) message, self, sender);
} else if (Stop.class.equals(klass)) {
onStop((Stop) message, self, sender);
} /*else if (MediaGroupStateChanged.class.equals(klass)) {
onMediaGroupStateChanged((MediaGroupStateChanged) message, self, sender);
}*/ else if (JoinCall.class.equals(klass)) {
onJoinCall((JoinCall) message, self, sender);
} else if (Play.class.equals(klass) || StartRecording.class.equals(klass) || StopRecording.class.equals(klass)) {
conferenceMediaResourceController.tell(message, sender);
} else if (StopMediaGroup.class.equals(klass)) {
StopMediaGroup msg = (StopMediaGroup)message;
/* to media-server as media-server will automatically stop beep when it will receive
* play command for beep. If a beep wont be played, then conference need to send
* EndSignal(StopMediaGroup) to media-server to stop ongoing music-on-hold.
* https://github.com/RestComm/Restcomm-Connect/issues/2024
*/
if(!msg.beep()){
conferenceMediaResourceController.tell(message, sender);
}
}else if(EndpointStateChanged.class.equals(klass)) {
onEndpointStateChanged((EndpointStateChanged) message, self, sender);
} else if (MediaResourceBrokerResponse.class.equals(klass)) {
onMediaResourceBrokerResponse((MediaResourceBrokerResponse<?>) message, self, sender);
} else if(JoinComplete.class.equals(klass)) {
onJoinComplete((JoinComplete) message, self, sender);
} else if(ConferenceMediaResourceControllerStateChanged.class.equals(klass)) {
onConferenceMediaResourceControllerStateChanged((ConferenceMediaResourceControllerStateChanged) message, self, sender);
}
}
private void onObserve(Observe message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
synchronized (this.observers) {
this.observers.add(observer);
observer.tell(new Observing(self), self);
}
}
}
private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
this.observers.remove(observer);
}
}
private void onJoinComplete(JoinComplete message, ActorRef self, ActorRef sender) {
if(logger.isInfoEnabled())
logger.info("got JoinComplete in conference controller");
if(!firstJoinSent){
firstJoinSent = true;
conferenceMediaResourceController.tell(message, self);
}
}
private void onMediaResourceBrokerResponse(MediaResourceBrokerResponse<?> message, ActorRef self, ActorRef sender) throws Exception {
if(logger.isInfoEnabled())
logger.info("got MRB response in conference controller");
if(is(acquiringMediaGateway)){
MediaGatewayForConference mgc = (MediaGatewayForConference) message.get();
mediaGateway = mgc.mediaGateway();
this.conferenceSid = mgc.conferenceSid();
// if this is master we would like to connect to master conference ep
// for master's first join it would be null but if master left and rejoin it should join on same ep as received by mrb.
// if this is not master conference ep should be null, so RMS would give us next available from pool.
this.conferenceEndpointIdName = mgc.isThisMaster() ? mgc.masterConfernceEndpointIdName() : null;
if(logger.isDebugEnabled())
logger.debug("onMediaResourceBrokerResponse: "+mgc.toString());
fsm.transition(message, acquiringMediaSession);
}else if(is(acquiringCnfMediaResourceController)){
conferenceMediaResourceController = (ActorRef) message.get();
conferenceMediaResourceController.tell(new Observe(self), self);
conferenceMediaResourceController.tell(new StartConferenceMediaResourceController(this.cnfEndpoint, this.conferenceSid), self);
}
}
private void onConferenceMediaResourceControllerStateChanged(ConferenceMediaResourceControllerStateChanged message, ActorRef self, ActorRef sender) throws Exception {
if(logger.isDebugEnabled())
logger.debug("onConferenceMediaResourceControllerStateChanged: "+message.state());
switch (message.state()) {
case ACTIVE:
if (is(acquiringCnfMediaResourceController)) {
fsm.transition(message, active);
}
break;
case FAILED:
fsm.transition(message, failed);
break;
case INACTIVE:
fsm.transition(message, stopping);
break;
default:
break;
}
}
private void onCreateMediaSession(CreateMediaSession message, ActorRef self, ActorRef sender) throws Exception {
if (is(uninitialized)) {
//this.conference = sender;
fsm.transition(message, acquiringMediaGateway);
}
}
private void onCloseMediaSession(CloseMediaSession message, ActorRef self, ActorRef sender) throws Exception {
if (is(active)) {
fsm.transition(message, inactive);
} else {
fsm.transition(message, stoppingCMRC);
}
}
private void onStop(Stop message, ActorRef self, ActorRef sender) throws Exception {
if (is(acquiringMediaSession) || is(acquiringEndpoint)) {
this.fsm.transition(message, inactive);
} else if (is(acquiringCnfMediaResourceController) || is(active)) {
this.fsm.transition(message, stoppingCMRC);
}
}
private void onMediaGatewayResponse(MediaGatewayResponse<?> message, ActorRef self, ActorRef sender) throws Exception {
// XXX Check if message successful
if (is(acquiringMediaSession)) {
this.mediaSession = (MediaSession) message.get();
this.fsm.transition(message, acquiringEndpoint);
} else if (is(acquiringEndpoint)) {
this.cnfEndpoint = (ActorRef) message.get();
this.cnfEndpoint.tell(new Observe(self), self);
this.fsm.transition(message, acquiringCnfMediaResourceController);
}
}
/*private void onMediaGroupStateChanged(MediaGroupStateChanged message, ActorRef self, ActorRef sender) throws Exception {
switch (message.state()) {
case ACTIVE:
if (is(creatingMediaGroup)) {
fsm.transition(message, gettingCnfMediaResourceController);
}
break;
case INACTIVE:
if (is(creatingMediaGroup)) {
this.fail = Boolean.TRUE;
fsm.transition(message, failed);
} else if (is(stopping)) {
// Stop media group actor
this.mediaGroup.tell(new StopObserving(self), self);
context().stop(mediaGroup);
this.mediaGroup = null;
// Move to next state
if (this.mediaGroup == null && this.cnfEndpoint == null) {
this.fsm.transition(message, fail ? failed : inactive);
}
}
break;
default:
break;
}
}*/
private void onJoinCall(JoinCall message, ActorRef self, ActorRef sender) {
connectionMode = message.getConnectionMode();
// Tell call to join conference by passing reference to the media mixer
final JoinConference join = new JoinConference(this.cnfEndpoint, connectionMode, message.getSid());
message.getCall().tell(join, sender);
}
/*private void onStopMediaGroup(StopMediaGroup message, ActorRef self, ActorRef sender) {
if (is(active)) {
// Stop the primary media group
this.mediaGroup.tell(new Stop(), self);
this.playing = Boolean.FALSE;
}
}
private void onPlay(Play message, ActorRef self, ActorRef sender) {
if (is(active) && !playing) {
if (logger.isInfoEnabled()) {
logger.info("Received Play message, isActive: "+is(active)+" , is playing: "+playing);
}
this.playing = Boolean.TRUE;
this.mediaGroup.tell(message, self);
} else {
if (logger.isInfoEnabled()) {
logger.info("Received Play message but wont process it, isActive: "+is(active)+" , is playing: "+playing);
}
}
}
private void onStartRecording(StartRecording message, ActorRef self, ActorRef sender) throws Exception {
if (is(active) && !recording) {
String finishOnKey = "1234567890*#";
int maxLength = 3600;
int timeout = 5;
this.recording = Boolean.TRUE;
this.recordStarted = DateTime.now();
// Tell media group to start recording
Record record = new Record(message.getRecordingUri(), timeout, maxLength, finishOnKey);
this.mediaGroup.tell(record, null);
}
}
private void onStopRecording(StopRecording message, ActorRef self, ActorRef sender) throws Exception {
if (is(active) && recording) {
this.recording = Boolean.FALSE;
mediaGroup.tell(new Stop(), null);
}
}
private void onMediaGroupResponse(MediaGroupResponse<String> message, ActorRef self, ActorRef sender) throws Exception {
if (is(active) && this.playing) {
this.playing = Boolean.FALSE;
}
}*/
private void onEndpointStateChanged(EndpointStateChanged message, ActorRef self, ActorRef sender) throws Exception {
if (is(stopping)) {
if (sender.equals(this.cnfEndpoint) && (EndpointState.DESTROYED.equals(message.getState()) || EndpointState.FAILED.equals(message.getState()))) {
if(EndpointState.FAILED.equals(message.getState()))
logger.error("Could not destroy endpoint on media server. corresponding actor path is: " + this.cnfEndpoint.path());
this.cnfEndpoint.tell(new StopObserving(self), self);
context().stop(cnfEndpoint);
cnfEndpoint = null;
if(this.cnfEndpoint == null) {
this.fsm.transition(message, inactive);
}
}
}
}
/*
* ACTIONS
*/
private abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
private final class AcquiringMediaGateway extends AbstractAction {
public AcquiringMediaGateway(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
CreateMediaSession createMediaSession = (CreateMediaSession) message;
String conferenceName = createMediaSession.conferenceName();
mrb.tell(new GetMediaGateway(createMediaSession.callSid(), conferenceName, null), self());
}
}
private final class AcquiringCnfMediaResourceController extends AbstractAction {
public AcquiringCnfMediaResourceController(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled())
logger.info("MMSConferenceController: GettingCnfMediaResourceController: conferenceName = "+conferenceName+" conferenceSid: "+conferenceSid+" cnfenpointID: "+cnfEndpoint);
mrb.tell(new GetConferenceMediaResourceController(conferenceName), self());
}
}
private final class AcquiringMediaSession extends AbstractAction {
public AcquiringMediaSession(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mediaGateway.tell(new org.restcomm.connect.mgcp.CreateMediaSession(), super.source);
}
}
private final class AcquiringEndpoint extends AbstractAction {
public AcquiringEndpoint(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
mediaGateway.tell(new CreateConferenceEndpoint(mediaSession, conferenceEndpointIdName), super.source);
}
}
private final class Active extends AbstractAction {
public Active(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
ConferenceMediaResourceControllerStateChanged msg = (ConferenceMediaResourceControllerStateChanged)message;
broadcast(new MediaServerConferenceControllerStateChanged(MediaServerControllerState.ACTIVE, conferenceSid, msg.conferenceState(), msg.moderatorPresent()));
}
}
private final class StoppingCMRC extends AbstractAction {
public StoppingCMRC(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled())
logger.info("StoppingCMRC");
conferenceMediaResourceController.tell(new StopConferenceMediaResourceController(), super.source);
}
}
private final class Stopping extends AbstractAction {
public Stopping(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
ConferenceMediaResourceControllerStateChanged response = (ConferenceMediaResourceControllerStateChanged) message;
// CMRC might ask you not to destroy endpoint bcz master have left firt and other slaves are still connected to this conference endpoint.
if(response.destroyEndpoint()){
// Destroy Bridge Endpoint and its connections
cnfEndpoint.tell(new DestroyEndpoint(), super.source);
}else{
if(logger.isInfoEnabled())
logger.info("CMRC have ask you not to destroy endpoint bcz master have left firt and other slaves are still connected to this conference endpoint");
cnfEndpoint.tell(new StopObserving(self()), self());
context().stop(cnfEndpoint);
cnfEndpoint = null;
if(cnfEndpoint == null) {
fsm.transition(message, inactive);
}
}
}
}
private abstract class FinalState extends AbstractAction {
private final MediaServerControllerState state;
public FinalState(ActorRef source, final MediaServerControllerState state) {
super(source);
this.state = state;
}
@Override
public void execute(Object message) throws Exception {
// Cleanup resources
if (cnfEndpoint != null) {
mediaGateway.tell(new DestroyEndpoint(cnfEndpoint), super.source);
cnfEndpoint = null;
}
if(conferenceMediaResourceController != null){
context().stop(conferenceMediaResourceController);
conferenceMediaResourceController = null;
}
// Notify observers the controller has stopped
broadcast(new MediaServerConferenceControllerStateChanged(state, conferenceSid));
// Clean observers
observers.clear();
// Terminate actor
getContext().stop(super.source);
}
}
private final class Inactive extends FinalState {
public Inactive(final ActorRef source) {
super(source, MediaServerControllerState.INACTIVE);
}
}
private final class Failed extends FinalState {
public Failed(final ActorRef source) {
super(source, MediaServerControllerState.FAILED);
}
}
}
| 26,350 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
QueryEndpoint.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.mms/src/main/java/org/restcomm/connect/mscontrol/mms/messages/QueryEndpoint.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.mscontrol.mms.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class QueryEndpoint {
public QueryEndpoint() {
super();
}
}
| 1,212 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
EndpointInfo.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.mms/src/main/java/org/restcomm/connect/mscontrol/mms/messages/EndpointInfo.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.mscontrol.mms.messages;
import jain.protocol.ip.mgcp.message.parms.ConnectionMode;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import akka.actor.ActorRef;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class EndpointInfo {
private final ActorRef endpoint;
private final ConnectionMode connectionMode;
public EndpointInfo(ActorRef endpoint, ConnectionMode connectionMode) {
super();
this.endpoint = endpoint;
this.connectionMode = connectionMode;
}
public ActorRef getEndpoint() {
return endpoint;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
}
| 1,668 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
TestUssdMessages.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/test/java/org/restcomm/connect/ussd/TestUssdMessages.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.ussd;
import static org.junit.Assert.*;
import javax.xml.stream.XMLStreamException;
import org.junit.Test;
import org.restcomm.connect.ussd.commons.UssdMessageType;
import org.restcomm.connect.ussd.commons.UssdRestcommResponse;
import org.restcomm.connect.ussd.commons.UssdInfoRequest;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public class TestUssdMessages {
private String requestLanguage = "en";
private String responseMessage = "Press 1 to know your airtime and 2 to know your SMS balance";
private UssdMessageType ussdMessageType = UssdMessageType.unstructuredSSRequest_Request;
UssdRestcommResponse ussdRestcommResponse;
String ussdOriginalRestcommResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ussd-data><language value=\"en\"></language>"
+ "<ussd-string value=\"Press 1 to know your airtime and 2 to know your SMS balance\"></ussd-string>"
+ "<anyExt><message-type>unstructuredSSRequest_Request</message-type></anyExt></ussd-data>";
String ussdInfoRequestFromClient = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ussd-data><language value=\"en\"/>"
+ "<ussd-string value=\"1\"/><anyExt><message-type>unstructuredSSRequest_Response</message-type></anyExt></ussd-data>";
String ussdInfoRequestFromClient2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><ussd-data>"
+ "<ussd-string value=\"2\"/></ussd-data>";
private void createUssdMessage() {
ussdRestcommResponse = new UssdRestcommResponse();
ussdRestcommResponse.setLanguage("en");
ussdRestcommResponse.setMessage(responseMessage);
ussdRestcommResponse.setMessageType(ussdMessageType);
}
@Test
public void testUssdRestcommResponse() throws XMLStreamException{
createUssdMessage();
String ussdPayload = ussdRestcommResponse.createUssdPayload();
assertTrue(ussdOriginalRestcommResponse.equals(ussdPayload.replaceAll("\\n", "")));
}
@Test
public void testInforRequestFromClient() throws Exception {
UssdInfoRequest ussdInfoRequest = new UssdInfoRequest(ussdInfoRequestFromClient);
assertTrue("1".equals(ussdInfoRequest.getMessage()));
assertTrue("en".equals(ussdInfoRequest.getLanguage()));
assertTrue(UssdMessageType.unstructuredSSRequest_Response.equals(ussdInfoRequest.getUssdMessageType()));
ussdInfoRequest = new UssdInfoRequest(ussdInfoRequestFromClient2);
assertTrue("2".equals(ussdInfoRequest.getMessage()));
assertTrue("en".equals(ussdInfoRequest.getLanguage()));
assertTrue(UssdMessageType.unstructuredSSRequest_Response.equals(ussdInfoRequest.getUssdMessageType()));
}
}
| 3,582 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdCallType.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/telephony/UssdCallType.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.ussd.telephony;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public enum UssdCallType {
/*
* Ussd Call types
* PULL: User initiates the USSD call and Restcomm responds
* PUSH: Restcomm initiates the USSD call
*/
PULL,PUSH;
}
| 1,100 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdCall.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/telephony/UssdCall.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.ussd.telephony;
import akka.actor.ActorRef;
import akka.actor.UntypedActorContext;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.dao.Sid;
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.fsm.TransitionEndListener;
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.telephony.CreateCallType;
import org.restcomm.connect.commons.util.DNSUtils;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.telephony.api.Answer;
import org.restcomm.connect.telephony.api.CallInfo;
import org.restcomm.connect.telephony.api.CallResponse;
import org.restcomm.connect.telephony.api.CallStateChanged;
import org.restcomm.connect.telephony.api.GetCallInfo;
import org.restcomm.connect.telephony.api.GetCallObservers;
import org.restcomm.connect.telephony.api.InitializeOutbound;
import org.restcomm.connect.telephony.api.events.UssdStreamEvent;
import org.restcomm.connect.ussd.commons.UssdRestcommResponse;
import org.restcomm.connect.ussd.interpreter.UssdInterpreter;
import scala.concurrent.duration.Duration;
import javax.servlet.sip.Address;
import javax.servlet.sip.ServletParseException;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServletMessage;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipSession;
import javax.servlet.sip.SipURI;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Currency;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.TimeUnit;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public class UssdCall extends RestcommUntypedActor implements TransitionEndListener {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
private final String ussdContentType = "application/vnd.3gpp.ussd+xml";
private static final String OUTBOUND_API = "outbound-api";
private static final String OUTBOUND_DIAL = "outbound-dial";
private UssdCallType ussdCallType;
private final FiniteStateMachine fsm;
// States for the FSM.
private final State uninitialized;
private final State ringing;
private final State inProgress;
private final State ready;
private final State processingUssdMessage;
private final State completed;
private final State queued;
private final State dialing;
private final State disconnecting;
private final State cancelling;
// SIP runtime stuff.
private final SipFactory factory;
private String apiVersion;
private Sid accountId;
private String name;
private SipURI from;
private SipURI to;
private String transport;
private UssdRestcommResponse userUssdRequest;
private String username;
private String password;
private CreateCallType type;
private long timeout;
private SipServletRequest invite;
private SipServletRequest outgoingInvite;
private SipServletResponse lastResponse;
private Map<String, String> headers;
private boolean isFromApi;
// Runtime stuff.
private final Sid id;
private CallStateChanged.State external;
private String direction;
private DateTime created;
private final List<ActorRef> observers;
private CallDetailRecordsDao callDetailrecordsDao;
private CallDetailRecord outgoingCallRecord;
private ActorRef ussdInterpreter;
public UssdCall(final SipFactory factory) {
super();
final ActorRef source = self();
// Initialize the states for the FSM.
uninitialized = new State("uninitialized", null, null);
ringing = new State("ringing", new Ringing(source), null);
inProgress = new State("in progress", new InProgress(source), null);
ready = new State("answering", new Ready(source), null);
processingUssdMessage = new State("processing UssdMessage", new ProcessingUssdMessage(source), null);
completed = new State("Completed", new Completed(source), null);
queued = new State("queued", new Queued(source), null);
dialing = new State("dialing", new Dialing(source), null);
disconnecting = new State("Disconnecting", new Disconnecting(source), null);
cancelling = new State("Cancelling", new Cancelling(source), null);
// Initialize the transitions for the FSM.
final Set<Transition> transitions = new HashSet<Transition>();
transitions.add(new Transition(uninitialized, ringing));
transitions.add(new Transition(uninitialized, cancelling));
transitions.add(new Transition(uninitialized, queued));
transitions.add(new Transition(queued, dialing));
transitions.add(new Transition(queued, cancelling));
transitions.add(new Transition(dialing, processingUssdMessage));
transitions.add(new Transition(dialing, completed));
transitions.add(new Transition(ringing, inProgress));
transitions.add(new Transition(ringing, cancelling));
transitions.add(new Transition(inProgress, processingUssdMessage));
transitions.add(new Transition(inProgress, disconnecting));
transitions.add(new Transition(inProgress, completed));
transitions.add(new Transition(processingUssdMessage, ready));
transitions.add(new Transition(processingUssdMessage, inProgress));
transitions.add(new Transition(processingUssdMessage, completed));
transitions.add(new Transition(processingUssdMessage, processingUssdMessage));
transitions.add(new Transition(processingUssdMessage, dialing));
transitions.add(new Transition(processingUssdMessage, disconnecting));
// Initialize the FSM.
this.fsm = new FiniteStateMachine(uninitialized, transitions);
this.fsm.addTransitionEndListener(this);
// Initialize the SIP runtime stuff.
this.factory = factory;
// Initialize the runtime stuff.
this.id = Sid.generate(Sid.Type.CALL);
this.created = DateTime.now();
this.observers = Collections.synchronizedList(new ArrayList<ActorRef>());
}
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);
}
}
private void stopObserving(final Object message) {
final StopObserving request = (StopObserving) message;
final ActorRef observer = request.observer();
if (observer != null) {
observers.remove(observer);
}
}
private CallResponse<CallInfo> info() {
if (from == null)
from = (SipURI) invite.getFrom().getURI();
if (to == null)
to = (SipURI) invite.getTo().getURI();
final String from = this.from.getUser();
final String to = this.to.getUser();
final CallInfo info = new CallInfo(id, accountId, external, type, direction, created, null, name, from, to, invite, lastResponse,
false, false, isFromApi, null, null);
return new CallResponse<CallInfo>(info);
}
private SipURI getInitialIpAddressPort(SipServletMessage message) throws ServletParseException, UnknownHostException {
// Issue #268 - https://bitbucket.org/telestax/telscale-restcomm/issue/268
// First get the Initial Remote Address (real address that the request came from)
// Then check the following:
// 1. If contact header address is private network address
// 2. If there are no "Record-Route" headers (there is no proxy in the call)
// 3. If contact header address != real ip address
// Finally, if all of the above are true, create a SIP URI using the realIP address and the SIP port
// and store it to the sip session to be used as request uri later
String realIP = message.getInitialRemoteAddr();
int realPort = message.getInitialRemotePort();
final ListIterator<String> recordRouteHeaders = message.getHeaders("Record-Route");
final Address contactAddr = factory.createAddress(message.getHeader("Contact"));
InetAddress contactInetAddress = DNSUtils.getByName(((SipURI) contactAddr.getURI()).getHost());
InetAddress inetAddress = DNSUtils.getByName(realIP);
int remotePort = message.getRemotePort();
int contactPort = ((SipURI)contactAddr.getURI()).getPort();
String remoteAddress = message.getRemoteAddr();
//Issue #332: https://telestax.atlassian.net/browse/RESTCOMM-332
final String initialIpBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemoteAddr");
String initialPortBeforeLB = message.getHeader("X-Sip-Balancer-InitialRemotePort");
SipURI uri = null;
if (initialIpBeforeLB != null) {
if(initialPortBeforeLB == null)
initialPortBeforeLB = "5060";
logger.info("We are behind load balancer, storing Initial Remote Address " + initialIpBeforeLB+":"+initialPortBeforeLB
+ " to the session for later use");
realIP = initialIpBeforeLB+":"+initialPortBeforeLB;
uri = factory.createSipURI(null, realIP);
} else if (contactInetAddress.isSiteLocalAddress() && !recordRouteHeaders.hasNext()
&& !contactInetAddress.toString().equalsIgnoreCase(inetAddress.toString())) {
logger.info("Contact header address " + contactAddr.toString()
+ " is a private network ip address, storing Initial Remote Address " + realIP+":"+realPort
+ " to the session for later use");
realIP = realIP + ":" + realPort;
uri = factory.createSipURI(null, realIP);
}
// //Assuming that the contactPort (from the Contact header) is the port that is assigned to the sip client,
// //If RemotePort (either from Packet or from the Via header rport) is not the same as the contactPort, then we
// //should use the remotePort and remoteAddres for the URI to use later for client behind NAT
// else if(remotePort != contactPort) {
// logger.info("RemotePort: "+remotePort+" is different than the Contact Address port: "+contactPort+" so storing for later use the "
// + remoteAddress+":"+remotePort);
// realIP = remoteAddress+":"+remotePort;
// uri = factory.createSipURI(null, realIP);
// }
return uri;
}
@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();
final State state = fsm.state();
logger.info("UssdCall's Current State: \"" + state.toString());
logger.info("UssdCall Processing Message: \"" + klass.getName());
if (Observe.class.equals(klass)) {
observe(message);
} else if (StopObserving.class.equals(klass)) {
stopObserving(message);
} else if (GetCallObservers.class.equals(klass)) {
sender.tell(new CallResponse<List<ActorRef>>(observers), self);
} else if (GetCallInfo.class.equals(klass)) {
sender.tell(info(), self);
} else if (message instanceof SipServletRequest) {
final SipServletRequest request = (SipServletRequest) message;
final String method = request.getMethod();
if ("INVITE".equalsIgnoreCase(method)) {
if (uninitialized.equals(state)) {
fsm.transition(message, ringing);
}
} else if ("BYE".equalsIgnoreCase(method)) {
fsm.transition(message, disconnecting);
} else if("CANCEL".equalsIgnoreCase(method)) {
if (!request.getSession().getState().equals(SipSession.State.CONFIRMED) || !request.getSession().getState().equals(SipSession.State.TERMINATED))
fsm.transition(message, cancelling);
}
} else if (message instanceof SipServletResponse) {
final SipServletResponse response = (SipServletResponse) message;
lastResponse = response;
if(response.getStatus() == SipServletResponse.SC_OK && response.getRequest().getMethod().equalsIgnoreCase("INVITE")){
response.createAck().send();
} if(response.getStatus() == SipServletResponse.SC_OK && (response.getRequest().getMethod().equalsIgnoreCase("BYE"))) {
fsm.transition(message, completed);
}
} else if (UssdRestcommResponse.class.equals(klass)) {
//If direction is outbound, get the message and create the Invite
if (!direction.equalsIgnoreCase("inbound") && outgoingInvite == null) {
this.ussdInterpreter = sender;
fsm.transition(message, dialing);
return;
}
fsm.transition(message, processingUssdMessage);
} else if (Answer.class.equals(klass)) {
fsm.transition(message, inProgress);
} else if (InitializeOutbound.class.equals(klass)) {
fsm.transition(message, queued);
}
}
@Override
public void onTransitionEnd(State was, State is, Object event) {
UssdStreamEvent.Builder builder = UssdStreamEvent.builder()
.setSid(id)
.setAccountSid(accountId)
.setDirection(UssdStreamEvent.Direction.valueOf(direction))
.setFrom(from.getUser())
.setTo(to.getUser());
if (userUssdRequest != null){
builder.setStatus(UssdStreamEvent.Status.processing)
.setRequest(getUssdRequestSdrData());
userUssdRequest = null;
} else {
UssdStreamEvent.Status.valueOf(external.toString().toUpperCase().replaceAll("-", "_"));
}
getContext().system()
.eventStream()
.publish(builder.build());
}
private String getUssdRequestSdrData(){
return userUssdRequest.getMessage().trim();
}
private abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
private final class Ringing extends AbstractAction {
public Ringing(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if (message instanceof SipServletRequest) {
invite = (SipServletRequest) message;
from = (SipURI) invite.getFrom().getURI();
to = (SipURI) invite.getTo().getURI();
timeout = -1;
direction = "inbound";
// Send a ringing response.
final SipServletResponse ringing = invite.createResponse(SipServletResponse.SC_RINGING);
ringing.send();
SipURI initialInetUri = getInitialIpAddressPort(invite);
if(initialInetUri != null)
invite.getSession().setAttribute("realInetUri", initialInetUri);
} else if (message instanceof SipServletResponse) {
final UntypedActorContext context = getContext();
context.setReceiveTimeout(Duration.Undefined());
}
// Notify the observers.
external = CallStateChanged.State.RINGING;
final CallStateChanged event = new CallStateChanged(external);
for (final ActorRef observer : observers) {
logger.info("Telling observers that state changed to RINGING");
observer.tell(event, source);
}
if (outgoingCallRecord != null && direction.contains("outbound")) {
outgoingCallRecord = outgoingCallRecord.setStatus(external.name());
callDetailrecordsDao.updateCallDetailRecord(outgoingCallRecord);
}
}
}
private final class InProgress extends AbstractAction {
public InProgress(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
final State state = fsm.state();
final SipServletResponse okay = invite.createResponse(SipServletResponse.SC_OK);
okay.send();
invite.getApplicationSession().setExpires(0);
// Notify the observers.
external = CallStateChanged.State.IN_PROGRESS;
final CallStateChanged event = new CallStateChanged(external);
for (final ActorRef observer : observers) {
observer.tell(event, source);
}
if (outgoingCallRecord != null && direction.contains("outbound")
&& !outgoingCallRecord.getStatus().equalsIgnoreCase("in_progress")) {
outgoingCallRecord = outgoingCallRecord.setStatus(external.name());
outgoingCallRecord = outgoingCallRecord.setAnsweredBy(to.getUser());
callDetailrecordsDao.updateCallDetailRecord(outgoingCallRecord);
}
}
}
private final class Ready extends AbstractAction {
public Ready(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
}
}
private final class ProcessingUssdMessage extends AbstractAction {
public ProcessingUssdMessage(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
UssdRestcommResponse ussdRequest = (UssdRestcommResponse) message;
SipSession session = null;
if (direction.equalsIgnoreCase("inbound")) {
session = invite.getSession();
} else {
session = outgoingInvite.getSession();
}
SipServletRequest request = null;
if(ussdRequest.getIsFinalMessage()) {
request = session.createRequest("BYE");
} else {
request = session.createRequest("INFO");
}
userUssdRequest = ussdRequest;
request.setContent(ussdRequest.createUssdPayload().toString().trim(), ussdContentType);
logger.info("Prepared request: \n"+request);
SipURI realInetUri = (SipURI) session.getAttribute("realInetUri");
if (realInetUri != null) {
logger.info("Using the real ip address of the sip client " + realInetUri.toString()
+ " as a request uri of the BYE request");
request.setRequestURI(realInetUri);
}
request.send();
if(ussdRequest.getIsFinalMessage())
fsm.transition(request, completed);
}
}
private final class Cancelling extends AbstractAction {
public Cancelling(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
logger.info("Cancelling the call");
SipServletRequest cancel = (SipServletRequest)message;
SipServletResponse requestTerminated = invite.createResponse(SipServletResponse.SC_REQUEST_TERMINATED);
// SipServletResponse requestTerminated = cancel.createResponse(SipServletResponse.SC_REQUEST_TERMINATED);
requestTerminated.send();
if (invite != null) {
invite.getSession().invalidate();
}
if (outgoingInvite != null) {
outgoingInvite.getSession().invalidate();
}
// Notify the observers.
external = CallStateChanged.State.CANCELED;
final CallStateChanged event = new CallStateChanged(external);
for (final ActorRef observer : observers) {
observer.tell(event, source);
}
if (outgoingCallRecord != null && direction.contains("outbound")) {
outgoingCallRecord = outgoingCallRecord.setStatus(CallStateChanged.State.CANCELED.name());
final DateTime now = DateTime.now();
outgoingCallRecord = outgoingCallRecord.setEndTime(now);
final int seconds = 0;
outgoingCallRecord = outgoingCallRecord.setDuration(seconds);
callDetailrecordsDao.updateCallDetailRecord(outgoingCallRecord);
}
logger.info("Call Cancelled");
}
}
private final class Disconnecting extends AbstractAction {
public Disconnecting(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
logger.info("Disconnecting the call");
SipServletRequest bye = (SipServletRequest)message;
SipServletResponse response = bye.createResponse(SipServletResponse.SC_OK);
response.send();
if (invite != null) {
invite.getSession().invalidate();
}
if (outgoingInvite != null) {
outgoingInvite.getSession().invalidate();
}
// Notify the observers.
external = CallStateChanged.State.CANCELED;
final CallStateChanged event = new CallStateChanged(external);
for (final ActorRef observer : observers) {
observer.tell(event, source);
}
if (outgoingCallRecord != null && direction.contains("outbound")) {
outgoingCallRecord = outgoingCallRecord.setStatus(CallStateChanged.State.CANCELED.name());
final DateTime now = DateTime.now();
outgoingCallRecord = outgoingCallRecord.setEndTime(now);
final int seconds = 0;
outgoingCallRecord = outgoingCallRecord.setDuration(seconds);
callDetailrecordsDao.updateCallDetailRecord(outgoingCallRecord);
}
logger.info("Call Disconnected");
}
}
private final class Completed extends AbstractAction {
public Completed(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
logger.info("Completing the call");
if (invite != null) {
invite.getSession().invalidate();
}
if (outgoingInvite != null) {
outgoingInvite.getSession().invalidate();
}
// Notify the observers.
external = CallStateChanged.State.COMPLETED;
final CallStateChanged event = new CallStateChanged(external);
for (final ActorRef observer : observers) {
observer.tell(event, source);
}
if (outgoingCallRecord != null && direction.contains("outbound")) {
outgoingCallRecord = outgoingCallRecord.setStatus(CallStateChanged.State.COMPLETED.name());
final DateTime now = DateTime.now();
outgoingCallRecord = outgoingCallRecord.setEndTime(now);
final int seconds = 0;
outgoingCallRecord = outgoingCallRecord.setDuration(seconds);
callDetailrecordsDao.updateCallDetailRecord(outgoingCallRecord);
}
logger.info("Call completed");
}
}
private final class Queued extends AbstractAction {
public Queued(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
final InitializeOutbound request = (InitializeOutbound) message;
name = request.name();
from = request.from();
to = request.to();
transport = (to.getTransportParam() != null) ? to.getTransportParam() : "udp";
apiVersion = request.apiVersion();
accountId = request.accountId();
username = request.username();
password = request.password();
type = request.type();
isFromApi = request.isFromApi();
callDetailrecordsDao = request.getDaoManager().getCallDetailRecordsDao();
String toHeaderString = to.toString();
if (toHeaderString.indexOf('?') != -1) {
// custom headers parsing for SIP Out
// https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
headers = new HashMap<String, String>();
// we keep only the to URI without the headers
to = (SipURI) factory.createURI(toHeaderString.substring(0, toHeaderString.lastIndexOf('?')));
String headersString = toHeaderString.substring(toHeaderString.lastIndexOf('?') + 1);
StringTokenizer tokenizer = new StringTokenizer(headersString, "&");
while (tokenizer.hasMoreTokens()) {
String headerNameValue = tokenizer.nextToken();
String headerName = headerNameValue.substring(0, headerNameValue.lastIndexOf('='));
String headerValue = headerNameValue.substring(headerNameValue.lastIndexOf('=') + 1);
headers.put(headerName, headerValue);
}
}
timeout = request.timeout();
if (request.isFromApi()) {
direction = OUTBOUND_API;
} else {
direction = OUTBOUND_DIAL;
}
// Notify the observers.
external = CallStateChanged.State.QUEUED;
final CallStateChanged event = new CallStateChanged(external);
for (final ActorRef observer : observers) {
observer.tell(event, source);
}
if (callDetailrecordsDao != null) {
final CallDetailRecord.Builder builder = CallDetailRecord.builder();
builder.setSid(id);
builder.setInstanceId(RestcommConfiguration.getInstance().getMain().getInstanceId());
builder.setDateCreated(created);
builder.setAccountSid(accountId);
builder.setTo(to.getUser());
builder.setCallerName(name);
String fromString = from.getUser() != null ? from.getUser() : "USSD REST API";
builder.setFrom(fromString);
// builder.setForwardedFrom(callInfo.forwardedFrom());
// builder.setPhoneNumberSid(phoneId);
builder.setStatus(external.name());
builder.setDirection("outbound-api");
builder.setApiVersion(apiVersion);
builder.setPrice(new BigDecimal("0.00"));
// TODO implement currency property to be read from Configuration
builder.setPriceUnit(Currency.getInstance("USD"));
final StringBuilder buffer = new StringBuilder();
buffer.append("/").append(apiVersion).append("/Accounts/");
buffer.append(accountId.toString()).append("/Calls/");
buffer.append(id.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
outgoingCallRecord = builder.build();
callDetailrecordsDao.addCallDetailRecord(outgoingCallRecord);
}
}
}
private final class Dialing extends AbstractAction {
public Dialing(final ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
UssdRestcommResponse ussdRequest = (UssdRestcommResponse) message;
final ActorRef self = self();
// Create a SIP invite to initiate a new session.
final StringBuilder buffer = new StringBuilder();
buffer.append(to.getHost());
if (to.getPort() > -1) {
buffer.append(":").append(to.getPort());
}
if (!transport.equalsIgnoreCase("udp")) {
buffer.append(";transport=").append(transport);
}
final SipURI uri = factory.createSipURI(null, buffer.toString());
final SipApplicationSession application = factory.createApplicationSession();
application.setAttribute("UssdCall","true");
application.setAttribute(UssdCall.class.getName(), self);
if(ussdInterpreter != null)
application.setAttribute(UssdInterpreter.class.getName(), ussdInterpreter);
outgoingInvite = factory.createRequest(application, "INVITE", from, to);
if (!transport.equalsIgnoreCase("udp")) {
((SipURI)outgoingInvite.getRequestURI()).setTransportParam(transport);
((SipURI)outgoingInvite.getFrom().getURI()).setTransportParam(transport);
((SipURI)outgoingInvite.getTo().getURI()).setTransportParam(transport);
}
outgoingInvite.pushRoute(uri);
if (headers != null) {
// adding custom headers for SIP Out
// https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
Set<Map.Entry<String, String>> entrySet = headers.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
outgoingInvite.addHeader("X-" + entry.getKey(), entry.getValue());
}
}
outgoingInvite.addHeader("X-RestComm-ApiVersion", apiVersion);
outgoingInvite.addHeader("X-RestComm-AccountSid", accountId.toString());
outgoingInvite.addHeader("X-RestComm-CallSid", id.toString());
final SipSession session = outgoingInvite.getSession();
session.setHandler("CallManager");
outgoingInvite.setContent(ussdRequest.createUssdPayload().toString(), ussdContentType);
// Send the invite.
outgoingInvite.send();
// Set the timeout period.
final UntypedActorContext context = getContext();
context.setReceiveTimeout(Duration.create(timeout, TimeUnit.SECONDS));
}
}
/* (non-Javadoc)
* @see akka.actor.UntypedActor#postStop()
*/
@Override
public void postStop() {
super.postStop();
}
}
| 32,660 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdCallManager.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/telephony/UssdCallManager.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.ussd.telephony;
import static javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES;
import static javax.servlet.sip.SipServletResponse.SC_BAD_REQUEST;
import static javax.servlet.sip.SipServletResponse.SC_FORBIDDEN;
import static javax.servlet.sip.SipServletResponse.SC_NOT_FOUND;
import static javax.servlet.sip.SipServletResponse.SC_OK;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;
import javax.servlet.sip.ServletParseException;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipURI;
import org.apache.commons.configuration.Configuration;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.core.service.RestcommConnectServiceProvider;
import org.restcomm.connect.core.service.util.UriUtils;
import org.restcomm.connect.core.service.api.NumberSelectorService;
import org.restcomm.connect.dao.AccountsDao;
import org.restcomm.connect.dao.ApplicationsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.common.OrganizationUtil;
import org.restcomm.connect.dao.entities.Account;
import org.restcomm.connect.dao.entities.Application;
import org.restcomm.connect.dao.entities.IncomingPhoneNumber;
import org.restcomm.connect.dao.entities.Notification;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionFeatureAccessRequest;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
import org.restcomm.connect.extension.controller.ExtensionController;
import org.restcomm.connect.http.client.rcmlserver.resolver.RcmlserverResolver;
import org.restcomm.connect.interpreter.SIPOrganizationUtil;
import org.restcomm.connect.interpreter.StartInterpreter;
import org.restcomm.connect.telephony.api.CallManagerResponse;
import org.restcomm.connect.telephony.api.CreateCall;
import org.restcomm.connect.telephony.api.ExecuteCallScript;
import org.restcomm.connect.telephony.api.FeatureAccessRequest;
import org.restcomm.connect.telephony.api.InitializeOutbound;
import org.restcomm.connect.telephony.api.util.CallControlHelper;
import org.restcomm.connect.ussd.interpreter.UssdInterpreter;
import org.restcomm.connect.ussd.interpreter.UssdInterpreterParams;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*/
public class UssdCallManager extends RestcommUntypedActor {
static final int ERROR_NOTIFICATION = 0;
static final int WARNING_NOTIFICATION = 1;
static final Pattern PATTERN = Pattern.compile("[\\*#0-9]{1,12}");
static final int ACCOUNT_NOT_ACTIVE_FAILURE_RESPONSE_CODE = SC_FORBIDDEN;
private final Configuration configuration;
private final ServletContext context;
private final SipFactory sipFactory;
private final DaoManager storage;
private final String ussdGatewayUri;
private final String ussdGatewayUsername;
private final String ussdGatewayPassword;
private final NumberSelectorService numberSelector;
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
//List of extensions for UssdCallManager
List<RestcommExtensionGeneric> extensions;
private CreateCall createCallRequest;
// configurable switch whether to use the To field in a SIP header to determine the callee address
// alternatively the Request URI can be used
private boolean useTo;
private UriUtils uriUtils;
/**
* @param configuration
* @param context
* @param factory
* @param storage
*/
public UssdCallManager(Configuration configuration, ServletContext context, SipFactory factory, DaoManager storage) {
super();
this.configuration = configuration;
this.context = context;
this.sipFactory = factory;
this.storage = storage;
final Configuration runtime = configuration.subset("runtime-settings");
final Configuration ussdGatewayConfig = runtime.subset("ussd-gateway");
this.ussdGatewayUri = ussdGatewayConfig.getString("ussd-gateway-uri");
this.ussdGatewayUsername = ussdGatewayConfig.getString("ussd-gateway-user");
this.ussdGatewayPassword = ussdGatewayConfig.getString("ussd-gateway-password");
numberSelector = (NumberSelectorService)context.getAttribute(NumberSelectorService.class.getName());
extensions = ExtensionController.getInstance().getExtensions(ExtensionType.FeatureAccessControl);
uriUtils = RestcommConnectServiceProvider.getInstance().uriUtils();
}
private ActorRef ussdCall() {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new UssdCall(sipFactory);
}
});
return getContext().actorOf(props);
}
private void check(final Object message) throws IOException {
final SipServletRequest request = (SipServletRequest) message;
if (request.getContentLength() == 0) {
String contentType = request.getContentType();
if (!("application/vnd.3gpp.ussd+xml".equals(contentType))) {
final SipServletResponse response = request.createResponse(SC_BAD_REQUEST);
response.send();
}
}
}
@Override
public void onReceive(final Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
if (message instanceof SipServletRequest) {
final SipServletRequest request = (SipServletRequest) message;
final String method = request.getMethod();
if ("INVITE".equalsIgnoreCase(method)) {
check(request);
invite(request);
} else if ("INFO".equalsIgnoreCase(method)) {
processRequest(request);
} else if ("ACK".equalsIgnoreCase(method)) {
processRequest(request);
} else if ("BYE".equalsIgnoreCase(method)) {
processRequest(request);
} else if ("CANCEL".equalsIgnoreCase(method)) {
processRequest(request);
}
} else if (message instanceof SipServletResponse) {
response(message);
} else if (CreateCall.class.equals(klass)) {
try {
this.createCallRequest = (CreateCall) message;
sender.tell(new CallManagerResponse<ActorRef>(outbound(message)), self);
} catch (final Exception exception) {
sender.tell(new CallManagerResponse<ActorRef>(exception), self);
}
} else if (ExecuteCallScript.class.equals(klass)) {
execute(message);
}
}
private void invite(final Object message) throws Exception {
final SipServletRequest request = (SipServletRequest) message;
// Make sure we handle re-invites properly.
if (!request.isInitial()) {
final SipServletResponse okay = request.createResponse(SC_OK);
okay.send();
return;
}
final AccountsDao accounts = storage.getAccountsDao();
final ApplicationsDao applications = storage.getApplicationsDao();
final String toUser = CallControlHelper.getUserSipId(request, useTo);
final SipURI fromUri = (SipURI) request.getFrom().getURI();
Sid sourceOrganizationSid = OrganizationUtil.getOrganizationSidBySipURIHost(storage, fromUri);
Sid destOrg = SIPOrganizationUtil.searchOrganizationBySIPRequest(storage.getOrganizationsDao(), request);
IncomingPhoneNumber number = getIncomingPhoneNumber(toUser, sourceOrganizationSid, destOrg);
if (number != null) {
Account numAccount = accounts.getAccount(number.getAccountSid());
if (!numAccount.getStatus().equals(Account.Status.ACTIVE)) {
//reject call since the number belongs to an an account which is not ACTIVE
final SipServletResponse response = request.createResponse(ACCOUNT_NOT_ACTIVE_FAILURE_RESPONSE_CODE, "Account is not Active");
response.send();
String msg = String.format("Restcomm rejects this USSD Session because number's %s account %s is not ACTIVE, current state %s", number.getPhoneNumber(), numAccount.getSid(), numAccount.getStatus());
if (logger.isDebugEnabled()) {
logger.debug(msg);
}
sendNotification(msg, 11005, "Error", true);
return;
}
}
if(logger.isDebugEnabled()) {
logger.debug("sourceOrganizationSid: " + sourceOrganizationSid);
}
if(sourceOrganizationSid == null){
logger.error("Null Organization: fromUri: "+fromUri);
}
if (redirectToHostedVoiceApp(request, accounts, applications, number)) {
return;
}
// We didn't find anyway to handle the call.
final SipServletResponse response = request.createResponse(SC_NOT_FOUND);
response.send();
}
private IncomingPhoneNumber getIncomingPhoneNumber(String phone, Sid sourceOrganizationSid, Sid destOrg) {
IncomingPhoneNumber number = numberSelector.searchNumber(phone, sourceOrganizationSid, destOrg);
return number;
}
/**
* Try to locate a hosted voice app corresponding to the callee/To address. If one is found, begin execution, otherwise
* return false;
*
* @param request
* @param accounts
* @param applications
* @throws Exception
*/
private boolean redirectToHostedVoiceApp(final SipServletRequest request, final AccountsDao accounts,
final ApplicationsDao applications, IncomingPhoneNumber number) throws Exception {
boolean isFoundHostedApp = false;
// This is a USSD Invite
if (number != null) {
ExtensionController ec = ExtensionController.getInstance();
IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.INBOUND_USSD, number.getAccountSid());
ExtensionResponse er = ec.executePreInboundAction(far, extensions);
if (er.isAllowed()) {
final UssdInterpreterParams.Builder builder = new UssdInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setAccount(number.getAccountSid());
builder.setVersion(number.getApiVersion());
final Account account = accounts.getAccount(number.getAccountSid());
builder.setEmailAddress(account.getEmailAddress());
final Sid sid = number.getUssdApplicationSid();
if (sid != null) {
final Application application = applications.getApplication(sid);
RcmlserverConfigurationSet rcmlserverConfig = RestcommConfiguration.getInstance().getRcmlserver();
RcmlserverResolver resolver = RcmlserverResolver.getInstance(rcmlserverConfig.getBaseUrl(), rcmlserverConfig.getApiPath());
builder.setUrl(uriUtils.resolve(resolver.resolveRelative(application.getRcmlUrl()), number.getAccountSid()));
} else {
builder.setUrl(uriUtils.resolve(number.getUssdUrl(), number.getAccountSid()));
}
final String ussdMethod = number.getUssdMethod();
if (ussdMethod == null || ussdMethod.isEmpty()) {
builder.setMethod("POST");
} else {
builder.setMethod(ussdMethod);
}
if (number.getUssdFallbackUrl() != null)
builder.setFallbackUrl(number.getUssdFallbackUrl());
builder.setFallbackMethod(number.getUssdFallbackMethod());
builder.setStatusCallback(number.getStatusCallback());
builder.setStatusCallbackMethod(number.getStatusCallbackMethod());
final Props props = UssdInterpreter.props(builder.build());
final ActorRef ussdInterpreter = getContext().actorOf(props);
final ActorRef ussdCall = ussdCall();
ussdCall.tell(request, self());
ussdInterpreter.tell(new StartInterpreter(ussdCall), self());
SipApplicationSession applicationSession = request.getApplicationSession();
applicationSession.setAttribute("UssdCall", "true");
applicationSession.setAttribute(UssdInterpreter.class.getName(), ussdInterpreter);
applicationSession.setAttribute(UssdCall.class.getName(), ussdCall);
isFoundHostedApp = true;
ec.executePostInboundAction(far, extensions);
} else {
if (logger.isDebugEnabled()) {
final String errMsg = "Inbound USSD session is not Allowed";
logger.debug(errMsg);
}
String errMsg = "Inbound USSD session to Number: " + number.getPhoneNumber()
+ " is not allowed";
sendNotification(errMsg, 11001, "warning", true);
final SipServletResponse resp = request.createResponse(SC_FORBIDDEN, "Inbound USSD session is not Allowed");
resp.send();
ec.executePostInboundAction(far, extensions);
return false;
}
} else {
logger.info("USSD Number registration NOT FOUND");
request.createResponse(SipServletResponse.SC_NOT_FOUND).send();
}
return isFoundHostedApp;
}
private void sendNotification(String errMessage, int errCode, String errType, boolean createNotification) {
NotificationsDao notifications = storage.getNotificationsDao();
Notification notification;
if (errType == "warning") {
logger.warning(errMessage); // send message to console
if (createNotification) {
notification = notification(WARNING_NOTIFICATION, errCode, errMessage);
notifications.addNotification(notification);
}
} else if (errType == "error") {
logger.error(errMessage); // send message to console
if (createNotification) {
notification = notification(ERROR_NOTIFICATION, errCode, errMessage);
notifications.addNotification(notification);
}
} else if (errType == "info") {
if(logger.isInfoEnabled()) {
logger.info(errMessage); // send message to console
}
}
}
private Notification notification(final int log, final int error, final String message) {
String version = configuration.subset("runtime-settings").getString("api-version");
Sid accountId = new Sid("ACae6e420f425248d6a26948c17a9e2acf");
// Sid callSid = new Sid("CA00000000000000000000000000000000");
final Notification.Builder builder = Notification.builder();
final Sid sid = Sid.generate(Sid.Type.NOTIFICATION);
builder.setSid(sid);
// builder.setAccountSid(accountId);
builder.setAccountSid(accountId);
// builder.setCallSid(callSid);
builder.setApiVersion(version);
builder.setLog(log);
builder.setErrorCode(error);
final String base = configuration.subset("runtime-settings").getString("error-dictionary-uri");
StringBuilder buffer = new StringBuilder();
buffer.append(base);
if (!base.endsWith("/")) {
buffer.append("/");
}
buffer.append(error).append(".html");
final URI info = URI.create(buffer.toString());
builder.setMoreInfo(info);
builder.setMessageText(message);
final DateTime now = DateTime.now();
builder.setMessageDate(now);
try {
builder.setRequestUrl(new URI(""));
} catch (URISyntaxException e) {
e.printStackTrace();
}
/**
* if (response != null) { builder.setRequestUrl(request.getUri()); builder.setRequestMethod(request.getMethod());
* builder.setRequestVariables(request.getParametersAsString()); }
**/
builder.setRequestMethod("");
builder.setRequestVariables("");
buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/Notifications/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
return builder.build();
}
private void processRequest(SipServletRequest request) throws IOException {
final ActorRef ussdInterpreter = (ActorRef) request.getApplicationSession().getAttribute(UssdInterpreter.class.getName());
if (ussdInterpreter != null) {
logger.info("Dispatching Request: " + request.getMethod() + " to UssdInterpreter: " + ussdInterpreter);
ussdInterpreter.tell(request, self());
} else {
final SipServletResponse notFound = request.createResponse(SipServletResponse.SC_NOT_FOUND);
notFound.send();
}
}
private ActorRef outbound(final Object message) throws ServletParseException {
final CreateCall request = (CreateCall) message;
final Configuration runtime = configuration.subset("runtime-settings");
final String uri = ussdGatewayUri;
final String ussdUsername = (request.username() != null) ? request.username() : ussdGatewayUsername;
final String ussdPassword = (request.password() != null) ? request.password() : ussdGatewayPassword;
SipURI from = (SipURI) sipFactory.createSipURI(request.from(), uri);
SipURI to = (SipURI) sipFactory.createSipURI(request.to(), uri);
String transport = (to.getTransportParam() != null) ? to.getTransportParam() : "udp";
//from = outboundInterface(transport);
SipURI obi = outboundInterface(transport);
from = (obi == null) ? from : obi;
final ActorRef ussdCall = ussdCall();
final ActorRef self = self();
final InitializeOutbound init = new InitializeOutbound(null, from, to, ussdUsername, ussdPassword, request.timeout(),
request.isFromApi(), runtime.getString("api-version"), request.accountId(), request.type(), storage, false);
ussdCall.tell(init, self);
return ussdCall;
}
private SipURI outboundInterface(String transport) {
SipURI result = null;
@SuppressWarnings("unchecked") final List<SipURI> uris = (List<SipURI>) context.getAttribute(OUTBOUND_INTERFACES);
for (final SipURI uri : uris) {
final String interfaceTransport = uri.getTransportParam();
if (transport.equalsIgnoreCase(interfaceTransport)) {
result = uri;
}
}
return result;
}
private void execute(final Object message) {
final ExecuteCallScript request = (ExecuteCallScript) message;
final ActorRef self = self();
final UssdInterpreterParams.Builder builder = new UssdInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setAccount(request.account());
builder.setVersion(request.version());
builder.setUrl(request.url());
builder.setMethod(request.method());
builder.setFallbackUrl(request.fallbackUrl());
builder.setFallbackMethod(request.fallbackMethod());
final Props props = UssdInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
interpreter.tell(new StartInterpreter(request.call()), self);
}
public void response(final Object message) throws IOException {
final ActorRef self = self();
final SipServletResponse response = (SipServletResponse) message;
final SipApplicationSession application = response.getApplicationSession();
if (application.isValid()) {
// otherwise the response is coming back to a Voice app hosted by Restcomm
final ActorRef ussdCall = (ActorRef) application.getAttribute(UssdCall.class.getName());
ussdCall.tell(response, self);
} else {
if(logger.isErrorEnabled()){
logger.debug("Application invalid "+ message.toString());
}
}
}
}
| 22,402 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdCollect.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/telephony/api/UssdCollect.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.ussd.telephony.api;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected]
*/
@Immutable
public final class UssdCollect {
private final String ussdMessage;
public UssdCollect(final String ussdMessage) {
super();
this.ussdMessage = ussdMessage;
}
public String ussdMessage() {
return ussdMessage;
}
}
| 1,239 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdInterpreter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/interpreter/UssdInterpreter.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.ussd.interpreter;
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 org.apache.commons.configuration.Configuration;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.dao.Sid;
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.telephony.CreateCallType;
import org.restcomm.connect.core.service.RestcommConnectServiceProvider;
import org.restcomm.connect.core.service.util.UriUtils;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.dao.entities.Notification;
import org.restcomm.connect.email.EmailService;
import org.restcomm.connect.email.api.EmailRequest;
import org.restcomm.connect.email.api.Mail;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionFeatureAccessRequest;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
import org.restcomm.connect.extension.controller.ExtensionController;
import org.restcomm.connect.http.client.Downloader;
import org.restcomm.connect.http.client.DownloaderResponse;
import org.restcomm.connect.http.client.HttpRequestDescriptor;
import org.restcomm.connect.http.client.HttpResponseDescriptor;
import org.restcomm.connect.interpreter.StartInterpreter;
import org.restcomm.connect.interpreter.StopInterpreter;
import org.restcomm.connect.interpreter.rcml.Attribute;
import org.restcomm.connect.interpreter.rcml.End;
import org.restcomm.connect.interpreter.rcml.GetNextVerb;
import org.restcomm.connect.interpreter.rcml.Parser;
import org.restcomm.connect.interpreter.rcml.ParserFailed;
import org.restcomm.connect.interpreter.rcml.Tag;
import org.restcomm.connect.telephony.api.Answer;
import org.restcomm.connect.telephony.api.CallInfo;
import org.restcomm.connect.telephony.api.CallResponse;
import org.restcomm.connect.telephony.api.CallStateChanged;
import org.restcomm.connect.telephony.api.FeatureAccessRequest;
import org.restcomm.connect.telephony.api.GetCallInfo;
import org.restcomm.connect.ussd.commons.UssdInfoRequest;
import org.restcomm.connect.ussd.commons.UssdMessageType;
import org.restcomm.connect.ussd.commons.UssdRestcommResponse;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Currency;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Pattern;
import static org.restcomm.connect.interpreter.rcml.Verbs.ussdCollect;
import static org.restcomm.connect.interpreter.rcml.Verbs.ussdLanguage;
import static org.restcomm.connect.interpreter.rcml.Verbs.ussdMessage;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*/
public class UssdInterpreter extends RestcommUntypedActor {
// Logger.
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
static final int ERROR_NOTIFICATION = 0;
static final int WARNING_NOTIFICATION = 1;
static final Pattern PATTERN = Pattern.compile("[\\*#0-9]{1,12}");
static String EMAIL_SENDER;
// States for the FSM.
// ==========================
final State uninitialized;
final State observeCall;
final State acquiringCallInfo;
final State disconnecting;
final State cancelling;
final State finished;
private final State preparingMessage;
private final State processingInfoRequest;
// FSM.
FiniteStateMachine fsm = null;
// Information to reach the application that will be executed
// by this interpreter.
Sid accountId;
Sid phoneId;
String version;
URI statusCallback;
String statusCallbackMethod;
String emailAddress;
ActorRef ussdCall = null;
CallInfo callInfo = null;
// State for outbound calls.
ActorRef outboundCall = null;
CallInfo outboundCallInfo = null;
// The call state.
CallStateChanged.State callState = null;
// A call detail record.
CallDetailRecord callRecord = null;
ActorRef downloader = null;
// application data.
HttpRequestDescriptor request;
HttpResponseDescriptor response;
// The RCML parser.
ActorRef parser;
Tag verb;
DaoManager storage = null;
final Set<Transition> transitions = new HashSet<Transition>();
ActorRef mailerNotify = null;
URI url;
String method;
URI fallbackUrl;
String fallbackMethod;
Tag ussdLanguageTag = null;
int maxMessageLength;
private final int englishLength = 182;
private final int nonEnglishLength = 80;
Queue<Tag> ussdMessageTags = new LinkedBlockingQueue<Tag>();
Tag ussdCollectTag = null;
String ussdCollectAction = "";
Configuration configuration = null;
private final State downloadingRcml;
private final State downloadingFallbackRcml;
private final State ready;
private final State notFound;
private boolean receivedBye;
private boolean sentBye;
//List of extensions for UssdInterpreter
List<RestcommExtensionGeneric> extensions;
private UriUtils uriUtils;
public UssdInterpreter(final UssdInterpreterParams params) {
super();
final ActorRef source = self();
uninitialized = new State("uninitialized", null, null);
observeCall = new State("observe call", new ObserveCall(source), null);
acquiringCallInfo = new State("acquiring call info", new AcquiringCallInfo(source), null);
downloadingRcml = new State("downloading rcml", new DownloadingRcml(source), null);
downloadingFallbackRcml = new State("downloading fallback rcml", new DownloadingFallbackRcml(source), null);
preparingMessage = new State("Preparing message", new PreparingMessage(source), null);
processingInfoRequest = new State("Processing info request from client", new ProcessingInfoRequest(source), null);
ready = new State("ready", new Ready(source), null);
notFound = new State("notFound", new NotFound(source), null);
cancelling = new State("Cancelling", new Cancelling(source), null);
disconnecting = new State("Disconnecting", new Disconnecting(source), null);
finished = new State("finished", new Finished(source), null);
transitions.add(new Transition(uninitialized, acquiringCallInfo));
transitions.add(new Transition(uninitialized, cancelling));
transitions.add(new Transition(acquiringCallInfo, downloadingRcml));
transitions.add(new Transition(acquiringCallInfo, cancelling));
transitions.add(new Transition(downloadingRcml, ready));
transitions.add(new Transition(downloadingRcml, cancelling));
transitions.add(new Transition(downloadingRcml, notFound));
transitions.add(new Transition(downloadingRcml, downloadingFallbackRcml));//??????
transitions.add(new Transition(downloadingRcml, finished));
transitions.add(new Transition(downloadingRcml, ready));//redundant
transitions.add(new Transition(ready, preparingMessage));
transitions.add(new Transition(preparingMessage, downloadingRcml));
transitions.add(new Transition(preparingMessage, processingInfoRequest));
transitions.add(new Transition(preparingMessage, disconnecting));
transitions.add(new Transition(preparingMessage, finished));
transitions.add(new Transition(processingInfoRequest, preparingMessage));
transitions.add(new Transition(processingInfoRequest, ready));
transitions.add(new Transition(processingInfoRequest, finished));
transitions.add(new Transition(processingInfoRequest, disconnecting));
transitions.add(new Transition(processingInfoRequest, cancelling));
transitions.add(new Transition(processingInfoRequest, notFound));
transitions.add(new Transition(disconnecting, finished));
// Initialize the FSM.
this.fsm = new FiniteStateMachine(uninitialized, transitions);
// Initialize the runtime stuff.
this.accountId = params.getAccount();
this.phoneId = params.getPhone();
this.version = params.getVersion();
this.url = params.getUrl();
this.method = params.getMethod();
this.fallbackUrl = params.getFallbackUrl();
this.fallbackMethod = params.getFallbackMethod();
this.statusCallback = params.getStatusCallback();
this.statusCallbackMethod = params.getStatusCallbackMethod();
this.emailAddress = params.getEmailAddress();
this.configuration = params.getConfiguration();
this.storage = params.getStorage();
final Configuration runtime = configuration.subset("runtime-settings");
String path = runtime.getString("cache-path");
if (!path.endsWith("/")) {
path = path + "/";
}
path = path + accountId.toString();
this.downloader = downloader();
receivedBye = false;
sentBye = false;
extensions = ExtensionController.getInstance().getExtensions(ExtensionType.FeatureAccessControl);
uriUtils = RestcommConnectServiceProvider.getInstance().uriUtils();
}
public static Props props(final UssdInterpreterParams params) {
return new Props(new UntypedActorFactory() {
@Override
public Actor create() throws Exception {
return new UssdInterpreter(params);
}
});
}
private Notification notification(final int log, final int error, final String message) {
final Notification.Builder builder = Notification.builder();
final Sid sid = Sid.generate(Sid.Type.NOTIFICATION);
builder.setSid(sid);
builder.setAccountSid(accountId);
builder.setCallSid(callInfo.sid());
builder.setApiVersion(version);
builder.setLog(log);
builder.setErrorCode(error);
final String base = configuration.subset("runtime-settings").getString("error-dictionary-uri");
StringBuilder buffer = new StringBuilder();
buffer.append(base);
if (!base.endsWith("/")) {
buffer.append("/");
}
buffer.append(error).append(".html");
final URI info = URI.create(buffer.toString());
builder.setMoreInfo(info);
builder.setMessageText(message);
final DateTime now = DateTime.now();
builder.setMessageDate(now);
if (request != null) {
builder.setRequestUrl(request.getUri());
builder.setRequestMethod(request.getMethod());
builder.setRequestVariables(request.getParametersAsString());
}
if (response != null) {
builder.setResponseHeaders(response.getHeadersAsString());
final String type = response.getContentType();
if (type.contains("text/xml") || type.contains("application/xml") || type.contains("text/html")) {
try {
builder.setResponseBody(response.getContentAsString());
} catch (final IOException exception) {
logger.error(
"There was an error while reading the contents of the resource " + "located @ " + url.toString(),
exception);
}
}
}
buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/Notifications/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
return builder.build();
}
ActorRef mailer(final Configuration configuration) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public Actor create() throws Exception {
return new EmailService(configuration);
}
});
return getContext().actorOf(props);
}
ActorRef downloader() {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new Downloader();
}
});
return getContext().actorOf(props);
}
ActorRef parser(final String xml) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new Parser(xml, self());
}
});
return getContext().actorOf(props);
}
void invalidVerb(final Tag verb) {
final ActorRef self = self();
// Get the next verb.
final GetNextVerb next = new GetNextVerb();
parser.tell(next, self);
}
List<NameValuePair> parameters() {
CallInfo info = null;
if (callInfo != null) {
info = callInfo;
} else if (outboundCallInfo != null){
info = outboundCallInfo;
}
if (info != null) {
final List<NameValuePair> parameters = new ArrayList<NameValuePair>();
final String callSid = info.sid().toString();
parameters.add(new BasicNameValuePair("CallSid", callSid));
final String accountSid = accountId.toString();
parameters.add(new BasicNameValuePair("AccountSid", accountSid));
final String from = (info.from());
parameters.add(new BasicNameValuePair("From", from));
final String to = (info.to());
parameters.add(new BasicNameValuePair("To", to));
if (callState == null)
callState = info.state();
final String state = callState.toString();
parameters.add(new BasicNameValuePair("CallStatus", state));
parameters.add(new BasicNameValuePair("ApiVersion", version));
final String direction = info.direction();
parameters.add(new BasicNameValuePair("Direction", direction));
final String callerName = info.fromName();
parameters.add(new BasicNameValuePair("CallerName", callerName));
final String forwardedFrom = info.forwardedFrom();
parameters.add(new BasicNameValuePair("ForwardedFrom", forwardedFrom));
// logger.info("Type " + callInfo.type());
if (CreateCallType.SIP == info.type()) {
// Adding SIP OUT Headers and SipCallId for
// https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out
SipServletResponse lastResponse = info.lastResponse();
// logger.info("lastResponse " + lastResponse);
if (lastResponse != null) {
final int statusCode = lastResponse.getStatus();
final String method = lastResponse.getMethod();
// See https://www.twilio.com/docs/sip/receiving-sip-headers
// Headers on the final SIP response message (any 4xx or 5xx message or the final BYE/200) are posted to the
// Dial action URL.
if ((statusCode >= 400 && "INVITE".equalsIgnoreCase(method))
|| (statusCode >= 200 && statusCode < 300 && "BYE".equalsIgnoreCase(method))) {
final String sipCallId = lastResponse.getCallId();
parameters.add(new BasicNameValuePair("DialSipCallId", sipCallId));
parameters.add(new BasicNameValuePair("DialSipResponseCode", "" + statusCode));
Iterator<String> headerIt = lastResponse.getHeaderNames();
while (headerIt.hasNext()) {
String headerName = headerIt.next();
if (headerName.startsWith("X-")) {
parameters.add(new BasicNameValuePair("DialSipHeader_" + headerName, lastResponse
.getHeader(headerName)));
}
}
}
}
}
return parameters;
} else {
return null;
}
}
void sendMail(final Notification notification) {
if (emailAddress == null || emailAddress.isEmpty()) {
return;
}
final String EMAIL_SUBJECT = "RestComm Error Notification - Attention Required";
final StringBuilder buffer = new StringBuilder();
buffer.append("<strong>").append("Sid: ").append("</strong></br>");
buffer.append(notification.getSid().toString()).append("</br>");
buffer.append("<strong>").append("Account Sid: ").append("</strong></br>");
buffer.append(notification.getAccountSid().toString()).append("</br>");
buffer.append("<strong>").append("Call Sid: ").append("</strong></br>");
buffer.append(notification.getCallSid().toString()).append("</br>");
buffer.append("<strong>").append("API Version: ").append("</strong></br>");
buffer.append(notification.getApiVersion()).append("</br>");
buffer.append("<strong>").append("Log: ").append("</strong></br>");
buffer.append(notification.getLog() == ERROR_NOTIFICATION ? "ERROR" : "WARNING").append("</br>");
buffer.append("<strong>").append("Error Code: ").append("</strong></br>");
buffer.append(notification.getErrorCode()).append("</br>");
buffer.append("<strong>").append("More Information: ").append("</strong></br>");
buffer.append(notification.getMoreInfo().toString()).append("</br>");
buffer.append("<strong>").append("Message Text: ").append("</strong></br>");
buffer.append(notification.getMessageText()).append("</br>");
buffer.append("<strong>").append("Message Date: ").append("</strong></br>");
buffer.append(notification.getMessageDate().toString()).append("</br>");
buffer.append("<strong>").append("Request URL: ").append("</strong></br>");
buffer.append(notification.getRequestUrl().toString()).append("</br>");
buffer.append("<strong>").append("Request Method: ").append("</strong></br>");
buffer.append(notification.getRequestMethod()).append("</br>");
buffer.append("<strong>").append("Request Variables: ").append("</strong></br>");
buffer.append(notification.getRequestVariables()).append("</br>");
buffer.append("<strong>").append("Response Headers: ").append("</strong></br>");
buffer.append(notification.getResponseHeaders()).append("</br>");
buffer.append("<strong>").append("Response Body: ").append("</strong></br>");
buffer.append(notification.getResponseBody()).append("</br>");
final Mail emailMsg = new Mail(EMAIL_SENDER,emailAddress,EMAIL_SUBJECT, buffer.toString());
if (mailerNotify == null){
mailerNotify = mailer(configuration.subset("smtp-notify"));
}
mailerNotify.tell(new EmailRequest(emailMsg), self());
}
void callback() {
if (statusCallback != null) {
if (statusCallbackMethod == null) {
statusCallbackMethod = "POST";
}
final List<NameValuePair> parameters = parameters();
request = new HttpRequestDescriptor(statusCallback, statusCallbackMethod, parameters);
downloader.tell(request, null);
}
}
@Override
public void onReceive(final Object message) throws Exception {
final Class<?> klass = message.getClass();
final State state = fsm.state();
final ActorRef sender = sender();
final ActorRef source = self();
if (logger.isInfoEnabled()) {
logger.info(" ********** UssdInterpreter's Current State: " + state.toString());
logger.info(" ********** UssdInterpreter's Processing Message: " + klass.getName());
}
if (StartInterpreter.class.equals(klass)) {
ussdCall = ((StartInterpreter) message).resource();
fsm.transition(message, acquiringCallInfo);
} else if (message instanceof SipServletRequest) {
SipServletRequest request = (SipServletRequest) message;
String method = request.getMethod();
if ("INFO".equalsIgnoreCase(method)) {
fsm.transition(message, processingInfoRequest);
} else if ("ACK".equalsIgnoreCase(method)) {
fsm.transition(message, downloadingRcml);
} else if ("BYE".equalsIgnoreCase(method)) {
receivedBye = true;
fsm.transition(message, disconnecting);
} else if ("CANCEL".equalsIgnoreCase(method)) {
fsm.transition(message, cancelling);
}
} else if (CallStateChanged.class.equals(klass)) {
final CallStateChanged event = (CallStateChanged) message;
callState = event.state();
if (CallStateChanged.State.RINGING == event.state()) {
if(logger.isInfoEnabled()) {
logger.info("CallStateChanged.State.RINGING");
}
} else if (CallStateChanged.State.IN_PROGRESS == event.state()) {
if(logger.isInfoEnabled()) {
logger.info("CallStateChanged.State.IN_PROGRESS");
}
} else if (CallStateChanged.State.NO_ANSWER == event.state() || CallStateChanged.State.COMPLETED == event.state()
|| CallStateChanged.State.FAILED == event.state() || CallStateChanged.State.CANCELED == event.state()) {
if(logger.isInfoEnabled()) {
logger.info("CallStateChanged.State.NO_ANSWER OR CallStateChanged.State.COMPLETED OR CallStateChanged.State.FAILED or CallStateChanged.State.CANCELED");
}
fsm.transition(message, finished);
} else if (CallStateChanged.State.BUSY == event.state()) {
if(logger.isInfoEnabled()) {
logger.info("CallStateChanged.State.BUSY");
}
}
// else if (CallStateChanged.State.COMPLETED == event.state()) {
// logger.info("CallStateChanged.State.Completed");
// fsm.transition(message, finished);
// }
} else if (CallResponse.class.equals(klass)) {
if (acquiringCallInfo.equals(state)) {
@SuppressWarnings("unchecked")
final CallResponse<CallInfo> response = (CallResponse<CallInfo>) message;
// Check from whom is the message (initial call or outbound call) and update info accordingly
if( response.get().direction().contains("inbound") ){
callInfo = response.get();
ussdCall.tell(new Answer(callInfo.sid()), source);
}
else if ("outbound-api".equals(response.get().direction())){
outboundCallInfo = response.get();
fsm.transition(message, downloadingRcml);
}else{
logger.debug("direction doesn't match inbound or outbound, : " + response.get().direction().toString() );
}
/* if (sender == ussdCall) {
callInfo = response.get();
} else {
outboundCallInfo = response.get();
}
final String direction = callInfo.direction();
if ("inbound".equals(direction)) {
ussdCall.tell(new Answer(callInfo.sid()), source);
// fsm.transition(message, downloadingRcml);
} else {
fsm.transition(message, downloadingRcml);
// fsm.transition(message, initializingCall);
}*/
}
} else if (DownloaderResponse.class.equals(klass)) {
final DownloaderResponse response = (DownloaderResponse) message;
if (logger.isDebugEnabled()) {
logger.debug("Rcml DownloaderResponse success=" + response.succeeded());
}
//FIXME: what if these ifblocks arent in downloadingRcml?
if (response.succeeded()) {
int sc = response.get().getStatusCode();
//processingInfoRequest
if (logger.isDebugEnabled()) {
logger.debug("Rcml DownloaderResponse URI : " + response.get().getURI()
+ ", statusCode=" + response.get().getStatusCode()+" state="+state);
}
if(HttpStatus.SC_OK == sc){
fsm.transition(message, ready);
} else if (HttpStatus.SC_NOT_FOUND == sc){
fsm.transition(message, notFound);
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("Rcml DownloaderResponse error : " + response.error()
+ ", cause=" +
((response.cause() != null) ? response.cause().getMessage() : ""));
}
if (downloadingRcml.equals(state) && fallbackUrl!=null) {
fsm.transition(message, downloadingFallbackRcml);
} else {
//unexpected response
if(!sentBye && !receivedBye){
sendBye("UssdInterpreter Stopping. Unexpected State when receiving DownloaderResponse " + response.error());
sentBye = true;
}
fsm.transition(message, finished);
}
}
} else if (ParserFailed.class.equals(klass)) {
if(logger.isInfoEnabled()) {
logger.info("ParserFailed received. Will stop the call");
}
fsm.transition(message, cancelling);
} else if (Tag.class.equals(klass)) {
final Tag verb = (Tag) message;
ExtensionController ec = ExtensionController.getInstance();
IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.OUTBOUND_USSD, accountId);
ExtensionResponse er = ec.executePreOutboundAction(far, extensions);
if (!er.isAllowed()) {
if (logger.isDebugEnabled()) {
final String errMsg = "Outbound USSD session is not Allowed";
logger.debug(errMsg);
}
String errMsg = "Outbound USSD session is not Allowed";
final Notification notification = notification(WARNING_NOTIFICATION, 11001, errMsg);
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
sendBye(errMsg);
ec.executePostOutboundAction(far, extensions);
return;
}
if (ussdLanguage.equals(verb.name())) {
if (ussdLanguageTag == null) {
ussdLanguageTag = verb;
final GetNextVerb next = new GetNextVerb();
parser.tell(next, source);
} else {
// We support only one Language element
invalidVerb(verb);
}
return;
} else if (ussdMessage.equals(verb.name())) {
ussdMessageTags.add(verb);
final GetNextVerb next = new GetNextVerb();
parser.tell(next, source);
return;
} else if (ussdCollect.equals(verb.name())) {
if (ussdCollectTag == null) {
ussdCollectTag = verb;
final GetNextVerb next = new GetNextVerb();
parser.tell(next, source);
} else {
// We support only one Collect element
invalidVerb(verb);
}
return;
} else {
invalidVerb(verb);
}
} else if (End.class.equals(klass)) {
fsm.transition(message, preparingMessage);
}
}
private void sendBye(String message) {
CallInfo info = null;
if (callInfo != null) {
info = callInfo;
} else if (outboundCallInfo != null){
info = outboundCallInfo;
}
if (info != null) {
final SipSession session = info.invite().getSession();
final String sessionState = session.getState().name();
if (sessionState == SipSession.State.TERMINATED.name()) {
if (logger.isInfoEnabled()) {
logger.info("SipSession already TERMINATED, will not send BYE");
}
return;
} else {
if (logger.isInfoEnabled()) {
logger.info("About to send BYE, session state: " + sessionState);
}
}
final SipServletRequest bye = session.createRequest("BYE");
try {
bye.addHeader("Reason",message);
bye.send();
} catch (Exception e) {
if(logger.isErrorEnabled()){
logger.error("Error sending BYE "+e.getMessage());
}
}
}
}
abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
final class ObserveCall extends AbstractAction {
public ObserveCall(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
ussdCall.tell(new Observe(source), source);
}
}
final class AcquiringCallInfo extends AbstractAction {
public AcquiringCallInfo(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Acquiring Call Info");
}
ussdCall.tell(new Observe(source), source);
ussdCall.tell(new GetCallInfo(), source);
}
}
private final class DownloadingRcml extends AbstractAction {
public DownloadingRcml(final ActorRef source) {
super(source);
}
@SuppressWarnings("unchecked")
@Override
public void execute(final Object message) throws Exception {
if (callInfo != null) {
final CallDetailRecordsDao records = storage.getCallDetailRecordsDao();
final CallDetailRecord.Builder builder = CallDetailRecord.builder();
builder.setSid(callInfo.sid());
builder.setInstanceId(RestcommConfiguration.getInstance().getMain().getInstanceId());
builder.setDateCreated(callInfo.dateCreated());
builder.setAccountSid(accountId);
builder.setTo(callInfo.to());
builder.setCallerName(callInfo.fromName());
builder.setFrom(callInfo.from());
builder.setForwardedFrom(callInfo.forwardedFrom());
builder.setPhoneNumberSid(phoneId);
builder.setStatus(callState.toString());
final DateTime now = DateTime.now();
builder.setStartTime(now);
builder.setDirection(callInfo.direction());
builder.setApiVersion(version);
builder.setPrice(new BigDecimal("0.00"));
// TODO implement currency property to be read from Configuration
builder.setPriceUnit(Currency.getInstance("USD"));
final StringBuilder buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/Calls/");
buffer.append(callInfo.sid().toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
builder.setCallPath(ussdCall.path().toString());
callRecord = builder.build();
records.addCallDetailRecord(callRecord);
}
// Update the application.
callback();
// Ask the downloader to get us the application that will be executed.
final List<NameValuePair> parameters = parameters();
request = new HttpRequestDescriptor(url, method, parameters);
downloader.tell(request, source);
}
}
private final class DownloadingFallbackRcml extends AbstractAction {
public DownloadingFallbackRcml(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Downloading Fallback RCML");
}
final Class<?> klass = message.getClass();
// Notify the account of the issue.
if (DownloaderResponse.class.equals(klass)) {
final DownloaderResponse result = (DownloaderResponse) message;
final Throwable cause = result.cause();
Notification notification = null;
if (cause instanceof ClientProtocolException) {
notification = notification(ERROR_NOTIFICATION, 11206, cause.getMessage());
} else if (cause instanceof IOException) {
notification = notification(ERROR_NOTIFICATION, 11205, cause.getMessage());
} else if (cause instanceof URISyntaxException) {
notification = notification(ERROR_NOTIFICATION, 11100, cause.getMessage());
}
if (notification != null) {
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
sendMail(notification);
}
}
// Try to use the fall back url and method.
final List<NameValuePair> parameters = parameters();
request = new HttpRequestDescriptor(fallbackUrl, fallbackMethod, parameters);
downloader.tell(request, source);
}
}
private final class Ready extends AbstractAction {
public Ready(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("In Ready state");
}
// ussdCall.tell(new Answer(), source);
// Execute the received RCML here
final UntypedActorContext context = getContext();
final State state = fsm.state();
if (downloadingRcml.equals(state) || downloadingFallbackRcml.equals(state) || processingInfoRequest.equals(state)) {
response = ((DownloaderResponse) message).get();
if (parser != null) {
context.stop(parser);
parser = null;
}
final String type = response.getContentType();
if (type.contains("text/xml") || type.contains("application/xml") || type.contains("text/html")) {
parser = parser(response.getContentAsString());
} else if (type.contains("text/plain")) {
parser = parser("<UssdMessage>" + response.getContentAsString() + "</UssdMessage>");
} else {
final StopInterpreter stop = new StopInterpreter();
source.tell(stop, source);
return;
}
}
final GetNextVerb next = new GetNextVerb();
parser.tell(next, source);
}
}
private final class NotFound extends AbstractAction {
public NotFound(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("In Not Found State");
}
final DownloaderResponse response = (DownloaderResponse) message;
if (logger.isDebugEnabled()) {
logger.debug("response succeeded " + response.succeeded() + ", statusCode " + response.get().getStatusCode());
}
final Notification notification = notification(WARNING_NOTIFICATION, 21402, "URL Not Found : "
+ response.get().getURI());
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
// Hang up the call.
ussdCall.tell(new org.restcomm.connect.telephony.api.NotFound(), source);
}
}
// RCML END received, construct the USSD Message and ask UssdCall to send it
private final class PreparingMessage extends AbstractAction {
public PreparingMessage(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Preparing the USSD Message");
}
if (End.class.equals(message.getClass())) {
Boolean hasCollect = false;
UssdRestcommResponse ussdRestcommResponse = new UssdRestcommResponse();
String language = "";
if (ussdLanguageTag == null) {
language = "en";
ussdRestcommResponse.setLanguage(language);
} else {
language = ussdLanguageTag.text();
ussdRestcommResponse.setLanguage(language);
}
if (language.equalsIgnoreCase("en")) {
maxMessageLength = englishLength;
ussdRestcommResponse.setMessageLength(englishLength);
} else {
maxMessageLength = nonEnglishLength;
ussdRestcommResponse.setMessageLength(nonEnglishLength);
}
StringBuffer ussdText = processUssdMessageTags(ussdMessageTags);
if (ussdCollectTag != null) {
hasCollect = true;
ussdCollectAction = ussdCollectTag.attribute("action").value();
ussdRestcommResponse.setUssdCollectAction(ussdCollectAction);
Queue<Tag> children = new java.util.concurrent.ConcurrentLinkedQueue<Tag>(ussdCollectTag.children());
if (children != null && children.size() > 0) {
ussdText.append(processUssdMessageTags(children));
} else if (ussdCollectTag.text() != null) {
ussdText.append(ussdCollectTag.text());
}
}
if (ussdText.length() > maxMessageLength) {
final String errorString = "Error while preparing the USSD response. Ussd text length more "
+ "than the permitted for the selected language: "+maxMessageLength;
Notification notification = notification(ERROR_NOTIFICATION, 11100, errorString);
if (notification != null) {
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
sendMail(notification);
}
if(logger.isInfoEnabled()) {
logger.info(errorString);
}
ussdText = new StringBuffer();
ussdText.append("Error while preparing the response.\nMessage length exceeds the maximum.");
}
ussdRestcommResponse.setMessage(ussdText.toString());
if(logger.isInfoEnabled()) {
logger.info("UssdMessage prepared, hasCollect: " + hasCollect);
logger.info("UssdMessage prepared: " + ussdMessage.toString() + " hasCollect: " + hasCollect);
}
if (callInfo != null && callInfo.direction().equalsIgnoreCase("inbound")) {
// USSD PULL
if (hasCollect) {
ussdRestcommResponse.setMessageType(UssdMessageType.unstructuredSSRequest_Request);
ussdRestcommResponse.setIsFinalMessage(false);
} else {
ussdRestcommResponse.setMessageType(UssdMessageType.processUnstructuredSSRequest_Response);
ussdRestcommResponse.setIsFinalMessage(true);
}
} else {
//USSD PUSH
if (hasCollect) {
ussdRestcommResponse.setMessageType(UssdMessageType.unstructuredSSRequest_Request);
ussdRestcommResponse.setIsFinalMessage(false);
} else {
ussdRestcommResponse.setMessageType(UssdMessageType.unstructuredSSNotify_Request);
if (ussdRestcommResponse.getErrorCode() != null) {
ussdRestcommResponse.setIsFinalMessage(true);
} else {
ussdRestcommResponse.setIsFinalMessage(false);
}
}
}
if(logger.isInfoEnabled()) {
logger.info("UssdRestcommResponse message prepared: "+ussdRestcommResponse);
}
ussdCall.tell(ussdRestcommResponse, source);
}
}
}
private StringBuffer processUssdMessageTags(Queue<Tag> messageTags) {
StringBuffer message = new StringBuffer();
while (!messageTags.isEmpty()) {
Tag tag = messageTags.poll();
if (tag != null) {
message.append(tag.text());
if (!messageTags.isEmpty())
message.append("\n");
} else {
return message;
}
}
return message;
}
private final class ProcessingInfoRequest extends AbstractAction {
public ProcessingInfoRequest(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("UssdInterpreter Processing INFO request");
}
final NotificationsDao notifications = storage.getNotificationsDao();
SipServletRequest info = (SipServletRequest) message;
SipServletResponse okay = info.createResponse(200);
okay.send();
UssdInfoRequest ussdInfoRequest = new UssdInfoRequest(info);
String ussdText = ussdInfoRequest.getMessage();
UssdMessageType ussdMsgType = ussdInfoRequest.getUssdMessageType();
if ( !ussdMsgType.equals(UssdMessageType.unstructuredSSNotify_Response) &&
ussdCollectAction != null &&
!ussdCollectAction.isEmpty() &&
ussdText != null) {
URI target = null;
try {
target = URI.create(ussdCollectAction);
} catch (final Exception exception) {
final Notification notification = notification(ERROR_NOTIFICATION, 11100, ussdCollectAction
+ " is an invalid URI.");
notifications.addNotification(notification);
sendMail(notification);
final StopInterpreter stop = new StopInterpreter();
source.tell(stop, source);
return;
}
final URI base = request.getUri();
final URI uri = uriUtils.resolveWithBase(base, target);
// Parse "method".
String method = "POST";
Attribute attribute = null;
try {
attribute = verb.attribute("method");
} catch (Exception e) {}
if (attribute != null) {
method = attribute.value();
if (method != null && !method.isEmpty()) {
if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) {
final Notification notification = notification(WARNING_NOTIFICATION, 14104, method
+ " is not a valid HTTP method for <Gather>");
notifications.addNotification(notification);
method = "POST";
}
} else {
method = "POST";
}
}
final List<NameValuePair> parameters = parameters();
parameters.add(new BasicNameValuePair("Digits", ussdText));
request = new HttpRequestDescriptor(uri, method, parameters);
downloader.tell(request, source);
ussdCollectTag = null;
ussdLanguageTag = null;
ussdMessageTags = new LinkedBlockingQueue<Tag>();
return;
} else if (ussdMsgType.equals(UssdMessageType.unstructuredSSNotify_Response)) {
UssdRestcommResponse ussdRestcommResponse = new UssdRestcommResponse();
ussdRestcommResponse.setErrorCode("1");
ussdRestcommResponse.setIsFinalMessage(true);
ussdCall.tell(ussdRestcommResponse, source);
return;
}
// Ask the parser for the next action to take.
final GetNextVerb next = new GetNextVerb();
parser.tell(next, self());
}
}
private final class Cancelling extends AbstractAction {
public Cancelling(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Cancelling state");
}
final Class<?> klass = message.getClass();
if (message instanceof SipServletRequest) {
SipServletRequest request = (SipServletRequest)message;
if (ussdCall != null)
ussdCall.tell(request, self());
if (outboundCall != null)
ussdCall.tell(request, self());
}
}
}
private final class Disconnecting extends AbstractAction {
public Disconnecting(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("Disconnecting state");
}
final Class<?> klass = message.getClass();
if (message instanceof SipServletRequest) {
SipServletRequest request = (SipServletRequest)message;
if (ussdCall != null)
ussdCall.tell(request, self());
if (outboundCall != null)
ussdCall.tell(request, self());
}
}
}
private final class Finished extends AbstractAction {
public Finished(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled()) {
logger.info("In Finished state");
}
final Class<?> klass = message.getClass();
if (CallStateChanged.class.equals(klass)) {
final CallStateChanged event = (CallStateChanged) message;
callState = event.state();
if (callRecord != null) {
callRecord = callRecord.setStatus(callState.toString());
final DateTime end = DateTime.now();
callRecord = callRecord.setEndTime(end);
final int seconds = (int) (end.getMillis() - callRecord.getStartTime().getMillis()) / 1000;
callRecord = callRecord.setDuration(seconds);
final CallDetailRecordsDao records = storage.getCallDetailRecordsDao();
records.updateCallDetailRecord(callRecord);
}
callback();
}
context().stop(self());
}
}
@Override
public void postStop() {
if(logger.isInfoEnabled()) {
logger.info("UssdInterpreter postStop");
}
if (ussdCall != null)
getContext().stop(ussdCall);
if (outboundCall != null)
getContext().stop(outboundCall);
if (downloader != null)
getContext().stop(downloader);
if (parser != null)
getContext().stop(parser);
if (mailerNotify != null)
getContext().stop(mailerNotify);
super.postStop();
}
}
| 51,916 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdInterpreterParams.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/interpreter/UssdInterpreterParams.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.ussd.interpreter;
import akka.actor.ActorRef;
import org.apache.commons.configuration.Configuration;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoManager;
import java.net.URI;
/**
* @author [email protected] (Oleg Agafonov)
*/
public final class UssdInterpreterParams {
private Configuration configuration;
private DaoManager storage;
private ActorRef sms;
private Sid account;
private Sid phone;
private String version;
private URI url;
private String method;
private URI fallbackUrl;
private String fallbackMethod;
private URI statusCallback;
private String statusCallbackMethod;
private String emailAddress;
public Configuration getConfiguration() {
return configuration;
}
public DaoManager getStorage() {
return storage;
}
public ActorRef getSms() {
return sms;
}
public Sid getAccount() {
return account;
}
public Sid getPhone() {
return phone;
}
public String getVersion() {
return version;
}
public URI getUrl() {
return url;
}
public String getMethod() {
return method;
}
public URI getFallbackUrl() {
return fallbackUrl;
}
public String getFallbackMethod() {
return fallbackMethod;
}
public URI getStatusCallback() {
return statusCallback;
}
public String getStatusCallbackMethod() {
return statusCallbackMethod;
}
public String getEmailAddress() {
return emailAddress;
}
private UssdInterpreterParams(Configuration configuration, DaoManager storage, ActorRef callManager, ActorRef sms, Sid account, Sid phone, String version, URI url, String method, URI fallbackUrl, String fallbackMethod, URI statusCallback, String statusCallbackMethod, String emailAddress) {
this.configuration = configuration;
this.storage = storage;
this.sms = sms;
this.account = account;
this.phone = phone;
this.version = version;
this.url = url;
this.method = method;
this.fallbackUrl = fallbackUrl;
this.fallbackMethod = fallbackMethod;
this.statusCallback = statusCallback;
this.statusCallbackMethod = statusCallbackMethod;
this.emailAddress = emailAddress;
}
public static final class Builder {
private Configuration configuration;
private DaoManager storage;
private ActorRef callManager;
private ActorRef sms;
private Sid account;
private Sid phone;
private String version;
private URI url;
private String method;
private URI fallbackUrl;
private String fallbackMethod;
private URI statusCallback;
private String statusCallbackMethod;
private String emailAddress;
public Builder setConfiguration(Configuration configuration) {
this.configuration = configuration;
return this;
}
public Builder setStorage(DaoManager storage) {
this.storage = storage;
return this;
}
public Builder setSms(ActorRef sms) {
this.sms = sms;
return this;
}
public Builder setAccount(Sid account) {
this.account = account;
return this;
}
public Builder setPhone(Sid phone) {
this.phone = phone;
return this;
}
public Builder setVersion(String version) {
this.version = version;
return this;
}
public Builder setUrl(URI url) {
this.url = url;
return this;
}
public Builder setMethod(String method) {
this.method = method;
return this;
}
public Builder setFallbackUrl(URI fallbackUrl) {
this.fallbackUrl = fallbackUrl;
return this;
}
public Builder setFallbackMethod(String fallbackMethod) {
this.fallbackMethod = fallbackMethod;
return this;
}
public Builder setStatusCallback(URI statusCallback) {
this.statusCallback = statusCallback;
return this;
}
public Builder setStatusCallbackMethod(String statusCallbackMethod) {
this.statusCallbackMethod = statusCallbackMethod;
return this;
}
public Builder setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
return this;
}
public UssdInterpreterParams build() {
return new UssdInterpreterParams(configuration, storage, callManager, sms, account, phone, version, url, method, fallbackUrl, fallbackMethod, statusCallback, statusCallbackMethod, emailAddress);
}
}
}
| 5,757 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdMessageType.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/commons/UssdMessageType.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.ussd.commons;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public enum UssdMessageType {
/*
* There are in total 6 USSD Messages
* processUnstructuredSSRequest_Request : This request is always initiated by Mobile/User and hence is first message in PULL flow. Always PULL Case
* processUnstructuredSSRequest_Response : This is always last response from USSD Gateway to above request received. However there can be many exchanges of below messages if Application wants tree based menu. Always PULL Case
* unstructuredSSRequest_Request : USSD Gateway can send this message in response to received "processUnstructuredSSRequest_Request". This means that USSD Gateway is expecting some response back from Mobile/User. This can be also used in PUSH, where USSD Gateway is sending this message for first time to get user response and after receiving below response, USSD Gw can again send another "unstructuredSSRequest_Request" or send "unstructuredSSNotify_Request" just to notify user (without expecting any input from user). Both PULL and PUSH case.
* unstructuredSSRequest_Response : This response is always from Mobile/User. Both PULL and PUSH Case
* unstructuredSSNotify_Request : This is always used in PUSH, where USSD Gateway is sending this message to notify User/Mobile. User doesn't get any option to send any response but just press Ok. As soon as he presses Ok below response is sent back. Always PUSH case
* unstructuredSSNotify_Response: Response from user. Always PUSH case
*/
/** processUnstructuredSSRequest_Request : This request is always initiated by Mobile/User and hence is first message in PULL flow. Always PULL Case */
processUnstructuredSSRequest_Request,
/** processUnstructuredSSRequest_Response : This is always last response from USSD Gateway to above request received. However there can be many exchanges of below messages if Application wants tree based menu. Always PULL Case */
processUnstructuredSSRequest_Response,
/**unstructuredSSRequest_Request : USSD Gateway can send this message in response to received "processUnstructuredSSRequest_Request". This means that USSD Gateway is expecting some response back from Mobile/User. This can be also used in PUSH, where USSD Gateway is sending this message for first time to get user response and after receiving below response, USSD Gw can again send another "unstructuredSSRequest_Request" or send "unstructuredSSNotify_Request" just to notify user (without expecting any input from user). Both PULL and PUSH case.*/
unstructuredSSRequest_Request,
/**unstructuredSSRequest_Response : This response is always from Mobile/User. Both PULL and PUSH Case*/
unstructuredSSRequest_Response,
/**unstructuredSSNotify_Request : This is always used in PUSH, where USSD Gateway is sending this message to notify User/Mobile. User doesn't get any option to send any response but just press Ok. As soon as he presses Ok below response is sent back. Always PUSH case*/
unstructuredSSNotify_Request,
/**unstructuredSSNotify_Response: Response from user. Always PUSH case*/
unstructuredSSNotify_Response;
}
| 4,031 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdRestcommResponse.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/commons/UssdRestcommResponse.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.ussd.commons;
import java.io.StringWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
/**
* This class represent the USSD response message that Restcomm creates after parsing the RCML application
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public class UssdRestcommResponse {
private String message;
private String language;
private int messageLength;
private UssdMessageType messageType;
private Boolean isFinalMessage = true;
private String ussdCollectAction;
private String errorCode;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public int getMessageLength() {
return messageLength;
}
public void setMessageLength(int messageLength) {
this.messageLength = messageLength;
}
public UssdMessageType getUssdMessageType() {
return messageType;
}
public void setMessageType(UssdMessageType messageType) {
this.messageType = messageType;
}
public Boolean getIsFinalMessage() {
return isFinalMessage;
}
public void setIsFinalMessage(Boolean isFinalMessage) {
this.isFinalMessage = isFinalMessage;
}
public String createUssdPayload() throws XMLStreamException {
// create an XMLOutputFactory
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
StringWriter writer = new StringWriter();
XMLStreamWriter streamWriter = outputFactory.createXMLStreamWriter(writer);
streamWriter.writeStartDocument("UTF-8", "1.0");
streamWriter.writeCharacters("\n");
streamWriter.writeStartElement("ussd-data");
streamWriter.writeCharacters("\n");
if (getLanguage() != null) {
// Write Language element
streamWriter.writeStartElement("language");
streamWriter.writeAttribute("value", getLanguage());
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n");
}
if (getMessage() != null) {
// Write ussd-string
streamWriter.writeStartElement("ussd-string");
streamWriter.writeAttribute("value", getMessage());
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n");
}
if (getUssdMessageType() != null) {
streamWriter.writeStartElement("anyExt");
streamWriter.writeCharacters("\n");
streamWriter.writeStartElement("message-type");
streamWriter.writeCharacters(getUssdMessageType().name());
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n");
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n");
}
if (getErrorCode() != null) {
// Write error code
streamWriter.writeStartElement("error-code");
streamWriter.writeAttribute("value", getErrorCode());
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n");
}
streamWriter.writeEndElement();
streamWriter.writeCharacters("\n");
streamWriter.writeEndDocument();
streamWriter.flush();
streamWriter.close();
return writer.toString();
}
/**
* @param ussdCollectAction
*/
public void setUssdCollectAction(String ussdCollectAction) {
this.ussdCollectAction = ussdCollectAction;
}
public String getUssdCollectAction() {
return ussdCollectAction;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "UssdRestCommResponse :"+message+" messageType: "+messageType.name()+" isFinalMessage: "+isFinalMessage;
}
} | 5,095 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdInfoRequest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.ussd/src/main/java/org/restcomm/connect/ussd/commons/UssdInfoRequest.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.ussd.commons;
import static javax.xml.stream.XMLStreamConstants.*;
import java.io.IOException;
import java.io.StringReader;
import javax.servlet.sip.SipServletRequest;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
/**
* This class represents the INFO request received by Restcomm from Client.
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public class UssdInfoRequest {
private final String ussdPayload;
private String message;
private String language;
private UssdMessageType ussdMessageType;
public UssdInfoRequest(SipServletRequest request) throws IOException{
this.ussdPayload = new String(request.getRawContent());
}
public UssdInfoRequest(String payload) {
this.ussdPayload = payload;
}
public void readUssdPayload() throws Exception{
StringReader reader = new StringReader(ussdPayload.trim().replaceAll("&([^;]+(?!(?:\\w|;)))", "&$1").replaceAll("\\n", "").replaceAll("\\t", ""));
final XMLInputFactory inputs = XMLInputFactory.newInstance();
inputs.setProperty("javax.xml.stream.isCoalescing", true);
XMLStreamReader stream = null;
try {
stream = inputs.createXMLStreamReader(reader);
while (stream.hasNext()){
stream.next();
int streamEvent = stream.getEventType();
if( streamEvent != END_DOCUMENT && streamEvent == START_ELEMENT) {
String name = stream.getLocalName();
if(name.equalsIgnoreCase("language") && stream.isStartElement()) {
this.language = stream.getAttributeValue("", "value");
} else if (name.equalsIgnoreCase("ussd-string") && stream.isStartElement()) {
this.message = stream.getAttributeValue("", "value");
} else if (name.equalsIgnoreCase("anyExt") && stream.isStartElement()) {
stream.next();
name = stream.getLocalName();
if (name.equalsIgnoreCase("message-type") && stream.isStartElement()){
stream.next();
this.ussdMessageType = UssdMessageType.valueOf(stream.getText().trim());
}
}
}
}
} catch (Exception e) {
this.message = e.getMessage();
throw e;
}
}
public String getMessage() throws Exception {
if (message == null)
readUssdPayload();
return message;
}
public String getLanguage() throws Exception {
if (language == null)
readUssdPayload();
return (language == null) ? "en" : language;
}
public UssdMessageType getUssdMessageType() throws Exception {
if(ussdMessageType == null)
readUssdPayload();
return (ussdMessageType == null) ? UssdMessageType.unstructuredSSRequest_Response : ussdMessageType;
}
public int getMessageLength() throws Exception {
if(message == null)
readUssdPayload();
return message.length();
}
public Boolean getIsFinalMessage() {
// TODO Auto-generated method stub
return null;
}
}
| 4,163 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MonitoringService.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.monitoring.service/src/main/java/org/restcomm/connect/monitoringservice/MonitoringService.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.monitoringservice;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.patterns.Observing;
import org.restcomm.connect.commons.patterns.StopObserving;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.entities.InstanceId;
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 org.restcomm.connect.telephony.api.CallInfo;
import org.restcomm.connect.telephony.api.CallResponse;
import org.restcomm.connect.telephony.api.CallStateChanged;
import org.restcomm.connect.telephony.api.GetCall;
import org.restcomm.connect.telephony.api.GetCallInfo;
import org.restcomm.connect.telephony.api.GetLiveCalls;
import org.restcomm.connect.telephony.api.GetStatistics;
import org.restcomm.connect.telephony.api.MonitoringServiceResponse;
import org.restcomm.connect.telephony.api.TextMessage;
import org.restcomm.connect.telephony.api.UserRegistration;
import javax.servlet.sip.ServletParseException;
import javax.sip.header.ContactHeader;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*/
public class MonitoringService extends RestcommUntypedActor {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
private DaoManager daoManager;
private final Map<String, ActorRef> callMap;
private final Map<String, ActorRef> callLocationMap;
private final Map<String,CallInfo> callDetailsMap;
private final Map<String,CallInfo> incomingCallDetailsMap;
private final Map<String,CallInfo> outgoingCallDetailsMap;
private final Map<String, CallStateChanged.State> callStateMap;
private final Map<String, String> registeredUsers;
private final AtomicInteger callsUpToNow;
private final AtomicInteger incomingCallsUpToNow;
private final AtomicInteger outgoingCallsUpToNow;
private final AtomicInteger completedCalls;
private final AtomicInteger failedCalls;
private final AtomicInteger busyCalls;
private final AtomicInteger canceledCalls;
private final AtomicInteger noAnswerCalls;
private final AtomicInteger notFoundCalls;
private final AtomicInteger textInboundToApp;
private final AtomicInteger textInboundToClient;
private final AtomicInteger textInboundToProxyOut;
private final AtomicInteger textOutbound;
private final AtomicInteger textNotFound;
private final AtomicInteger maxConcurrentCalls;
private final AtomicInteger maxConcurrentIncomingCalls;
private final AtomicInteger maxConcurrentOutgoingCalls;
private final AtomicInteger mgcpEndpointsBridge;
private final AtomicInteger mgcpEndpointsIvr;
private final AtomicInteger mgcpEndpointsConference;
private final AtomicInteger mgcpEndpointsPacketRelay;
private final Map<String, String> mgcpEndpointMap;
private final Map<String, String> mgcpConnectionMap;
private InstanceId instanceId;
public MonitoringService(final DaoManager daoManager) {
this.daoManager = daoManager;
callMap = new ConcurrentHashMap<String, ActorRef>();
callLocationMap = new ConcurrentHashMap<String, ActorRef>();
callDetailsMap = new ConcurrentHashMap<String, CallInfo>();
incomingCallDetailsMap = new ConcurrentHashMap<String, CallInfo>();
outgoingCallDetailsMap = new ConcurrentHashMap<String, CallInfo>();
callStateMap = new ConcurrentHashMap<String, CallStateChanged.State>();
registeredUsers = new ConcurrentHashMap<String, String>();
callsUpToNow = new AtomicInteger();
incomingCallsUpToNow = new AtomicInteger();
outgoingCallsUpToNow = new AtomicInteger();
completedCalls = new AtomicInteger();
failedCalls = new AtomicInteger();
busyCalls = new AtomicInteger();
canceledCalls = new AtomicInteger();
noAnswerCalls = new AtomicInteger();
notFoundCalls = new AtomicInteger();
textInboundToApp = new AtomicInteger();
textInboundToClient = new AtomicInteger();
textInboundToProxyOut = new AtomicInteger();
textOutbound = new AtomicInteger();
textNotFound = new AtomicInteger();
maxConcurrentCalls = new AtomicInteger(0);
maxConcurrentIncomingCalls = new AtomicInteger(0);
maxConcurrentOutgoingCalls = new AtomicInteger(0);
mgcpEndpointsBridge = new AtomicInteger(0);
mgcpEndpointsIvr = new AtomicInteger(0);
mgcpEndpointsConference = new AtomicInteger(0);
mgcpEndpointsPacketRelay = new AtomicInteger(0);
mgcpEndpointMap = new ConcurrentHashMap<String, String>();
mgcpConnectionMap = new ConcurrentHashMap<String, String>();
if(logger.isInfoEnabled()){
logger.info("Monitoring Service started");
}
}
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
if(logger.isInfoEnabled()){
logger.info("MonitoringService, path: \""+self.path()+"\" Processing Message: \"" + klass.getName() + "\" sender : "+ sender.getClass()+"\" self is terminated: "+self.isTerminated()+"\"");
}
if (InstanceId.class.equals(klass)) {
onGotInstanceId((InstanceId) message, self, sender);
} else if (Observing.class.equals(klass)) {
onStartObserve((Observing) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
if(logger.isInfoEnabled()){
logger.info("Received stop observing");
}
onStopObserving((StopObserving) message, self, sender);
} else if (CallResponse.class.equals(klass)) {
onCallResponse((CallResponse<CallInfo>)message, self, sender);
} else if (CallStateChanged.class.equals(klass)) {
onCallStateChanged((CallStateChanged)message, self, sender);
} else if (GetStatistics.class.equals(klass)) {
onGetStatistics((GetStatistics) message, self, sender);
} else if (GetLiveCalls.class.equals(klass)) {
onGetLiveCalls((GetLiveCalls)message, self, sender);
} else if (UserRegistration.class.equals(klass)) {
onUserRegistration((UserRegistration)message, self, sender);
} else if (TextMessage.class.equals(klass)) {
onTextMessage((TextMessage) message, self, sender);
} else if (GetCall.class.equals(klass)) {
if (message != null) {
onGetCall(message, self, sender);
} else {
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService onGetCall, message is null, sender: "+sender.path());
}
}
} else if (MgcpConnectionAdded.class.equals(klass)) {
MgcpConnectionAdded mgcpConnectionAdded = (MgcpConnectionAdded)message;
mgcpConnectionMap.put(mgcpConnectionAdded.getConnId(), mgcpConnectionAdded.getEndpointId());
} else if (MgcpConnectionDeleted.class.equals(klass)) {
MgcpConnectionDeleted mgcpConnectionDeleted = (MgcpConnectionDeleted)message;
if (mgcpConnectionDeleted.getConnId() != null) {
mgcpConnectionMap.remove(mgcpConnectionDeleted.getConnId());
} else {
mgcpConnectionMap.values().removeAll(Collections.singleton(mgcpConnectionDeleted.getEndpoint()));
}
} else if (MgcpEndpointAdded.class.equals(klass)) {
MgcpEndpointAdded mgcpEndpointAdded = (MgcpEndpointAdded)message;
mgcpEndpointMap.put(mgcpEndpointAdded.getConnId(), mgcpEndpointAdded.getEndpoint());
logger.info("MonitoringService: Added endpoint: "+mgcpEndpointAdded.getEndpoint());
String endpoint = mgcpEndpointAdded.getEndpoint();
if (endpoint.contains("ivr")) {
mgcpEndpointsIvr.incrementAndGet();
} else if (endpoint.contains("conf")) {
mgcpEndpointsConference.incrementAndGet();
} else if (endpoint.contains("bridge")) {
mgcpEndpointsBridge.incrementAndGet();
} else if (endpoint.contains("relay")) {
mgcpEndpointsPacketRelay.incrementAndGet();
}
} else if (MgcpEndpointDeleted.class.equals(klass)) {
MgcpEndpointDeleted mgcpEndpointDeleted = (MgcpEndpointDeleted)message;
mgcpEndpointMap.values().removeAll(Collections.singleton(mgcpEndpointDeleted.getEndpoint()));
logger.info("MonitoringService: Deleted endpoint: "+mgcpEndpointDeleted.getEndpoint());
String endpoint = mgcpEndpointDeleted.getEndpoint();
if (endpoint.contains("ivr")) {
mgcpEndpointsIvr.decrementAndGet();
} else if (endpoint.contains("conf")) {
mgcpEndpointsConference.decrementAndGet();
} else if (endpoint.contains("bridge")) {
mgcpEndpointsBridge.decrementAndGet();
} else if (endpoint.contains("relay")) {
mgcpEndpointsPacketRelay.decrementAndGet();
}
}
}
private void onGetCall(Object message, ActorRef self, ActorRef sender) throws ServletParseException {
GetCall getCall = (GetCall)message;
String location = getCall.getIdentifier();
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService onGetCall, location: "+location);
}
if (location != null) {
ActorRef call = callLocationMap.get(location);
if(call == null && location.indexOf("@") != -1 && location.indexOf(":") != -1) {
// required in case the Contact Header of the INVITE doesn't contain any user part
// as it is the case for Restcomm SDKs
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService onGetCall Another try on removing the user part from " + location);
}
int indexOfAt = location.indexOf("@");
int indexOfColumn = location.indexOf(":");
String newLocation = location.substring(0, indexOfColumn+1).concat(location.substring(indexOfAt+1));
call = callLocationMap.get(newLocation);
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService onGetCall call " + call + " found for new Location " + newLocation);
}
}
if (call != null) {
sender.tell(call, sender());
} else {
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService onGetCall, Call is null");
}
}
} else {
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService onGetCall, GetCall identifier location is null");
}
}
}
/**
* @param message
* @param self
* @param sender
*/
private void onTextMessage(TextMessage message, ActorRef self, ActorRef sender) {
TextMessage.SmsState state = message.getState();
if (state.equals(TextMessage.SmsState.INBOUND_TO_APP)) {
textInboundToApp.incrementAndGet();
} else if (state.equals(TextMessage.SmsState.INBOUND_TO_CLIENT)) {
textInboundToClient.incrementAndGet();
} else if (state.equals(TextMessage.SmsState.INBOUND_TO_PROXY_OUT)) {
textInboundToProxyOut.incrementAndGet();
} else if (state.equals(TextMessage.SmsState.OUTBOUND)) {
textOutbound.incrementAndGet();
} else if (state.equals(TextMessage.SmsState.NOT_FOUND)) {
textNotFound.incrementAndGet();
}
}
private void onGotInstanceId(InstanceId instanceId, ActorRef self, ActorRef sender) {
this.instanceId = instanceId;
}
/**
* @param userRegistration
* @param self
* @param sender
*/
private void onUserRegistration(UserRegistration userRegistration, ActorRef self, ActorRef sender) {
if (userRegistration.getRegistered()) {
try {
registeredUsers.put(userRegistration.getUserPlusOrganizationsSid(), userRegistration.getAddress());
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService There was an issue during the process of UserRegistration message, "+e);
}
}
} else {
if (registeredUsers.containsKey(userRegistration.getUserPlusOrganizationsSid())) {
registeredUsers.remove(userRegistration.getUserPlusOrganizationsSid());
if (logger.isDebugEnabled()) {
String msg = String.format("MonitoringService User %s removed from registered users", userRegistration.getUserPlusOrganizationsSid());
logger.debug(msg);
}
} else {
if (logger.isDebugEnabled()) {
String msg = String.format("MonitoringService User %s was not removed because is not in the registered users", userRegistration.getUserPlusOrganizationsSid());
logger.debug(msg);
}
}
}
}
/**
* @param message
* @param self
* @param sender
*/
private void onStartObserve(Observing message, ActorRef self, ActorRef sender) {
String senderPath = sender.path().name();
sender.tell(new GetCallInfo(), self);
callMap.put(senderPath, sender);
callsUpToNow.incrementAndGet();
}
/**
* @param message
* @param self
* @param sender
*/
private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) throws ServletParseException {
String senderPath = sender.path().name();
callMap.remove(senderPath);
CallInfo callInfo = callDetailsMap.remove(senderPath);
if (callInfo != null && callInfo.invite() != null) {
callLocationMap.remove(callInfo.invite().getAddressHeader(ContactHeader.NAME).getURI().toString());
}
if (callInfo.direction().equalsIgnoreCase("inbound")) {
if (logger.isDebugEnabled()) {
String msg = String.format("MonitoringService Removed inbound call from: %s to: %s, currently liveCalls: %d", callInfo.from(), callInfo.to(),callDetailsMap.size());
logger.debug(msg);
}
incomingCallDetailsMap.remove(senderPath);
} else {
if (logger.isDebugEnabled()) {
String msg = String.format("MonitoringService Removed outbound call from: %s to: %s, currently liveCallS: %d ", callInfo.from(), callInfo.to(),callDetailsMap.size());
logger.debug(msg);
}
outgoingCallDetailsMap.remove(senderPath);
}
callStateMap.remove(senderPath);
}
/**
* @param message
* @param self
* @param sender
*/
private void onCallResponse(CallResponse<CallInfo> message, ActorRef self, ActorRef sender) throws ServletParseException {
String senderPath = sender.path().name();
CallInfo callInfo = message.get();
callDetailsMap.put(senderPath, callInfo);
if (callInfo != null && callInfo.invite() != null) {
callLocationMap.put(callInfo.invite().getAddressHeader(ContactHeader.NAME).getURI().toString(), sender);
}
if (callInfo.direction().equalsIgnoreCase("inbound")) {
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService New inbound call from: "+callInfo.from()+" to: "+callInfo.to());
}
incomingCallDetailsMap.put(senderPath, callInfo);
incomingCallsUpToNow.incrementAndGet();
} else {
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService New outbound call from: "+callInfo.from()+" to: "+callInfo.to());
}
outgoingCallDetailsMap.put(senderPath, callInfo);
outgoingCallsUpToNow.incrementAndGet();
}
//Calculate Maximum concurrent calls
if (maxConcurrentCalls.get() < callDetailsMap.size()) {
maxConcurrentCalls.set(callDetailsMap.size());
}
if (maxConcurrentIncomingCalls.get() < incomingCallDetailsMap.size()) {
maxConcurrentIncomingCalls.set(incomingCallDetailsMap.size());
}
if (maxConcurrentOutgoingCalls.get() < outgoingCallDetailsMap.size()) {
maxConcurrentOutgoingCalls.set(outgoingCallDetailsMap.size());
}
}
/**
* @param message
* @param self
* @param sender
*/
private void onCallStateChanged(CallStateChanged message, ActorRef self, ActorRef sender) {
String senderPath = sender.path().name();
if (senderPath != null && message != null && callStateMap != null && callDetailsMap != null) {
CallStateChanged.State callState = message.state();
callStateMap.put(senderPath, callState);
CallInfo callInfo = callDetailsMap.get(senderPath);
if (callInfo != null) {
callInfo.setState(callState);
if (callState.equals(CallStateChanged.State.FAILED)) {
failedCalls.incrementAndGet();
} else if (callState.equals(CallStateChanged.State.COMPLETED)) {
completedCalls.incrementAndGet();
} else if(callState.equals(CallStateChanged.State.BUSY)) {
busyCalls.incrementAndGet();
} else if (callState.equals(CallStateChanged.State.CANCELED)) {
canceledCalls.incrementAndGet();
} else if (callState.equals(CallStateChanged.State.NO_ANSWER)) {
noAnswerCalls.incrementAndGet();
} else if (callState.equals(CallStateChanged.State.NOT_FOUND)) {
notFoundCalls.incrementAndGet();
}
} else if(logger.isInfoEnabled()){
logger.info("MonitoringService CallInfo was not in the store for Call: "+senderPath);
}
} else {
logger.error("MonitoringService, SenderPath or storage is null.");
}
}
/**
* @param message
* @param self
* @param sender
*/
private void onGetStatistics (GetStatistics message, ActorRef self, ActorRef sender) throws ParseException {
List<CallInfo> callDetailsList = new ArrayList<CallInfo>(callDetailsMap.values());
Map<String, Integer> countersMap = new HashMap<String, Integer>();
Map<String, Double> durationMap = new HashMap<String, Double>();
final AtomicInteger liveIncomingCalls = new AtomicInteger();
final AtomicInteger liveOutgoingCalls = new AtomicInteger();
countersMap.put(MonitoringMetrics.COUNTERS_MAP_TOTAL_CALLS_SINCE_UPTIME,callsUpToNow.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_INCOMING_CALLS_SINCE_UPTIME, incomingCallsUpToNow.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_OUTGOING_CALL_SINCE_UPTIME, outgoingCallsUpToNow.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_REGISTERED_USERS, registeredUsers.size());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_LIVE_CALLS, callDetailsMap.size());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MAXIMUM_CONCURRENT_CALLS, maxConcurrentCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MAXIMUM_CONCURRENT_INCOMING_CALLS, maxConcurrentIncomingCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MAXIMUM_CONCURRENT_OUTGOING_CALLS, maxConcurrentOutgoingCalls.get());
Double averageCallDurationLast24Hours = null;
Double averageCallDurationLastHour = null;
try {
averageCallDurationLast24Hours = daoManager.getCallDetailRecordsDao().getAverageCallDurationLast24Hours(instanceId.getId());
averageCallDurationLastHour = daoManager.getCallDetailRecordsDao().getAverageCallDurationLastHour(instanceId.getId());
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("MonitoringService Exception during the query for AVG Call Duration: "+e.getStackTrace());
}
}
if (averageCallDurationLast24Hours == null) {
averageCallDurationLast24Hours = 0.0;
}
if (averageCallDurationLastHour == null) {
averageCallDurationLastHour = 0.0;
}
durationMap.put(MonitoringMetrics.DURATION_MAP_AVERAGE_CALL_DURATION_IN_SECONDS_LAST_24_HOURS, averageCallDurationLast24Hours);
durationMap.put(MonitoringMetrics.DURATION_MAP_AVERAGE_CALL_DURATION_IN_SECONDS_LAST_HOUR, averageCallDurationLastHour);
for (CallInfo callInfo : callDetailsList) {
if (callInfo.direction().equalsIgnoreCase("inbound")) {
liveIncomingCalls.incrementAndGet();
} else if (callInfo.direction().contains("outbound")) {
liveOutgoingCalls.incrementAndGet();
}
}
countersMap.put(MonitoringMetrics.COUNTERS_MAP_LIVE_INCOMING_CALLS, liveIncomingCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_LIVE_OUTGOING_CALLS, liveOutgoingCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_COMPLETED_CALLS, completedCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_NO_ANSWER_CALLS, noAnswerCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_BUSY_CALLS, busyCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_FAILED_CALLS, failedCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_NOT_FOUND_CALLS, notFoundCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_CANCELED_CALLS, canceledCalls.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_TEXT_MESSAGE_INBOUND_TO_APP, textInboundToApp.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_TEXT_MESSAGE_INBOUND_TO_CLIENT, textInboundToClient.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_TEXT_MESSAGE_INBOUND_TO_PROXY_OUT, textInboundToProxyOut.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_TEXT_MESSAGE_NOT_FOUND, textNotFound.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_TEXT_MESSAGE_OUTBOUND, textOutbound.get());
if (message.isWithMgcpStats()) {
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MGCP_CONNECTIONS, mgcpConnectionMap.size());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS, mgcpEndpointMap.size());
if (mgcpEndpointMap.size()>0) {
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS_BRIDGE, mgcpEndpointsBridge.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS_IVR, mgcpEndpointsIvr.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS_CONFERENCE, mgcpEndpointsConference.get());
countersMap.put(MonitoringMetrics.COUNTERS_MAP_MGCP_ENDPOINTS_PACKETRELAY, mgcpEndpointsPacketRelay.get());
}
}
MonitoringServiceResponse callInfoList = null;
if (message.isWithLiveCallDetails()) {
callInfoList = new MonitoringServiceResponse(instanceId, callDetailsList, countersMap, durationMap, true, null, new Sid(message.getAccountSid()));
} else {
URI callDetailsUri = null;
try {
callDetailsUri = new URI(String.format("/restcomm/%s/Accounts/%s/Supervisor.json/livecalls", RestcommConfiguration.getInstance().getMain().getApiVersion(), message.getAccountSid()));
} catch (URISyntaxException e) {
logger.error("MonitoringService Problem while trying to create the LiveCalls detail URI");
}
callInfoList = new MonitoringServiceResponse(instanceId, null, countersMap, durationMap, false, callDetailsUri, new Sid(message.getAccountSid()));
}
sender.tell(callInfoList, self);
}
/**
* @param message
* @param self
* @param sender
*/
private void onGetLiveCalls (GetLiveCalls message, ActorRef self, ActorRef sender) throws ParseException {
List<CallInfo> callDetailsList = new ArrayList<CallInfo>(callDetailsMap.values());
sender.tell(new LiveCallsDetails(callDetailsList), self());
}
@Override
public void postStop() {
if(logger.isInfoEnabled()){
logger.info("Monitoring Service at postStop()");
}
super.postStop();
}
}
| 26,470 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MonitoringMetrics.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.monitoring.service/src/main/java/org/restcomm/connect/monitoringservice/MonitoringMetrics.java | package org.restcomm.connect.monitoringservice;
/**
* Created by gvagenas on 26/09/16.
*/
public class MonitoringMetrics {
public static String COUNTERS_MAP_TOTAL_CALLS_SINCE_UPTIME="TotalCallsSinceUptime";
public static String COUNTERS_MAP_INCOMING_CALLS_SINCE_UPTIME="IncomingCallsSinceUptime";
public static String COUNTERS_MAP_OUTGOING_CALL_SINCE_UPTIME="OutgoingCallsSinceUptime";
public static String COUNTERS_MAP_REGISTERED_USERS="RegisteredUsers";
public static String COUNTERS_MAP_LIVE_CALLS="LiveCalls";
public static String COUNTERS_MAP_MAXIMUM_CONCURRENT_CALLS="MaximumConcurrentCalls";
public static String COUNTERS_MAP_MAXIMUM_CONCURRENT_INCOMING_CALLS="MaximumConcurrentIncomingCalls";
public static String COUNTERS_MAP_MAXIMUM_CONCURRENT_OUTGOING_CALLS="MaximumConcurrentOutgoingCalls";
public static String DURATION_MAP_AVERAGE_CALL_DURATION_IN_SECONDS_LAST_24_HOURS="AverageCallDurationInSecondsLast24Hours";
public static String DURATION_MAP_AVERAGE_CALL_DURATION_IN_SECONDS_LAST_HOUR="AverageCallDurationInSecondsLastHour";
public static String COUNTERS_MAP_LIVE_INCOMING_CALLS="LiveIncomingCalls";
public static String COUNTERS_MAP_LIVE_OUTGOING_CALLS="LiveOutgoingCalls";
public static String COUNTERS_MAP_COMPLETED_CALLS="CompletedCalls";
public static String COUNTERS_MAP_NO_ANSWER_CALLS="NoAnswerCalls";
public static String COUNTERS_MAP_BUSY_CALLS="BusyCalls";
public static String COUNTERS_MAP_FAILED_CALLS="FailedCalls";
public static String COUNTERS_MAP_NOT_FOUND_CALLS="NotFoundCalls";
public static String COUNTERS_MAP_CANCELED_CALLS="CanceledCalls";
public static String COUNTERS_MAP_TEXT_MESSAGE_INBOUND_TO_APP="TextMessageInboundToApp";
public static String COUNTERS_MAP_TEXT_MESSAGE_INBOUND_TO_CLIENT="TextMessageInboundToClient";
public static String COUNTERS_MAP_TEXT_MESSAGE_INBOUND_TO_PROXY_OUT="TextMessageInboundToProxyOut";
public static String COUNTERS_MAP_TEXT_MESSAGE_NOT_FOUND="TextMessageNotFound";
public static String COUNTERS_MAP_TEXT_MESSAGE_OUTBOUND="TextMessageOutbound";
public static String COUNTERS_MAP_MGCP_CONNECTIONS="MgcpConnections";
public static String COUNTERS_MAP_MGCP_LINKS="MgcpLinks";
public static String COUNTERS_MAP_MGCP_ENDPOINTS="MgcpEndpoints";
public static String COUNTERS_MAP_MGCP_ENDPOINTS_BRIDGE="MgcpEndpointsBridge";
public static String COUNTERS_MAP_MGCP_ENDPOINTS_IVR="MgcpEndpointsIvr";
public static String COUNTERS_MAP_MGCP_ENDPOINTS_PACKETRELAY="MgcpEndpointsPacketRelay";
public static String COUNTERS_MAP_MGCP_ENDPOINTS_CONFERENCE="MgcpEndpointsConference";
}
| 2,672 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
LiveCallsDetails.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.monitoring.service/src/main/java/org/restcomm/connect/monitoringservice/LiveCallsDetails.java | package org.restcomm.connect.monitoringservice;
import org.restcomm.connect.telephony.api.CallInfo;
import java.util.List;
/**
* Created by gvagenas on 15/05/2017.
*/
public class LiveCallsDetails {
private final List<CallInfo> callDetails;
public LiveCallsDetails (List<CallInfo> callDetails) {
this.callDetails = callDetails;
}
public List<CallInfo> getCallDetails () {
return callDetails;
}
}
| 440 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RemoteSupervisor.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.monitoring.service/src/main/java/org/restcomm/connect/monitoringservice/RemoteSupervisor.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.monitoringservice;
/**
* Implementation of this interface represent remote endpoints which want to get notified for traffic events
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public interface RemoteSupervisor {
}
| 1,186 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ATTSpeechSynthesizerTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.att/src/test/java/org/restcomm/connect/tts/att/ATTSpeechSynthesizerTest.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.tts.att;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.net.URI;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.restcomm.connect.commons.cache.DiskCache;
import org.restcomm.connect.commons.cache.DiskCacheRequest;
import org.restcomm.connect.commons.cache.DiskCacheResponse;
import org.restcomm.connect.commons.cache.HashGenerator;
import org.restcomm.connect.tts.api.GetSpeechSynthesizerInfo;
import org.restcomm.connect.tts.api.SpeechSynthesizerInfo;
import org.restcomm.connect.tts.api.SpeechSynthesizerRequest;
import org.restcomm.connect.tts.api.SpeechSynthesizerResponse;
import scala.concurrent.duration.FiniteDuration;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.testkit.JavaTestKit;
/**
* @author [email protected] (George Vagenas)
*/
@Ignore //Needs AT&T TTS server to be running so we ignore it and run it manually only
public final class ATTSpeechSynthesizerTest {
private ActorSystem system;
private ActorRef tts;
private ActorRef cache;
private String tempSystemDirectory;
public ATTSpeechSynthesizerTest() throws ConfigurationException {
super();
}
@Before
public void before() throws Exception {
system = ActorSystem.create();
final URL input = getClass().getResource("/att.xml");
final XMLConfiguration configuration = new XMLConfiguration(input);
tts = tts(configuration);
cache = cache("/tmp/cache", "http://127.0.0.1:8080/restcomm/cache");
// Fix for MacOS systems: only append "/" to temporary path if it doesnt end with it - hrosa
String tmpDir = System.getProperty("java.io.tmpdir");
tempSystemDirectory = "file:" + tmpDir + (tmpDir.endsWith("/") ? "" : "/");
}
@After
public void after() throws Exception {
system.shutdown();
}
private ActorRef tts(final Configuration configuration) {
final String classpath = configuration.getString("[@class]");
return system.actorOf(new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public Actor create() throws Exception {
return (UntypedActor) Class.forName(classpath).getConstructor(Configuration.class).newInstance(configuration);
}
}));
}
private ActorRef cache(final String path, final String uri) {
return system.actorOf(new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new DiskCache(path, uri, true);
}
}));
}
@SuppressWarnings("unchecked")
@Test
public void testInfo() {
new JavaTestKit(system) {
{
final ActorRef observer = getRef();
tts.tell(new GetSpeechSynthesizerInfo(), observer);
final SpeechSynthesizerResponse<SpeechSynthesizerInfo> response = this.expectMsgClass(
FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class);
assertTrue(response.succeeded());
final Set<String> languages = response.get().languages();
assertTrue(languages.contains("en"));
assertTrue(languages.contains("en-uk"));
assertTrue(languages.contains("es"));
assertTrue(languages.contains("fr"));
assertTrue(languages.contains("fr-ca"));
assertTrue(languages.contains("de"));
assertTrue(languages.contains("it"));
assertTrue(languages.contains("pt-br"));
}
};
}
@SuppressWarnings("unchecked")
@Test
public void testSynthesisManEnglish() {
new JavaTestKit(system) {
{
final ActorRef observer = getRef();
String gender = "man";
String woman = "woman";
String language = "en";
String message = "Hello TTS World! This is a test for AT&T TTS engine using man voice";
String hash = HashGenerator.hashMessage(gender, language, message);
String womanHash = HashGenerator.hashMessage(woman, language, message);
assertTrue(!hash.equalsIgnoreCase(womanHash));
final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, message);
tts.tell(synthesize, observer);
final SpeechSynthesizerResponse<URI> response = this.expectMsgClass(
FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class);
assertTrue(response.succeeded());
DiskCacheRequest diskCacheRequest = new DiskCacheRequest(response.get());
cache.tell(diskCacheRequest, observer);
final DiskCacheResponse diskCacheResponse = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS),
DiskCacheResponse.class);
assertTrue(diskCacheResponse.succeeded());
assertEquals(tempSystemDirectory + hash + ".wav", response.get().toString());
assertEquals("http://127.0.0.1:8080/restcomm/cache/" + hash + ".wav", diskCacheResponse.get().toString());
FileUtils.deleteQuietly(new File(response.get()));
}
};
}
@SuppressWarnings("unchecked")
@Test
public void testSynthesisWomanEnglish() {
new JavaTestKit(system) {
{
final ActorRef observer = getRef();
String gender = "woman";
String language = "en";
String message = "Hello TTS World! This is a test for AT&T TTS engine using women voice";
String hash = HashGenerator.hashMessage(gender, language, message);
final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, message);
tts.tell(synthesize, observer);
final SpeechSynthesizerResponse<URI> response = this.expectMsgClass(
FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class);
assertTrue(response.succeeded());
DiskCacheRequest diskCacheRequest = new DiskCacheRequest(response.get());
cache.tell(diskCacheRequest, observer);
final DiskCacheResponse diskCacheResponse = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS),
DiskCacheResponse.class);
assertTrue(diskCacheResponse.succeeded());
assertEquals(tempSystemDirectory + hash + ".wav", response.get().toString());
assertEquals("http://127.0.0.1:8080/restcomm/cache/" + hash + ".wav", diskCacheResponse.get().toString());
FileUtils.deleteQuietly(new File(response.get()));
}
};
}
@SuppressWarnings("unchecked")
@Test
public void testSynthesisManSpanish() {
new JavaTestKit(system) {
{
final ActorRef observer = getRef();
String gender = "man";
String woman = "woman";
String language = "es";
String message = "Hola TTS mundo! Esta es una prueba para el motor TTS AT&T utilizando la voz del hombre";
String hash = HashGenerator.hashMessage(gender, language, message);
String womanHash = HashGenerator.hashMessage(woman, language, message);
assertTrue(!hash.equalsIgnoreCase(womanHash));
final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, message);
tts.tell(synthesize, observer);
final SpeechSynthesizerResponse<URI> response = this.expectMsgClass(
FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class);
assertTrue(response.succeeded());
DiskCacheRequest diskCacheRequest = new DiskCacheRequest(response.get());
cache.tell(diskCacheRequest, observer);
final DiskCacheResponse diskCacheResponse = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS),
DiskCacheResponse.class);
assertTrue(diskCacheResponse.succeeded());
assertEquals(tempSystemDirectory + hash + ".wav", response.get().toString());
assertEquals("http://127.0.0.1:8080/restcomm/cache/" + hash + ".wav", diskCacheResponse.get().toString());
FileUtils.deleteQuietly(new File(response.get()));
}
};
}
@SuppressWarnings("unchecked")
@Test
public void testSynthesisWomanSpanish() {
new JavaTestKit(system) {
{
final ActorRef observer = getRef();
String gender = "woman";
String language = "es";
String message = "Hola TTS mundo! Esta es una prueba para el motor TTS AT & T utilizando la mujer de voz";
String hash = HashGenerator.hashMessage(gender, language, message);
final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(gender, language, message);
tts.tell(synthesize, observer);
final SpeechSynthesizerResponse<URI> response = this.expectMsgClass(
FiniteDuration.create(30, TimeUnit.SECONDS), SpeechSynthesizerResponse.class);
assertTrue(response.succeeded());
DiskCacheRequest diskCacheRequest = new DiskCacheRequest(response.get());
cache.tell(diskCacheRequest, observer);
final DiskCacheResponse diskCacheResponse = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS),
DiskCacheResponse.class);
assertTrue(diskCacheResponse.succeeded());
assertEquals(tempSystemDirectory + hash + ".wav", response.get().toString());
assertEquals("http://127.0.0.1:8080/restcomm/cache/" + hash + ".wav", diskCacheResponse.get().toString());
FileUtils.deleteQuietly(new File(response.get()));
}
};
}
}
| 11,822 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
AttSpeechSynthesizer.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.att/src/main/java/org/restcomm/connect/tts/att/AttSpeechSynthesizer.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.tts.att;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import naturalvoices.ClientPlayer;
import naturalvoices.Player;
import org.apache.commons.configuration.Configuration;
import org.restcomm.connect.commons.cache.HashGenerator;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.tts.api.GetSpeechSynthesizerInfo;
import org.restcomm.connect.tts.api.SpeechSynthesizerException;
import org.restcomm.connect.tts.api.SpeechSynthesizerInfo;
import org.restcomm.connect.tts.api.SpeechSynthesizerRequest;
import org.restcomm.connect.tts.api.SpeechSynthesizerResponse;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public final class AttSpeechSynthesizer extends RestcommUntypedActor {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
private final Map<String, String> men;
private final Map<String, String> women;
private final String rootDir;
private final Player player;
public AttSpeechSynthesizer(final Configuration configuration) {
super();
men = new ConcurrentHashMap<String, String>();
women = new ConcurrentHashMap<String, String>();
load(configuration);
rootDir = configuration.getString("tts-client-directory");
player = new ClientPlayer(rootDir, configuration.getString("host"), configuration.getInt("port", 7000));
player.Verbose = configuration.getBoolean("verbose-output",false);
}
@Override
public void onReceive(final Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
if (SpeechSynthesizerRequest.class.equals(klass)) {
try {
final URI uri = synthesize(message);
if (sender != null) {
sender.tell(new SpeechSynthesizerResponse<URI>(uri), self);
}
} catch (final Exception exception) {
logger.error("There was an exception while trying to synthesize message: "+exception);
if (sender != null) {
sender.tell(new SpeechSynthesizerResponse<URI>(exception), self);
}
}
} else if (GetSpeechSynthesizerInfo.class.equals(klass)) {
sender.tell(new SpeechSynthesizerResponse<SpeechSynthesizerInfo>(info()), self);
}
}
private SpeechSynthesizerInfo info() {
return new SpeechSynthesizerInfo(men.keySet());
}
private void load(final Configuration configuration) throws RuntimeException {
// Initialize female voices.
women.put("en", configuration.getString("speakers.english.female"));
women.put("en-uk", configuration.getString("speakers.english-uk.female"));
women.put("es", configuration.getString("speakers.spanish.female"));
women.put("fr", configuration.getString("speakers.french.female"));
women.put("de-de", configuration.getString("speakers.german.female"));
women.put("it-it", configuration.getString("speakers.italian.female"));
women.put("pt-br", configuration.getString("speakers.brazilian-portuguese.female"));
// Initialize male voices.
men.put("en", configuration.getString("speakers.english.male"));
men.put("en-uk", configuration.getString("speakers.english-uk.male"));
men.put("es", configuration.getString("speakers.spanish.male"));
men.put("fr", configuration.getString("speakers.french.male"));
men.put("fr-ca", configuration.getString("speakers.canadian-french.male"));
men.put("de", configuration.getString("speakers.german.male"));
men.put("it", configuration.getString("speakers.italian.male"));
men.put("pt-br", configuration.getString("speakers.brazilian-portuguese.male"));
}
private URI synthesize(final Object message) throws IOException, SpeechSynthesizerException {
final SpeechSynthesizerRequest request = (SpeechSynthesizerRequest) message;
final String gender = request.gender();
final String language = request.language();
final String text = request.text();
if (language == null) {
if(logger.isInfoEnabled()) {
logger.info("There is no suitable speaker to synthesize " + request.language());
}
throw new IllegalArgumentException("There is no suitable language to synthesize " + request.language());
}
final String hash = HashGenerator.hashMessage(gender, language, text);
//setup parameters as needed
if(gender.equalsIgnoreCase("man")) {
player.setVoice(men.get(language));
} else {
player.setVoice(women.get(language));
}
player.setLatin1(true);
//source text to play
player.setSourceText(text);
//save it to a file
File file = new File(System.getProperty("java.io.tmpdir") + File.separator + hash + ".wav");
player.Convert(file.getAbsolutePath());
if(file.exists()) {
return file.toURI();
} else {
if(logger.isInfoEnabled()) {
logger.info("There was a problem with AT&T TTS server. Check configuration and that TTS Server is running");
}
throw new SpeechSynthesizerException("There was a problem with TTSClientFile. Check configuration and that TTS Server is running");
}
}
}
| 6,563 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaResourceBrokerTestExceptionHandling.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb/src/test/java/org/restcomm/connect/mrb/MediaResourceBrokerTestExceptionHandling.java | package org.restcomm.connect.mrb;
import static org.junit.Assert.assertTrue;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.restcomm.connect.mrb.util.MediaResourceBrokerTestUtil;
import akka.actor.ActorRef;
import akka.testkit.JavaTestKit;
/**
* @author [email protected] (Maria Farooq)
*/
public class MediaResourceBrokerTestExceptionHandling extends MediaResourceBrokerTestUtil{
private final static Logger logger = Logger.getLogger(MediaResourceBrokerTestExceptionHandling.class.getName());
@Before
public void before() throws UnknownHostException, ConfigurationException, MalformedURLException {
if(logger.isDebugEnabled())
logger.debug("before");
configurationNode1 = createCfg(CONFIG_PATH_NODE_1);
startDaoManager();
mediaResourceBrokerNode1 = mediaResourceBroker(configurationNode1.subset("media-server-manager"), daoManager, getClass().getClassLoader());
if(logger.isDebugEnabled())
logger.debug("before completed");
}
@After
public void after(){
if(logger.isDebugEnabled())
logger.debug("after");
daoManager.shutdown();
if(!mediaResourceBrokerNode1.isTerminated()){
system.stop(mediaResourceBrokerNode1);
}
if(logger.isDebugEnabled())
logger.debug("after completed");
}
/**
* testGetMediaGatewayExceptionHandling
*/
@Test
public void testGetMediaGatewayExceptionHandling() {
new JavaTestKit(system) {
{
final ActorRef tester = getRef();
if(logger.isDebugEnabled())
logger.debug("test GetMediaGateway Exception Handling");
String mrbRequest = new String("Hello");
mediaResourceBrokerNode1.tell(mrbRequest, tester);
String mrbResponse = expectMsgClass(String.class);
assertTrue(mrbResponse.equals(mrbRequest));
}};
}
}
| 2,136 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaResourceBrokerTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb/src/test/java/org/restcomm/connect/mrb/MediaResourceBrokerTest.java | package org.restcomm.connect.mrb;
import static org.junit.Assert.assertTrue;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.UUID;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.dao.entities.ConferenceDetailRecord;
import org.restcomm.connect.mgcp.MediaResourceBrokerResponse;
import org.restcomm.connect.mrb.api.GetMediaGateway;
import org.restcomm.connect.mrb.api.MediaGatewayForConference;
import org.restcomm.connect.mrb.util.MediaResourceBrokerTestUtil;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import akka.actor.ActorRef;
import akka.testkit.JavaTestKit;
/**
* @author [email protected] (Maria Farooq)
*/
public class MediaResourceBrokerTest extends MediaResourceBrokerTestUtil{
private final static Logger logger = Logger.getLogger(MediaResourceBrokerTest.class.getName());
private static final String EXISTING_CALL_SID="CA01a09068a1f348269b6670ef599a6e57";
private static final String NON_EXISTING_CALL_SID="CA00000000000000000000000000000000";
private static final String RANDOM_CONFERENCE_NAME = UUID.randomUUID().toString().replace("-", "");
@Before
public void before() throws UnknownHostException, ConfigurationException, MalformedURLException {
if(logger.isDebugEnabled())
logger.debug("before");
configurationNode1 = createCfg(CONFIG_PATH_NODE_1);
startDaoManager();
mediaResourceBrokerNode1 = mediaResourceBroker(configurationNode1.subset("media-server-manager"), daoManager, getClass().getClassLoader());
if(logger.isDebugEnabled())
logger.debug("before completed");
}
@After
public void after(){
if(logger.isDebugEnabled())
logger.debug("after");
daoManager.shutdown();
if(!mediaResourceBrokerNode1.isTerminated()){
system.stop(mediaResourceBrokerNode1);
}
if(logger.isDebugEnabled())
logger.debug("after completed");
}
/**
* testGetMediaGatewayForACall for an inbound call
*
*/
@Test
public void testGetMediaGatewayForAInboundCall() {
new JavaTestKit(system) {
{
final ActorRef tester = getRef();
if(logger.isDebugEnabled())
logger.debug("test 1 for a call found in DB - we should get mediagateway");
mediaResourceBrokerNode1.tell(new GetMediaGateway(new Sid(EXISTING_CALL_SID)), tester);
MediaResourceBrokerResponse<ActorRef> mrbResponse = expectMsgClass(MediaResourceBrokerResponse.class);
assertTrue(!mrbResponse.get().isTerminated());
if(logger.isDebugEnabled())
logger.debug("cdr should be updated with ms id");
CallDetailRecord cdr = daoManager.getCallDetailRecordsDao().getCallDetailRecord(new Sid(EXISTING_CALL_SID));
assertTrue(cdr.getMsId() != null);
if(logger.isDebugEnabled())
logger.debug("test 2 for a call not found in DB - we should get mediagateway anyway.");
mediaResourceBrokerNode1.tell(new GetMediaGateway(new Sid(NON_EXISTING_CALL_SID)), tester);
mrbResponse = expectMsgClass(MediaResourceBrokerResponse.class);
assertTrue(!mrbResponse.get().isTerminated());
}};
}
/**
* testGetMediaGatewayForACall for an outbound call
*
*/
@Test
public void testGetMediaGatewayForAnOutboundCall() {
new JavaTestKit(system) {
{
final ActorRef tester = getRef();
if(logger.isDebugEnabled())
logger.debug("testGetMediaGatewayForACall for an outbound call.");
Sid callSid = null;
mediaResourceBrokerNode1.tell(new GetMediaGateway(callSid), tester);
MediaResourceBrokerResponse<ActorRef> mrbResponse = expectMsgClass(MediaResourceBrokerResponse.class);
assertTrue(!mrbResponse.get().isTerminated());
}};
}
/**
* test GetMediaGateway For A Conference:
*/
@Test
public void testGetMediaGatewayForAConference() {
new JavaTestKit(system) {
{
final ActorRef tester = getRef();
if(logger.isDebugEnabled())
logger.debug("testGetMediaGatewayForAConference");
mediaResourceBrokerNode1.tell(new GetMediaGateway(new Sid(EXISTING_CALL_SID), ACCOUNT_SID_1+":"+RANDOM_CONFERENCE_NAME, null), tester);
MediaResourceBrokerResponse<MediaGatewayForConference> mrbResponse = expectMsgClass(MediaResourceBrokerResponse.class);
assertTrue(mrbResponse != null);
MediaGatewayForConference mgfc = mrbResponse.get();
assertTrue(mgfc != null);
if(logger.isDebugEnabled())
logger.debug(""+mgfc);
//make sure we get a working mediaGateway
assertTrue(mgfc.mediaGateway() != null && !mgfc.mediaGateway().isTerminated());
//make sure we get a generated conferenceSid and that we are not master since this is community mrb and have no notion of master/slave.
assertTrue(mgfc.conferenceSid() != null && !mgfc.isThisMaster());
ConferenceDetailRecord cdr = daoManager.getConferenceDetailRecordsDao().getConferenceDetailRecord(mgfc.conferenceSid());
if(logger.isDebugEnabled())
logger.debug("Conference cdr: "+cdr.getFriendlyName());
//mrb must generate a conference cdr
assertTrue(cdr != null);
// check status
assertTrue(cdr.getStatus().equals(ConferenceStateChanged.State.RUNNING_INITIALIZING+""));
// check friendly name
assertTrue(cdr.getFriendlyName().equals(RANDOM_CONFERENCE_NAME));
}};
}
}
| 6,050 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ConferenceMediaResourceBrokerTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb/src/test/java/org/restcomm/connect/mrb/ConferenceMediaResourceBrokerTest.java | package org.restcomm.connect.mrb;
import static org.junit.Assert.assertTrue;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.UUID;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.patterns.Observe;
import org.restcomm.connect.commons.patterns.Observing;
import org.restcomm.connect.dao.entities.ConferenceDetailRecord;
import org.restcomm.connect.mgcp.CreateConferenceEndpoint;
import org.restcomm.connect.mgcp.MediaGatewayResponse;
import org.restcomm.connect.mgcp.MediaResourceBrokerResponse;
import org.restcomm.connect.mgcp.MediaSession;
import org.restcomm.connect.mrb.api.ConferenceMediaResourceControllerStateChanged;
import org.restcomm.connect.mrb.api.GetConferenceMediaResourceController;
import org.restcomm.connect.mrb.api.GetMediaGateway;
import org.restcomm.connect.mrb.api.MediaGatewayForConference;
import org.restcomm.connect.mrb.api.StartConferenceMediaResourceController;
import org.restcomm.connect.mrb.util.MediaResourceBrokerTestUtil;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import akka.actor.ActorRef;
import akka.testkit.JavaTestKit;
/**
* @author [email protected] (Maria Farooq)
*/
public class ConferenceMediaResourceBrokerTest extends MediaResourceBrokerTestUtil{
private final static Logger logger = Logger.getLogger(ConferenceMediaResourceBrokerTest.class.getName());
private static final String EXISTING_CALL_SID="CA01a09068a1f348269b6670ef599a6e57";
private static final String RANDOM_CONFERENCE_NAME = UUID.randomUUID().toString().replace("-", "");
@Before
public void before() throws UnknownHostException, ConfigurationException, MalformedURLException {
if(logger.isDebugEnabled())
logger.debug("before");
configurationNode1 = createCfg(CONFIG_PATH_NODE_1);
startDaoManager();
mediaResourceBrokerNode1 = mediaResourceBroker(configurationNode1.subset("media-server-manager"), daoManager, getClass().getClassLoader());
if(logger.isDebugEnabled())
logger.debug("before completed");
}
@After
public void after(){
if(logger.isDebugEnabled())
logger.debug("after");
daoManager.shutdown();
if(!mediaResourceBrokerNode1.isTerminated()){
system.stop(mediaResourceBrokerNode1);
}
if(logger.isDebugEnabled())
logger.debug("after completed");
}
/**
* testConferenceMediaResourceController
*/
@Test
public void testConferenceMediaResourceController() {
new JavaTestKit(system) {
{
final ActorRef tester = getRef();
if(logger.isDebugEnabled())
logger.debug("testGetMediaGatewayForAConference");
mediaResourceBrokerNode1.tell(new GetMediaGateway(new Sid(EXISTING_CALL_SID), ACCOUNT_SID_1+":"+RANDOM_CONFERENCE_NAME, null), tester);
MediaResourceBrokerResponse<MediaGatewayForConference> mrbResponse = expectMsgClass(MediaResourceBrokerResponse.class);
assertTrue(mrbResponse != null);
MediaGatewayForConference mgfc = mrbResponse.get();
if(logger.isDebugEnabled())
logger.debug(""+mgfc);
ActorRef mediaGateway = mgfc.mediaGateway();
assertTrue(mgfc != null && mediaGateway != null && !mediaGateway.isTerminated() && mgfc.conferenceSid() != null && !mgfc.isThisMaster());
ConferenceDetailRecord cdr = daoManager.getConferenceDetailRecordsDao().getConferenceDetailRecord(mgfc.conferenceSid());
//mrb must generate a proper conference cdr
assertTrue(cdr != null && cdr.getStatus().equals(ConferenceStateChanged.State.RUNNING_INITIALIZING+"") && cdr.isMasterPresent() && cdr.getFriendlyName().equals(RANDOM_CONFERENCE_NAME));
//verify that we ger cmrc actor and its not terminated
mediaResourceBrokerNode1.tell(new GetConferenceMediaResourceController(RANDOM_CONFERENCE_NAME), tester);
MediaResourceBrokerResponse<ActorRef> mrbResponseForCMRC = expectMsgClass(MediaResourceBrokerResponse.class);
assertTrue(mrbResponseForCMRC != null);
ActorRef conferenceMediaResourceController = mrbResponseForCMRC.get();
assertTrue(conferenceMediaResourceController != null && !conferenceMediaResourceController.isTerminated());
// create media session
mediaGateway.tell(new org.restcomm.connect.mgcp.CreateMediaSession(), tester);
MediaSession mediaSession = (MediaSession)expectMsgClass(MediaGatewayResponse.class).get();
assertTrue(mediaSession != null);
//get conference endpoint.
mediaGateway.tell(new CreateConferenceEndpoint(mediaSession), tester);
MediaGatewayResponse<ActorRef> mgResponse = expectMsgClass(MediaGatewayResponse.class);
ActorRef conferenceEndpoint = mgResponse.get();
assertTrue(conferenceEndpoint != null && !conferenceEndpoint.isTerminated());
// Start ConferenceMediaResourceController & check conferenceMediaResourceController state, should be ACTIVE
conferenceMediaResourceController.tell(new Observe(tester), tester);
expectMsgClass(Observing.class);
conferenceMediaResourceController.tell(new StartConferenceMediaResourceController(conferenceEndpoint, cdr.getSid()), tester);
ConferenceMediaResourceControllerStateChanged conferenceMediaResourceControllerStateChanged = expectMsgClass(ConferenceMediaResourceControllerStateChanged.class);
assertTrue(conferenceMediaResourceControllerStateChanged.state().equals(ConferenceMediaResourceControllerStateChanged.MediaServerControllerState.ACTIVE));
cdr = daoManager.getConferenceDetailRecordsDao().getConferenceDetailRecord(mgfc.conferenceSid());
//check status
assertTrue(cdr.getStatus().equals(ConferenceStateChanged.State.RUNNING_MODERATOR_ABSENT+""));
}};
}
}
| 6,285 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaResourceBrokerTestUtil.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb/src/test/java/org/restcomm/connect/mrb/util/MediaResourceBrokerTestUtil.java | package org.restcomm.connect.mrb.util;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.loader.ObjectFactory;
import org.restcomm.connect.commons.util.DNSUtils;
import org.restcomm.connect.dao.ConferenceDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.entities.ConferenceDetailRecord;
import org.restcomm.connect.dao.mybatis.MybatisDaoManager;
import org.restcomm.connect.mrb.api.StartMediaResourceBroker;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;
import org.restcomm.connect.monitoringservice.MonitoringService;
/**
* @author [email protected] (Maria Farooq)
*/
public class MediaResourceBrokerTestUtil {
private final static Logger logger = Logger.getLogger(MediaResourceBrokerTestUtil.class.getName());
protected static ActorSystem system;
protected static Configuration configurationNode1;
protected static Configuration configurationNode2;
protected XMLConfiguration daoManagerConf = null;
protected MybatisDaoManager daoManager;
protected ActorRef mediaResourceBrokerNode1;
protected ActorRef mediaResourceBrokerNode2;
protected ActorRef monitoringService;
protected static final String RESTCOMM_CONFIG = "restcomm.xml";
protected static final String CONFIG_PATH_NODE_1 = "/restcomm.xml";
protected static final String CONFIG_PATH_NODE_2 = "/restcomm-node2.xml";
protected static final String CONFIG_PATH_DAO_MANAGER = "/dao-manager.xml";
protected static final String CONFERENCE_FRIENDLY_NAME_1 ="ACae6e420f425248d6a26948c17a9e2acf:1111";
protected static final String CONFERENCE_FRIENDLY_NAME_2 ="ACae6e420f425248d6a26948c17a9e2acf:1122";
protected static final String ACCOUNT_SID_1 ="ACae6e420f425248d6a26948c17a9e2acf";
@BeforeClass
public static void beforeClass() throws Exception {
Config config = ConfigFactory.load("akka_fault_tolerance_application.conf");
system = ActorSystem.create("test", config );
XMLConfiguration rectommXML = new XMLConfiguration();
rectommXML.setDelimiterParsingDisabled(true);
rectommXML.setAttributeSplittingDisabled(true);
rectommXML.load(RESTCOMM_CONFIG);
// initialize DnsUtilImpl ClassName
DNSUtils.initializeDnsUtilImplClassName(rectommXML);
}
@AfterClass
public static void afterClass() throws Exception {
system.shutdown();
}
protected Configuration createCfg(final String cfgFileName) throws ConfigurationException, MalformedURLException {
URL url = this.getClass().getResource(cfgFileName);
return new XMLConfiguration(url);
}
protected Configuration createDaoManagerCfg(final String cfgFileName) throws ConfigurationException, MalformedURLException {
URL url = this.getClass().getResource(cfgFileName);
return new XMLConfiguration(url);
}
private void cleanAllConferences() {
ConferenceDetailRecordsDao dao = daoManager.getConferenceDetailRecordsDao();
List<ConferenceDetailRecord> records = (List) dao.getConferenceDetailRecords(new Sid(ACCOUNT_SID_1));
for(int i=0; i<records.size(); i++){
ConferenceDetailRecord cdr = records.get(i);
cdr = cdr.setStatus(ConferenceStateChanged.State.COMPLETED+"");
dao.updateConferenceDetailRecordStatus(cdr);
}
}
private ActorRef monitoringService(final Configuration configuration, final DaoManager daoManager, final ClassLoader loader) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new MonitoringService(daoManager);
}
});
return system.actorOf(props);
}
protected ActorRef mediaResourceBroker(final Configuration configuration, final DaoManager storage, final ClassLoader loader) throws UnknownHostException{
ActorRef mrb = system.actorOf(new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
final String classpath = configuration.getString("mrb[@class]");
return (UntypedActor) new ObjectFactory(loader).getObjectInstance(classpath);
}
}));
if (monitoringService == null) {
monitoringService = monitoringService(configuration, daoManager,loader);
}
mrb.tell(new StartMediaResourceBroker(configuration, storage, loader, monitoringService), null);
return mrb;
}
protected void startDaoManager() throws ConfigurationException, MalformedURLException{
daoManagerConf = (XMLConfiguration)createDaoManagerCfg(CONFIG_PATH_DAO_MANAGER);
daoManager = new MybatisDaoManager();
daoManager.configure(configurationNode1, daoManagerConf);
daoManager.start();
}
}
| 5,593 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaResourceBrokerGeneric.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb/src/main/java/org/restcomm/connect/mrb/MediaResourceBrokerGeneric.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.mrb;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.joda.time.DateTime;
import org.mobicents.protocols.mgcp.stack.JainMgcpStackImpl;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.loader.ObjectFactory;
import org.restcomm.connect.commons.util.DNSUtils;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.ConferenceDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.MediaServersDao;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.dao.entities.ConferenceDetailRecord;
import org.restcomm.connect.dao.entities.ConferenceDetailRecordFilter;
import org.restcomm.connect.dao.entities.MediaServerEntity;
import org.restcomm.connect.mgcp.MediaResourceBrokerResponse;
import org.restcomm.connect.mgcp.PowerOnMediaGateway;
import org.restcomm.connect.mrb.api.GetConferenceMediaResourceController;
import org.restcomm.connect.mrb.api.GetMediaGateway;
import org.restcomm.connect.mrb.api.MediaGatewayForConference;
import org.restcomm.connect.mrb.api.StartMediaResourceBroker;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import jain.protocol.ip.mgcp.CreateProviderException;
import jain.protocol.ip.mgcp.JainMgcpProvider;
import jain.protocol.ip.mgcp.JainMgcpStack;
/**
* @author [email protected] (Maria Farooq)
*/
public class MediaResourceBrokerGeneric extends RestcommUntypedActor {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
protected Configuration configuration;
protected DaoManager storage;
protected ClassLoader loader;
protected ActorRef monitoringService;
protected ActorRef localMediaGateway;
protected String localMsId;
protected Map<String, ActorRef> mediaGatewayMap;
protected JainMgcpStack mgcpStack;
protected JainMgcpProvider mgcpProvider;
protected MediaServerEntity localMediaServerEntity;
public MediaResourceBrokerGeneric(){
super();
if (logger.isInfoEnabled()) {
logger.info(" ********** Community MediaResourceBroker Constructed");
}
}
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef sender = sender();
ActorRef self = self();
if (logger.isInfoEnabled()) {
logger.info(" ********** MediaResourceBroker " + self().path() + " Processing Message: " + klass.getName());
}
if (StartMediaResourceBroker.class.equals(klass)) {
onStartMediaResourceBroker((StartMediaResourceBroker)message, self, sender);
} else if (GetMediaGateway.class.equals(klass)) {
onGetMediaGateway((GetMediaGateway) message, self, sender);
} else if (GetConferenceMediaResourceController.class.equals(klass)){
sender.tell(new MediaResourceBrokerResponse<ActorRef>(getConferenceMediaResourceController()), self);
}
}
/**
* @param message
* @param self
* @param sender
* @throws UnknownHostException
*/
protected void onStartMediaResourceBroker(StartMediaResourceBroker message, ActorRef self, ActorRef sender) throws UnknownHostException{
this.configuration = message.configuration();
this.storage = message.storage();
this.loader = message.loader();
this.monitoringService = message.getMonitoringService();
localMediaServerEntity = uploadLocalMediaServersInDataBase();
bindMGCPStack(localMediaServerEntity.getLocalIpAddress(), localMediaServerEntity.getLocalPort());
this.localMediaGateway = turnOnMediaGateway(localMediaServerEntity);
this.mediaGatewayMap = new HashMap<String, ActorRef>();
mediaGatewayMap.put(localMediaServerEntity.getMsId()+"", localMediaGateway);
}
/**
* @param ip
* @param port
* @throws UnknownHostException
*/
protected void bindMGCPStack(String ip, int port) throws UnknownHostException {
mgcpStack = new JainMgcpStackImpl(DNSUtils.getByName(ip), port);
try {
mgcpProvider = mgcpStack.createProvider();
} catch (final CreateProviderException exception) {
logger.error(exception, "Could not create a JAIN MGCP provider.");
}
}
private ActorRef gateway() {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
final String classpath = configuration.getString("mgcp-server[@class]");
return (UntypedActor) new ObjectFactory(loader).getObjectInstance(classpath);
}
});
return getContext().actorOf(props);
}
/**
* @param mediaServerEntity
* @return
* @throws UnknownHostException
*/
protected ActorRef turnOnMediaGateway(MediaServerEntity mediaServerEntity) throws UnknownHostException {
if (logger.isDebugEnabled()) {
String mgcpServer = configuration.getString("mgcp-server[@class]");
logger.debug("Will switch on media gateway: "+mgcpServer);
}
ActorRef gateway = gateway();
final PowerOnMediaGateway.Builder builder = PowerOnMediaGateway.builder();
builder.setName(configuration.getString("mgcp-server[@name]"));
if(logger.isInfoEnabled())
logger.info("turnOnMediaGateway local ip: "+localMediaServerEntity.getLocalIpAddress()+" local port: "+localMediaServerEntity.getLocalPort()
+" remote ip: "+mediaServerEntity.getRemoteIpAddress()+" remote port: "+mediaServerEntity.getRemotePort());
builder.setLocalIP(DNSUtils.getByName(localMediaServerEntity.getLocalIpAddress()));
builder.setLocalPort(localMediaServerEntity.getLocalPort());
builder.setRemoteIP(DNSUtils.getByName(mediaServerEntity.getRemoteIpAddress()));
builder.setRemotePort(mediaServerEntity.getRemotePort());
if (mediaServerEntity.getExternalAddress() != null) {
builder.setExternalIP(DNSUtils.getByName(mediaServerEntity.getExternalAddress()));
builder.setUseNat(true);
} else {
builder.setUseNat(false);
}
builder.setTimeout(Long.parseLong(mediaServerEntity.getResponseTimeout()));
builder.setStack(mgcpStack);
builder.setProvider(mgcpProvider);
builder.setMonitoringService(monitoringService);
final PowerOnMediaGateway powerOn = builder.build();
gateway.tell(powerOn, null);
return gateway;
}
/**
* @return ConferenceMediaResourceController Community version actor
*/
protected ActorRef getConferenceMediaResourceController() {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new ConferenceMediaResourceControllerGeneric(localMediaGateway, configuration, storage, self());
}
});
return getContext().actorOf(props);
}
/**
* @param message - GetMediaGateway
* - (callSid: if MediaGateway is required for a call
* - conferenceName: if MediaGateway is required for a conference
* - msId: or if MediaGateway is required for a specific MediaServer in cluster)
* @param self
* @param sender
* @throws Exception
*/
protected void onGetMediaGateway(GetMediaGateway message, ActorRef self, ActorRef sender) throws Exception {
if(logger.isDebugEnabled()){
logger.debug(""+message.toString());
}
final String conferenceName = message.conferenceName();
final Sid callSid = message.callSid();
// if its not request for conference return home media-gateway (media-server associated with this RC instance)
if(conferenceName == null){
updateMSIdinCallDetailRecord(localMsId, callSid);
sender.tell(new MediaResourceBrokerResponse<ActorRef>(localMediaGateway), self);
}else{
final MediaGatewayForConference mgfc = addConferenceDetailRecord(conferenceName, callSid);
sender.tell(new MediaResourceBrokerResponse<MediaGatewayForConference>(mgfc), self);
}
}
/**
* @param msId
* @param callSid
*
*/
protected void updateMSIdinCallDetailRecord(final String msId, final Sid callSid){
if(callSid == null){
if(logger.isDebugEnabled())
logger.debug("Call Id is not specisfied, it can be an outbound call.");
}else{
CallDetailRecordsDao dao = storage.getCallDetailRecordsDao();
CallDetailRecord cdr = dao.getCallDetailRecord(callSid);
if(cdr != null){
cdr = cdr.setMsId(msId);
dao.updateCallDetailRecord(cdr);
}else{
logger.error("provided call id did not found");
}
}
}
/**
* @param conferenceName
* @param callSid
* @return
* @throws Exception
*/
protected MediaGatewayForConference addConferenceDetailRecord(final String conferenceName, final Sid callSid) throws Exception {
Sid sid = null;
MediaGatewayForConference mgc = null;
if(conferenceName == null ){
logger.error("provided conference name is null, this can lead to problems in future of this call");
}else{
CallDetailRecordsDao callDao = storage.getCallDetailRecordsDao();
CallDetailRecord callRecord = callDao.getCallDetailRecord(callSid);
if(callRecord != null){
ConferenceDetailRecordsDao dao = storage.getConferenceDetailRecordsDao();
// check if a conference with same name/account is running.
final String[] cnfNameAndAccount = conferenceName.split(":");
final String accountSid = cnfNameAndAccount[0];
final String friendlyName = cnfNameAndAccount[1];
ConferenceDetailRecordFilter filter = new ConferenceDetailRecordFilter(accountSid, "RUNNING%", null, null, friendlyName, 1, 0);
List<ConferenceDetailRecord> records = dao.getConferenceDetailRecords(filter);
ConferenceDetailRecord cdr;
if(records != null && records.size()>0){
cdr = records.get(0);
sid = cdr.getSid();
if(logger.isInfoEnabled())
logger.info("A conference with same name is running. According to database record. given SID is: "+sid);
}else{
// this is first record of this conference on all instances of
addNewConferenceRecord(accountSid, callRecord, friendlyName);
//getting CDR again as it is a conditional insert(select if exists or insert) to handle concurrency (incase another participant joins on another instance at very same time)
cdr = dao.getConferenceDetailRecords(filter).get(0);
sid = cdr.getSid();
if(logger.isInfoEnabled())
logger.info("addConferenceDetailRecord: SID: "+sid+" NAME: "+conferenceName);
}
mgc = new MediaGatewayForConference(sid, localMediaGateway, null, false);
}else{
logger.error("call record is null");
}
}
return mgc;
}
/**
* addNewConferenceRecord
* @param accountSid
* @param callRecord
* @param friendlyName
*/
protected void addNewConferenceRecord(String accountSid, CallDetailRecord callRecord, String friendlyName){
final ConferenceDetailRecord.Builder conferenceBuilder = ConferenceDetailRecord.builder();
Sid sid = Sid.generate(Sid.Type.CONFERENCE);
conferenceBuilder.setSid(sid);
conferenceBuilder.setDateCreated(DateTime.now());
conferenceBuilder.setAccountSid(new Sid(accountSid));
conferenceBuilder.setStatus(ConferenceStateChanged.State.RUNNING_INITIALIZING+"");
conferenceBuilder.setApiVersion(callRecord.getApiVersion());
final StringBuilder UriBuffer = new StringBuilder();
UriBuffer.append("/").append(callRecord.getApiVersion()).append("/Accounts/").append(accountSid).append("/Conferences/");
UriBuffer.append(sid);
final URI uri = URI.create(UriBuffer.toString());
conferenceBuilder.setUri(uri);
conferenceBuilder.setFriendlyName(friendlyName);
conferenceBuilder.setMasterMsId(localMsId);
ConferenceDetailRecord cdr = conferenceBuilder.build();
storage.getConferenceDetailRecordsDao().addConferenceDetailRecord(cdr);
}
/**
* @return
*/
protected MediaServerEntity uploadLocalMediaServersInDataBase() {
String localIpAdressForMediaGateway = configuration.getString("mgcp-server.local-address");
int localPortAdressForMediaGateway = Integer.parseInt(configuration.getString("mgcp-server.local-port"));
String remoteIpAddress = configuration.getString("mgcp-server.remote-address");
int remotePort = Integer.parseInt(configuration.getString("mgcp-server.remote-port"));
String responseTimeout = configuration.getString("mgcp-server.response-timeout");
String externalAddress = configuration.getString("mgcp-server.external-address");
final MediaServerEntity.Builder builder = MediaServerEntity.builder();
builder.setLocalIpAddress(localIpAdressForMediaGateway);
builder.setLocalPort(localPortAdressForMediaGateway);
builder.setRemoteIpAddress(remoteIpAddress);
builder.setRemotePort(remotePort);
builder.setResponseTimeout(responseTimeout);
builder.setExternalAddress(externalAddress);
MediaServersDao dao = storage.getMediaServersDao();
MediaServerEntity mediaServerEntity = builder.build();
final List<MediaServerEntity> existingMediaServersForSameIP = dao.getMediaServerEntityByIP(remoteIpAddress);
if(existingMediaServersForSameIP == null || existingMediaServersForSameIP.size()==0){
dao.addMediaServer(mediaServerEntity);
final List<MediaServerEntity> newMediaServerEntity = dao.getMediaServerEntityByIP(remoteIpAddress);
this.localMsId = newMediaServerEntity.get(0).getMsId()+"";
}else{
this.localMsId = existingMediaServersForSameIP.get(0).getMsId()+"";
mediaServerEntity = mediaServerEntity.setMsId(Integer.parseInt(this.localMsId));
dao.updateMediaServer(mediaServerEntity);
if(existingMediaServersForSameIP.size()>1)
logger.error("in DB: there are multiple media servers registered for same IP address");
}
return mediaServerEntity;
}
@Override
public void postStop() {
if(logger.isInfoEnabled())
logger.info("MRB on post stop");
// Cleanup resources
cleanup();
// Terminate actor
getContext().stop(self());
}
protected void cleanup() {
try {
if (mgcpStack != null){
mgcpStack = null;
}
mediaGatewayMap = null;
} catch (Exception e) {
logger.error("Exception is cleanup: ", e);
}
}
}
| 16,973 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ConferenceMediaResourceControllerGeneric.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb/src/main/java/org/restcomm/connect/mrb/ConferenceMediaResourceControllerGeneric.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.mrb;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.apache.commons.configuration.Configuration;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.dao.Sid;
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.fsm.TransitionNotFoundException;
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.dao.ConferenceDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.entities.ConferenceDetailRecord;
import org.restcomm.connect.dao.entities.MediaAttributes;
import org.restcomm.connect.mgcp.MediaGatewayResponse;
import org.restcomm.connect.mgcp.MediaSession;
import org.restcomm.connect.mrb.api.ConferenceMediaResourceControllerStateChanged;
import org.restcomm.connect.mrb.api.StartConferenceMediaResourceController;
import org.restcomm.connect.mrb.api.StopConferenceMediaResourceController;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse;
import org.restcomm.connect.mscontrol.api.messages.MediaGroupStateChanged;
import org.restcomm.connect.mscontrol.api.messages.Play;
import org.restcomm.connect.mscontrol.api.messages.Record;
import org.restcomm.connect.mscontrol.api.messages.StartMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.StartRecording;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup;
import org.restcomm.connect.mscontrol.api.messages.StopRecording;
import org.restcomm.connect.mscontrol.mms.MgcpMediaGroup;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author [email protected] (Maria Farooq)
*/
public class ConferenceMediaResourceControllerGeneric extends RestcommUntypedActor {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Finite State Machine
private final FiniteStateMachine fsm;
protected State uninitialized;
protected State acquiringConferenceInfo;
protected State creatingMediaGroup;
protected State preActive;
protected State active;
protected State stopping;
protected State inactive;
protected State failed;
protected ActorRef localMediaGateway;
protected ActorRef mediaGroup;
protected MediaSession localMediaSession;
protected ActorRef localConfernceEndpoint;
protected DaoManager storage;
protected Configuration configuration;
protected ConferenceDetailRecord cdr;
protected Sid conferenceSid;
// Runtime media operations
protected Boolean playing;
protected Boolean fail;
protected Boolean recording;
protected DateTime recordStarted;
// Observer pattern
protected final List<ActorRef> observers;
protected ActorRef mrb;
public ConferenceMediaResourceControllerGeneric(ActorRef localMediaGateway, final Configuration configuration, final DaoManager storage, final ActorRef mrb){
super();
final ActorRef source = self();
// Initialize the states for the FSM.
this.uninitialized = new State("uninitialized", null, null);
this.creatingMediaGroup = new State("creating media group", new CreatingMediaGroup(source), null);
this.acquiringConferenceInfo = new State("getting Conference Info From DB", new AcquiringConferenceInfo(source), null);
this.preActive = new State("pre active", new PreActive(source));
this.active = new State("active", new Active(source));
this.stopping = new State("stopping", new Stopping(source));
this.inactive = new State("inactive", new Inactive(source));
this.failed = new State("failed", new Failed(source));
// Transitions for the FSM.
final Set<Transition> transitions = new HashSet<Transition>();
//states for master
transitions.add(new Transition(uninitialized, acquiringConferenceInfo));
transitions.add(new Transition(acquiringConferenceInfo, creatingMediaGroup));
transitions.add(new Transition(creatingMediaGroup, preActive));
transitions.add(new Transition(preActive, active));
transitions.add(new Transition(active, stopping));
transitions.add(new Transition(stopping, inactive));
// Initialize the FSM.
this.fsm = new FiniteStateMachine(uninitialized, transitions);
this.storage = storage;
this.configuration = configuration;
this.localMediaGateway = localMediaGateway;
// Runtime media operations
this.playing = Boolean.FALSE;
this.recording = Boolean.FALSE;
this.fail = Boolean.FALSE;
this.mrb = mrb;
// Observers
this.observers = new ArrayList<ActorRef>(1);
}
protected boolean is(State state) {
return this.fsm.state().equals(state);
}
protected void broadcast(Object message) {
if (!this.observers.isEmpty()) {
final ActorRef self = self();
synchronized (this.observers) {
for (ActorRef observer : observers) {
observer.tell(message, self);
}
}
}
}
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef sender = sender();
ActorRef self = self();
final State state = fsm.state();
if (logger.isInfoEnabled()) {
logger.info(" ********** ConferenceMediaResourceController " + self().path() + " Processing Message: " + klass.getName());
logger.info(" ********** ConferenceMediaResourceController " + self().path() + " Current State: \"" + state.toString());
}
try{
if (Observe.class.equals(klass)) {
onObserve((Observe) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
onStopObserving((StopObserving) message, self, sender);
} else if (StartConferenceMediaResourceController.class.equals(klass)){
onStartConferenceMediaResourceController((StartConferenceMediaResourceController) message, self, sender);
} else if (MediaGatewayResponse.class.equals(klass)) {
onMediaGatewayResponse((MediaGatewayResponse<?>) message, self, sender);
} else if (MediaGroupStateChanged.class.equals(klass)) {
onMediaGroupStateChanged((MediaGroupStateChanged) message, self, sender);
} else if (StopMediaGroup.class.equals(klass)) {
onStopMediaGroup((StopMediaGroup) message, self, sender);
} else if (Play.class.equals(klass)) {
onPlay((Play) message, self, sender);
} else if(MediaGroupResponse.class.equals(klass)) {
onMediaGroupResponse((MediaGroupResponse<String>) message, self, sender);
} else if (StartRecording.class.equals(klass)) {
onStartRecording((StartRecording) message, self, sender);
} else if (StopRecording.class.equals(klass)) {
onStopRecording((StopRecording) message, self, sender);
} else if (StopConferenceMediaResourceController.class.equals(klass)) {
onStopConferenceMediaResourceController((StopConferenceMediaResourceController) message, self, sender);
}
}catch(Exception e){
logger.error("Exception in onReceive of CMRC: {}", e);
try{
fsm.transition(message, failed);
}catch(TransitionNotFoundException tfe){
/* some state might not allow direct transition to failed state:
* in that case catch the TransitionFailedException and print error.
*/
logger.error("CMRC failed at a state which does not allow direct transition to FAILED state. Current state is: " + state.toString());
}
}
}
protected void onObserve(Observe message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
synchronized (this.observers) {
this.observers.add(observer);
observer.tell(new Observing(self), self);
}
}
}
protected void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
this.observers.remove(observer);
}
}
protected void onStartConferenceMediaResourceController(StartConferenceMediaResourceController message, ActorRef self, ActorRef sender) throws Exception{
if (is(uninitialized)) {
if(logger.isDebugEnabled())
logger.debug("onStartConferenceMediaResourceController: conferenceSid: "+message.conferenceSid()+" cnfEndpoint: "+message.cnfEndpoint());
this.localConfernceEndpoint = message.cnfEndpoint();
this.conferenceSid = message.conferenceSid();
fsm.transition(message, acquiringConferenceInfo);
}
}
protected void onMediaGatewayResponse(MediaGatewayResponse<?> message, ActorRef self, ActorRef sender) throws Exception {
logger.info("inside onMediaGatewayResponse: state = "+fsm.state());
if (is(acquiringConferenceInfo)){
this.localMediaSession = (MediaSession) message.get();
this.fsm.transition(message, creatingMediaGroup);
}
}
protected void onStopConferenceMediaResourceController(StopConferenceMediaResourceController message, ActorRef self,
ActorRef sender) throws Exception {
fsm.transition(message, stopping);
}
protected void onMediaGroupStateChanged(MediaGroupStateChanged message, ActorRef self, ActorRef sender) throws Exception {
if(logger.isDebugEnabled())
logger.debug("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ onMediaGroupStateChanged - received STATE is: "+message.state()+" current fsm STATE is: "+fsm.state()+" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^");
switch (message.state()) {
case ACTIVE:
if (is(creatingMediaGroup)) {
fsm.transition(message, preActive);
}
break;
case INACTIVE:
if (is(creatingMediaGroup)) {
this.fail = Boolean.TRUE;
fsm.transition(message, failed);
} else if (is(stopping)) {
// Stop media group actor
this.mediaGroup.tell(new StopObserving(self), self);
context().stop(mediaGroup);
this.mediaGroup = null;
// Move to next state
this.fsm.transition(message, fail ? failed : inactive);
}
break;
default:
break;
}
}
protected void onPlay(Play message, ActorRef self, ActorRef sender) {
/*
* https://github.com/RestComm/Restcomm-Connect/issues/2024
* We actually dont care about running beeps or MOH, we will send new play
* it will stop exiting playing audio and will play new one
* (unless both are exactly same)
*/
//if (!playing) {
//this.playing = Boolean.TRUE;
this.mediaGroup.tell(message, self);
//}
}
protected void onStartRecording(StartRecording message, ActorRef self, ActorRef sender) throws Exception {
if (is(active) && !recording) {
String finishOnKey = "1234567890*#";
int maxLength = 3600;
int timeout = 5;
this.recording = Boolean.TRUE;
this.recordStarted = DateTime.now();
// Tell media group to start recording
Record record = new Record(message.getRecordingUri(), timeout, maxLength, finishOnKey, MediaAttributes.MediaType.AUDIO_ONLY);
this.mediaGroup.tell(record, null);
}
}
protected void onStopRecording(StopRecording message, ActorRef self, ActorRef sender) throws Exception {
if (is(active) && recording) {
this.recording = Boolean.FALSE;
mediaGroup.tell(new Stop(), null);
}
}
protected void onMediaGroupResponse(MediaGroupResponse<String> message, ActorRef self, ActorRef sender) throws Exception {
if (this.playing) {
this.playing = Boolean.FALSE;
}
}
protected void onStopMediaGroup(StopMediaGroup message, ActorRef self, ActorRef sender) {
//if (is(active)) {
// Stop the primary media group
this.mediaGroup.tell(new Stop(), self);
this.playing = Boolean.FALSE;
//}
}
/*
* ACTIONS
*
*/
protected abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
protected final class AcquiringConferenceInfo extends AbstractAction {
public AcquiringConferenceInfo(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object msg) throws Exception {
if(logger.isDebugEnabled())
logger.debug("current state is: "+fsm.state());
//check master MS info from DB
final ConferenceDetailRecordsDao conferenceDetailRecordsDao = storage.getConferenceDetailRecordsDao();
cdr = conferenceDetailRecordsDao.getConferenceDetailRecord(conferenceSid);
if(cdr == null){
logger.error("there is no information available in DB to proceed with this CMRC");
fsm.transition(msg, failed);
}else{
if(logger.isDebugEnabled()){
logger.debug("first participant Joined on master MS and sent message to CMRC");
}
localMediaGateway.tell(new org.restcomm.connect.mgcp.CreateMediaSession(), source);
}
}
}
protected final class CreatingMediaGroup extends AbstractAction {
public CreatingMediaGroup(ActorRef source) {
super(source);
}
protected ActorRef createMediaGroup(final Object message) {
final Props props = new Props(new UntypedActorFactory() {
protected static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new MgcpMediaGroup(localMediaGateway, localMediaSession, localConfernceEndpoint);
}
});
return getContext().actorOf(props);
}
@Override
public void execute(Object message) throws Exception {
mediaGroup = createMediaGroup(message);
mediaGroup.tell(new Observe(super.source), super.source);
mediaGroup.tell(new StartMediaGroup(), super.source);
}
}
protected final class PreActive extends AbstractAction {
public PreActive(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isDebugEnabled())
logger.debug("CMRC is in pre ACTIVE NOW...");
// later Conference will update the status as per informed by VI as per RCML
updateConferenceStatus(ConferenceStateChanged.State.RUNNING_MODERATOR_ABSENT+"");
broadcast(new ConferenceMediaResourceControllerStateChanged(ConferenceMediaResourceControllerStateChanged.MediaServerControllerState.ACTIVE, cdr.getStatus()));
fsm.transition(message, active);
}
}
protected final class Active extends AbstractAction {
public Active(final ActorRef source) {
super(source);
}
@Override
public void execute(final Object message) throws Exception {
if(logger.isInfoEnabled())
logger.info("CMRC is ACTIVE NOW...");
}
}
protected class Stopping extends AbstractAction {
public Stopping(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
if(logger.isInfoEnabled())
logger.info("CMRC is STOPPING NOW...");
updateConferenceStatus(ConferenceStateChanged.State.COMPLETED+"");
// Destroy Media Group
mediaGroup.tell(new StopMediaGroup(), super.source);
}
}
protected abstract class FinalState extends AbstractAction {
protected final ConferenceMediaResourceControllerStateChanged.MediaServerControllerState state;
public FinalState(ActorRef source, final ConferenceMediaResourceControllerStateChanged.MediaServerControllerState state) {
super(source);
this.state = state;
}
@Override
public void execute(Object message) throws Exception {
// Notify observers the controller has stopped
broadcast(new ConferenceMediaResourceControllerStateChanged(state, true));
}
}
protected final class Inactive extends FinalState {
public Inactive(final ActorRef source) {
super(source, ConferenceMediaResourceControllerStateChanged.MediaServerControllerState.INACTIVE);
}
}
protected final class Failed extends FinalState {
public Failed(final ActorRef source) {
super(source, ConferenceMediaResourceControllerStateChanged.MediaServerControllerState.FAILED);
}
}
@Override
public void postStop() {
if(logger.isDebugEnabled())
logger.debug("postStop called for: "+self());
// Cleanup resources
cleanup();
// Clean observers
observers.clear();
// Terminate actor
if(self() != null && !self().isTerminated()){
getContext().stop(self());
}
}
protected void cleanup() {
}
/*
* Database Utility Functions
*
*/
protected void updateConferenceStatus(String status){
if(cdr != null){
final ConferenceDetailRecordsDao dao = storage.getConferenceDetailRecordsDao();
cdr = dao.getConferenceDetailRecord(conferenceSid);
cdr = cdr.setStatus(status);
dao.updateConferenceDetailRecordStatus(cdr);
}
}
}
| 20,187 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MockMediaResourceBroker.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb/src/main/java/org/restcomm/connect/mrb/mock/MockMediaResourceBroker.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.mrb.mock;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import org.restcomm.connect.mgcp.MediaResourceBrokerResponse;
import org.restcomm.connect.mrb.MediaResourceBrokerGeneric;
import org.restcomm.connect.mrb.api.GetConferenceMediaResourceController;
import org.restcomm.connect.mrb.api.GetMediaGateway;
import org.restcomm.connect.mrb.api.StartMediaResourceBroker;
import java.net.UnknownHostException;
import java.util.HashMap;
/**
* @author [email protected] (Maria Farooq)
*
*/
public class MockMediaResourceBroker extends MediaResourceBrokerGeneric {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
public MockMediaResourceBroker(){
super();
if (logger.isInfoEnabled()) {
logger.info(" ********** MockMediaResourceBroker Constructed.");
}
}
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef sender = sender();
ActorRef self = self();
if (logger.isInfoEnabled()) {
logger.info(" ********** MockMediaResourceBroker " + self().path() + " Processing Message: " + klass.getName());
}
if (StartMediaResourceBroker.class.equals(klass)) {
onStartMediaResourceBroker((StartMediaResourceBroker)message, self, sender);
} else if (GetMediaGateway.class.equals(klass)) {
onGetMediaGateway((GetMediaGateway) message, self, sender);
} else if (GetConferenceMediaResourceController.class.equals(klass)){
sender.tell(new MediaResourceBrokerResponse<ActorRef>(getConferenceMediaResourceController()), self);
} else if(String.class.equals(klass)){
//this is for experimental purpose to see how akka actor behave on exceptions..
//remove try catch to do the experiment..
//try{
testExceptionOnRecieve((String)message, self, sender);
/*}catch(Exception e){
logger.error("MockMediaResourceBroker onReceive: {}", e);
}finally{
sender.tell(message, self);
}*/
}
}
private void testExceptionOnRecieve(String message, ActorRef self, ActorRef sender){
String s = null;
s.equalsIgnoreCase("blabla");
}
/* (non-Javadoc)
* @see org.restcomm.connect.telscale.mrb.MediaResourceBroker#onStartMediaResourceBroker(org.restcomm.connect.mrb.api.StartMediaResourceBroker, akka.actor.ActorRef, akka.actor.ActorRef)
*/
@Override
protected void onStartMediaResourceBroker(StartMediaResourceBroker message, ActorRef self, ActorRef sender) throws UnknownHostException{
this.configuration = message.configuration();
this.storage = message.storage();
this.loader = message.loader();
this.monitoringService = message.getMonitoringService();
localMediaServerEntity = uploadLocalMediaServersInDataBase();
this.localMediaGateway = turnOnMediaGateway(localMediaServerEntity);
this.mediaGatewayMap = new HashMap<String, ActorRef>();
mediaGatewayMap.put(localMediaServerEntity.getMsId()+"", localMediaGateway);
}
@Override
public void postStop() {
if(logger.isInfoEnabled())
logger.info("MRB Mock post stop called");
super.postStop();
}
}
| 4,379 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SdrService.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sdr.api/src/main/java/org/restcomm/connect/sdr/api/SdrService.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2017, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it andor 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 OUT ANY WARRANTY; out 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 this program. If not, see <http:www.gnu.orglicenses>
*/
package org.restcomm.connect.sdr.api;
import akka.actor.ActorRef;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.stream.StreamEvent;
import org.restcomm.connect.dao.entities.Recording;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.telephony.api.CallInfoStreamEvent;
import org.restcomm.connect.telephony.api.events.UssdStreamEvent;
/**
* @author [email protected] (Oleg Agafonov)
*/
public abstract class SdrService extends RestcommUntypedActor {
@Override
public void onReceive(Object message) throws Exception {
ActorRef self = self();
ActorRef sender = sender();
if (message instanceof StartSdrService) {
getContext().system().eventStream().subscribe(self, StreamEvent.class);
onStartSdrService((StartSdrService) message, self, sender);
} else if (message instanceof CallInfoStreamEvent) {
onCallInfoStreamEvent((CallInfoStreamEvent) message, self, sender);
} else if (message instanceof UssdStreamEvent) {
onUssdStreamEvent((UssdStreamEvent) message, self, sender);
} else if (message instanceof SmsMessage) {
onSmsMessage((SmsMessage) message, self, sender);
} else if (message instanceof Recording) {
onRecording((Recording)message, self, sender);
}
}
protected abstract void onStartSdrService(StartSdrService message, ActorRef self, ActorRef sender);
protected abstract void onCallInfoStreamEvent(CallInfoStreamEvent message, ActorRef self, ActorRef sender);
protected abstract void onSmsMessage(SmsMessage message, ActorRef self, ActorRef sender);
protected abstract void onUssdStreamEvent(UssdStreamEvent message, ActorRef self, ActorRef sender);
protected abstract void onRecording(Recording recording, ActorRef self, ActorRef sender);
}
| 2,720 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
StartSdrService.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.sdr.api/src/main/java/org/restcomm/connect/sdr/api/StartSdrService.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2017, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it andor 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 OUT ANY WARRANTY; out 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 this program. If not, see <http:www.gnu.orglicenses>
*/
package org.restcomm.connect.sdr.api;
import org.apache.commons.configuration.Configuration;
/**
* @author [email protected] (Oleg Agafonov)
*/
public class StartSdrService {
private final Configuration configuration;
public StartSdrService(Configuration configuration) {
this.configuration = configuration;
}
public Configuration getConfiguration() {
return configuration;
}
}
| 1,218 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ConferenceTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/test/org/restcomm/connect/telephony/ConferenceTest.java | package org.restcomm.connect.telephony;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.patterns.Observe;
import org.restcomm.connect.commons.patterns.Observing;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.ConferenceDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.http.client.CallApiResponse;
import org.restcomm.connect.http.client.api.CallApiClient;
import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory;
import org.restcomm.connect.mscontrol.api.messages.JoinComplete;
import org.restcomm.connect.mscontrol.api.messages.Leave;
import org.restcomm.connect.mscontrol.api.messages.Left;
import org.restcomm.connect.mscontrol.mms.MockFailingMmsControllerFactory;
import org.restcomm.connect.mscontrol.mms.MockMmsControllerFactory;
import org.restcomm.connect.telephony.api.AddParticipant;
import org.restcomm.connect.telephony.api.ConferenceCenterResponse;
import org.restcomm.connect.telephony.api.ConferenceInfo;
import org.restcomm.connect.telephony.api.ConferenceResponse;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import org.restcomm.connect.telephony.api.CreateConference;
import org.restcomm.connect.telephony.api.StopConference;
import org.restcomm.connect.telephony.util.ConferenceTestUtil;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import akka.testkit.JavaTestKit;
import scala.concurrent.duration.FiniteDuration;
public class ConferenceTest extends ConferenceTestUtil{
private final static Logger logger = Logger.getLogger(ConferenceTest.class.getName());
private static final Sid TEST_CALL_SID = new Sid("ID8deb35fc5121429fa96635aebe3976d2-CA6d61e3877f3c47828a26efc498a9e8f9");
private static final String TEST_CALL_URI = "/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Calls/ID8deb35fc5121429fa96635aebe3976d2-CA6d61e3877f3c47828a26efc498a9e8f9";
@Before
public void before() throws UnknownHostException, ConfigurationException, MalformedURLException {
configurationNode1 = createCfg(CONFIG_PATH_NODE_1);
startDaoManager();
}
@After
public void after(){
try {
daoManager.shutdown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Test
public void testJoinStoppingConference() {
new JavaTestKit(system) {
{
final ActorRef tester = getRef();
// Create MockFailingMmsControllerFactory
MediaServerControllerFactory factory = new MockFailingMmsControllerFactory(system, null);
// Create ConferenceCenter
final ActorRef conferenceCenter = conferenceCenter(factory, daoManager);
// get a fresh conference from conferenecneter
final CreateConference create = new CreateConference(CONFERENCE_FRIENDLY_NAME_1, new Sid(CALL_SID));
conferenceCenter.tell(create, tester);
ConferenceCenterResponse conferenceCenterResponse = expectMsgClass(ConferenceCenterResponse.class);
ActorRef conferene = conferenceCenterResponse.get();
// start observing conference
conferene.tell(new Observe(tester), tester);
Observing observingResponse = expectMsgClass(Observing.class);
assertTrue(observingResponse.succeeded());
// addparticipant in conference
conferene.tell(new AddParticipant(tester), tester);
//receieve sent to observers
expectMsgClass(ConferenceResponse.class);
//receieve sent to call (since we are pretending to call&VoiceInterpreter)
expectMsgClass(ConferenceResponse.class);
expectMsgClass(JoinComplete.class);
// stop conference
conferene.tell(new Left(), tester);
expectMsgClass(ConferenceResponse.class);
// get same conference again from conferenecneter
conferenceCenter.tell(create, tester);
conferenceCenterResponse = expectMsgClass(ConferenceCenterResponse.class);
ActorRef conferene2 = conferenceCenterResponse.get();
if(!conferene2.path().equals(conferene.path())){
assertTrue(!conferene2.path().equals(conferene.path()));
// start observing conference
conferene2.tell(new Observe(tester), tester);
observingResponse = expectMsgClass(Observing.class);
assertTrue(observingResponse.succeeded());
// addparticipant in conference
conferene2.tell(new AddParticipant(tester), tester);
expectMsgClass(ConferenceResponse.class);
expectMsgClass(ConferenceResponse.class);
expectMsgClass(JoinComplete.class);
}else{
logger.info("testing VI impl");
// start observing conference
conferene2.tell(new Observe(tester), tester);
observingResponse = expectMsgClass(Observing.class);
assertTrue(observingResponse.succeeded());
// addparticipant in conference
conferene2.tell(new AddParticipant(tester), tester);
ConferenceStateChanged csc = expectMsgClass(ConferenceStateChanged.class);
assertTrue(csc.state().equals(ConferenceStateChanged.State.STOPPING));
// get same conference again from conferenecneter
conferenceCenter.tell(create, tester);
conferenceCenterResponse = expectMsgClass(ConferenceCenterResponse.class);
conferene2 = conferenceCenterResponse.get();
assertTrue(!conferene2.path().equals(conferene.path()));
}
}};
}
@Test
public void testJoinCompletedConference() throws URISyntaxException {
new JavaTestKit(system) {
{
daoManager = mock(DaoManager.class);
CallDetailRecordsDao callDetailRecordsDao = mock(CallDetailRecordsDao.class);
ConferenceDetailRecordsDao conferenceDetailRecordsDao = mock(ConferenceDetailRecordsDao.class);
when(callDetailRecordsDao.getTotalRunningCallDetailRecordsByConferenceSid(any(Sid.class))).thenReturn(0);
when(daoManager.getCallDetailRecordsDao()).thenReturn(callDetailRecordsDao);
when(daoManager.getConferenceDetailRecordsDao()).thenReturn(conferenceDetailRecordsDao);
final ActorRef tester = getRef();
// Create MockFailingMmsControllerFactory
MediaServerControllerFactory factory = new MockMmsControllerFactory(system, null);
// Create ConferenceCenter
final ActorRef conferenceCenter = conferenceCenter(factory, daoManager);
// get a fresh conference from conferenecneter
final CreateConference create = new CreateConference(CONFERENCE_FRIENDLY_NAME_1, new Sid(CALL_SID));
conferenceCenter.tell(create, tester);
ConferenceCenterResponse conferenceCenterResponse = expectMsgClass(ConferenceCenterResponse.class);
ActorRef conferene = conferenceCenterResponse.get();
// start observing conference
conferene.tell(new Observe(tester), tester);
Observing observingResponse = expectMsgClass(Observing.class);
assertTrue(observingResponse.succeeded());
// addparticipant in conference
conferene.tell(new AddParticipant(tester), tester);
//receieve sent to observers
expectMsgClass(ConferenceResponse.class);
//receieve sent to call (since we are pretending to call&VoiceInterpreter)
expectMsgClass(ConferenceResponse.class);
expectMsgClass(JoinComplete.class);
// stop conference
conferene.tell(new Left(), tester);
expectMsgClass(ConferenceResponse.class);
expectMsgClass(ConferenceStateChanged.class);
// get same conference again from conferenecneter
conferenceCenter.tell(create, tester);
conferenceCenterResponse = expectMsgClass(ConferenceCenterResponse.class);
logger.info("conferenceCenterResponse 2: "+conferenceCenterResponse);
ActorRef conferene2 = conferenceCenterResponse.get();
assertTrue(!conferene2.path().equals(conferene.path()));
// start observing conference
conferene2.tell(new Observe(tester), tester);
observingResponse = expectMsgClass(Observing.class);
assertTrue(observingResponse.succeeded());
// addparticipant in conference
conferene2.tell(new AddParticipant(tester), tester);
expectMsgClass(ConferenceResponse.class);
expectMsgClass(ConferenceResponse.class);
expectMsgClass(JoinComplete.class);
}};
}
@Test
public void testConferenceTimeout() throws InterruptedException, URISyntaxException {
new JavaTestKit(system) {
{
FiniteDuration finiteDuration =FiniteDuration.apply(15, TimeUnit.SECONDS);
daoManager = mock(DaoManager.class);
ConferenceDetailRecordsDao conferenceDetailRecordsDao = mock(ConferenceDetailRecordsDao.class);
CallDetailRecordsDao callDetailRecordsDao = mock(CallDetailRecordsDao.class);
when(callDetailRecordsDao.getRunningCallDetailRecordsByConferenceSid(any(Sid.class))).thenReturn(mockedRemoteParticipants());
when(daoManager.getConferenceDetailRecordsDao()).thenReturn(conferenceDetailRecordsDao);
when(daoManager.getCallDetailRecordsDao()).thenReturn(callDetailRecordsDao);
// set conference timeout to 10 seconds
RestcommConfiguration.getInstance().getMain().setConferenceTimeout(10);
final ActorRef tester = getRef();
// Create MockMmsControllerFactory
MediaServerControllerFactory factory = new MockMmsControllerFactory(system, null);
// Create ConferenceCenter
final ActorRef conferenceCenter = conferenceCenter(factory, daoManager);
// get a fresh conference from conferenecneter
final CreateConference create = new CreateConference(CONFERENCE_FRIENDLY_NAME_1, new Sid(CALL_SID));
conferenceCenter.tell(create, tester);
ConferenceCenterResponse conferenceCenterResponse = expectMsgClass(ConferenceCenterResponse.class);
ActorRef conferene = conferenceCenterResponse.get();
// start observing conference
conferene.tell(new Observe(tester), tester);
Observing observingResponse = expectMsgClass(Observing.class);
assertTrue(observingResponse.succeeded());
// addparticipant in conference
conferene.tell(new AddParticipant(tester), tester);
//receieve sent to observers
ConferenceResponse addParticipantConferenceResponse = expectMsgClass(ConferenceResponse.class);
ConferenceInfo conferenceInfo = (ConferenceInfo)addParticipantConferenceResponse.get();
logger.info("conferenceInfo: "+conferenceInfo);
//receieve sent to call (since we are pretending to call&VoiceInterpreter)
expectMsgClass(finiteDuration, ConferenceResponse.class);
expectMsgClass(finiteDuration, JoinComplete.class);
expectMsgClass(finiteDuration, Leave.class);
ActorRef testActor = system.actorOf(new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new CallApiClient(TEST_CALL_SID, daoManager);
}
}));
assertFalse(testActor.isTerminated());
//send a CallApiResponse to conference on behalf of CallApiClient to see if it stops it
conferene.tell(new CallApiResponse(new Exception("testing")), testActor);
//wait a bit
Thread.sleep(500);
assertTrue(testActor.isTerminated());
//tell conference that call left on behalf of the call actor
conferene.tell(new Left(tester), tester);
expectMsgClass(finiteDuration, ConferenceResponse.class);
ConferenceStateChanged conferenceStateChanged = expectMsgClass(finiteDuration, ConferenceStateChanged.class);
assertEquals(ConferenceStateChanged.State.COMPLETED, conferenceStateChanged.state());
}};
}
private List<CallDetailRecord> mockedRemoteParticipants() throws URISyntaxException{
List<CallDetailRecord> mockedRemoteParticipants = new ArrayList<CallDetailRecord>();
CallDetailRecord.Builder builder = CallDetailRecord.builder();
builder.setSid(TEST_CALL_SID);
builder.setUri(new URI(TEST_CALL_URI));
builder.setConferenceSid(TEST_CNF_SID);
builder.setInstanceId(Sid.generate(Sid.Type.INSTANCE)+"");
mockedRemoteParticipants.add(builder.build());
return mockedRemoteParticipants;
}
private ActorRef conferenceCenter(final MediaServerControllerFactory factory, final DaoManager daoManager) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new ConferenceCenter(factory, daoManager);
}
});
return system.actorOf(props);
}
@Test
public void testStopConferenceWithNoLocalParticipants() throws URISyntaxException {
new JavaTestKit(system) {
{
daoManager = mock(DaoManager.class);
CallDetailRecordsDao callDetailRecordsDao = mock(CallDetailRecordsDao.class);
ConferenceDetailRecordsDao conferenceDetailRecordsDao = mock(ConferenceDetailRecordsDao.class);
when(callDetailRecordsDao.getTotalRunningCallDetailRecordsByConferenceSid(any(Sid.class))).thenReturn(0);
when(daoManager.getCallDetailRecordsDao()).thenReturn(callDetailRecordsDao);
when(daoManager.getConferenceDetailRecordsDao()).thenReturn(conferenceDetailRecordsDao);
final ActorRef tester = getRef();
// Create MockFailingMmsControllerFactory
MediaServerControllerFactory factory = new MockMmsControllerFactory(system, null);
// Create ConferenceCenter
final ActorRef conferenceCenter = conferenceCenter(factory, daoManager);
// get a fresh conference from conferenecneter
final CreateConference create = new CreateConference(CONFERENCE_FRIENDLY_NAME_1, new Sid(CALL_SID));
conferenceCenter.tell(create, tester);
ConferenceCenterResponse conferenceCenterResponse = expectMsgClass(ConferenceCenterResponse.class);
ActorRef conferene = conferenceCenterResponse.get();
// start observing conference
conferene.tell(new Observe(tester), tester);
Observing observingResponse = expectMsgClass(Observing.class);
assertTrue(observingResponse.succeeded());
// stop conference while no local participants is there
conferene.tell(new StopConference(), tester);
ConferenceStateChanged conferenceStateChanged = expectMsgClass(ConferenceStateChanged.class);
assertEquals(ConferenceStateChanged.State.COMPLETED, conferenceStateChanged.state());
}};
}
}
| 17,412 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ConferenceTestUtil.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/test/org/restcomm/connect/telephony/util/ConferenceTestUtil.java | package org.restcomm.connect.telephony.util;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.log4j.Logger;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.ConferenceDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.entities.ConferenceDetailRecord;
import org.restcomm.connect.dao.mybatis.MybatisDaoManager;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import akka.actor.ActorSystem;
/**
* @author [email protected] (Maria Farooq)
*/
public class ConferenceTestUtil {
private final static Logger logger = Logger.getLogger(ConferenceTestUtil.class.getName());
protected static ActorSystem system;
protected static Configuration configurationNode1;
protected static Configuration configurationNode2;
protected XMLConfiguration daoManagerConf = null;
protected static DaoManager daoManager;
protected static final String CONFIG_PATH_NODE_1 = "/restcomm.xml";
protected static final String CONFIG_PATH_NODE_2 = "/restcomm-node2.xml";
protected static final String CONFIG_PATH_DAO_MANAGER = "/dao-manager.xml";
protected static final String CONFERENCE_FRIENDLY_NAME_1 ="ACae6e420f425248d6a26948c17a9e2acf:1111";
protected static final String CONFERENCE_FRIENDLY_NAME_2 ="ACae6e420f425248d6a26948c17a9e2acf:1122";
protected static final String CALL_SID ="CAae6e420f425248d6a26948c17a9e2acf";
protected static final String ACCOUNT_SID_1 ="ACae6e420f425248d6a26948c17a9e2acf";
public static Sid TEST_CNF_SID = new Sid("CF6d61e3877f3c47828a26efc498a9e8f9");
@BeforeClass
public static void beforeClass() throws Exception {
RestcommConfiguration.createOnce(new XMLConfiguration());
system = ActorSystem.create();
}
@AfterClass
public static void afterClass() throws Exception {
system.shutdown();
}
protected Configuration createCfg(final String cfgFileName) throws ConfigurationException, MalformedURLException {
URL url = this.getClass().getResource(cfgFileName);
return new XMLConfiguration(url);
}
protected Configuration createDaoManagerCfg(final String cfgFileName) throws ConfigurationException, MalformedURLException {
URL url = this.getClass().getResource(cfgFileName);
return new XMLConfiguration(url);
}
private void cleanAllConferences() {
ConferenceDetailRecordsDao dao = daoManager.getConferenceDetailRecordsDao();
List<ConferenceDetailRecord> records = (List) dao.getConferenceDetailRecords(new Sid(ACCOUNT_SID_1));
for(int i=0; i<records.size(); i++){
ConferenceDetailRecord cdr = records.get(i);
cdr = cdr.setStatus(ConferenceStateChanged.State.COMPLETED+"");
dao.updateConferenceDetailRecordStatus(cdr);
}
}
protected void startDaoManager() throws ConfigurationException, MalformedURLException{
daoManagerConf = (XMLConfiguration)createDaoManagerCfg(CONFIG_PATH_DAO_MANAGER);
daoManager = new MybatisDaoManager();
daoManager.configure(configurationNode1, daoManagerConf, null);
daoManager.start();
}
}
| 3,462 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MockFailingMmsControllerFactory.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/test/org/restcomm/connect/mscontrol/mms/MockFailingMmsControllerFactory.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.mscontrol.mms;
import org.apache.log4j.Logger;
import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActorFactory;
/**
* Provides controllers for Mobicents Media Server.
*
* @author Maria Farooq ([email protected])
*
*/
public class MockFailingMmsControllerFactory implements MediaServerControllerFactory {
private static Logger logger = Logger.getLogger(MockFailingMmsControllerFactory.class);
private final ActorSystem system;
private final CallControllerFactory callControllerFactory;
private final ConferenceControllerFactory conferenceControllerFactory;
private final BridgeControllerFactory bridgeControllerFactory;
private final ActorRef mrb;
public MockFailingMmsControllerFactory(ActorSystem system, ActorRef mrb) {
super();
this.system = system;
this.callControllerFactory = new CallControllerFactory();
this.conferenceControllerFactory = new ConferenceControllerFactory();
this.bridgeControllerFactory = new BridgeControllerFactory();
this.mrb = mrb;
}
@Override
public Props provideCallControllerProps() {
return new Props(this.callControllerFactory);
}
@Override
public Props provideConferenceControllerProps() {
return new Props(this.conferenceControllerFactory);
}
@Override
public Props provideBridgeControllerProps() {
return new Props(this.bridgeControllerFactory);
}
private final class CallControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = -4649683839304615853L;
@Override
public Actor create() throws Exception {
return null;
}
}
private final class ConferenceControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = -919317656354678281L;
@Override
public Actor create() throws Exception {
return new MockFailingMmsConferenceController(mrb);
}
}
private final class BridgeControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = 8999152285760508857L;
@Override
public Actor create() throws Exception {
return null;
}
}
}
| 3,393 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MockMmsControllerFactory.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/test/org/restcomm/connect/mscontrol/mms/MockMmsControllerFactory.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.mscontrol.mms;
import org.apache.log4j.Logger;
import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory;
import akka.actor.Actor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActorFactory;
/**
* Provides controllers for Mobicents Media Server.
*
* @author Maria Farooq ([email protected])
*
*/
public class MockMmsControllerFactory implements MediaServerControllerFactory {
private static Logger logger = Logger.getLogger(MockMmsControllerFactory.class);
private final ActorSystem system;
private final CallControllerFactory callControllerFactory;
private final ConferenceControllerFactory conferenceControllerFactory;
private final BridgeControllerFactory bridgeControllerFactory;
private final ActorRef mrb;
public MockMmsControllerFactory(ActorSystem system, ActorRef mrb) {
super();
this.system = system;
this.callControllerFactory = new CallControllerFactory();
this.conferenceControllerFactory = new ConferenceControllerFactory();
this.bridgeControllerFactory = new BridgeControllerFactory();
this.mrb = mrb;
}
@Override
public Props provideCallControllerProps() {
return new Props(this.callControllerFactory);
}
@Override
public Props provideConferenceControllerProps() {
return new Props(this.conferenceControllerFactory);
}
@Override
public Props provideBridgeControllerProps() {
return new Props(this.bridgeControllerFactory);
}
private final class CallControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = -4649683839304615853L;
@Override
public Actor create() throws Exception {
return null;
}
}
private final class ConferenceControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = -919317656354678281L;
@Override
public Actor create() throws Exception {
return new MockMmsConferenceController(mrb);
}
}
private final class BridgeControllerFactory implements UntypedActorFactory {
private static final long serialVersionUID = 8999152285760508857L;
@Override
public Actor create() throws Exception {
return null;
}
}
}
| 3,365 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MockMmsConferenceController.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/test/org/restcomm/connect/mscontrol/mms/MockMmsConferenceController.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.mscontrol.mms;
import java.util.ArrayList;
import java.util.List;
import org.mobicents.servlet.restcomm.mscontrol.messages.MediaServerConferenceControllerStateChanged;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.commons.dao.Sid;
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.mscontrol.api.MediaServerController;
import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession;
import org.restcomm.connect.mscontrol.api.messages.JoinCall;
import org.restcomm.connect.mscontrol.api.messages.JoinComplete;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged.MediaServerControllerState;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import org.restcomm.connect.telephony.util.ConferenceTestUtil;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
/**
* @author Maria Farooq ([email protected])
*/
@Immutable
public final class MockMmsConferenceController extends MediaServerController {
// Logging
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Observers
private final List<ActorRef> observers;
private Sid conferenceSid = ConferenceTestUtil.TEST_CNF_SID;
public MockMmsConferenceController(final ActorRef mrb) {
super();
// Observers
this.observers = new ArrayList<ActorRef>(2);
}
private void broadcast(Object message) {
if (!this.observers.isEmpty()) {
final ActorRef self = self();
synchronized (this.observers) {
for (ActorRef observer : observers) {
observer.tell(message, self);
}
}
}
}
/*
* EVENTS
*/
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef sender = sender();
final ActorRef self = self();
if(logger.isInfoEnabled()) {
logger.info(" ********** Conference Controller Processing Message: " + klass.getName());
}
if (Observe.class.equals(klass)) {
onObserve((Observe) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
onStopObserving((StopObserving) message, self, sender);
} else if (CreateMediaSession.class.equals(klass)) {
broadcast(new MediaServerConferenceControllerStateChanged(MediaServerControllerState.ACTIVE, conferenceSid, ""+ConferenceStateChanged.State.RUNNING_MODERATOR_ABSENT, true));
} else if (Stop.class.equals(klass)) {
broadcast(new MediaServerConferenceControllerStateChanged(MediaServerControllerState.INACTIVE, conferenceSid));
} else if(JoinCall.class.equals(klass)){
onJoinCall((JoinCall)message, self, sender);
} else{
logger.error("Unhanldles Request Received.");
}
}
private void onJoinCall(JoinCall message, ActorRef self, ActorRef sender) {
sender.tell(new JoinComplete(), message.getCall());
}
private void onObserve(Observe message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
synchronized (this.observers) {
this.observers.add(observer);
observer.tell(new Observing(self), self);
}
}
}
private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
this.observers.remove(observer);
}
}
}
| 4,861 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MockFailingMmsConferenceController.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/test/org/restcomm/connect/mscontrol/mms/MockFailingMmsConferenceController.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.mscontrol.mms;
import java.util.ArrayList;
import java.util.List;
import org.mobicents.servlet.restcomm.mscontrol.messages.MediaServerConferenceControllerStateChanged;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.commons.dao.Sid;
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.mscontrol.api.MediaServerController;
import org.restcomm.connect.mscontrol.api.messages.CloseMediaSession;
import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession;
import org.restcomm.connect.mscontrol.api.messages.JoinCall;
import org.restcomm.connect.mscontrol.api.messages.JoinComplete;
import org.restcomm.connect.mscontrol.api.messages.JoinConference;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged.MediaServerControllerState;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
/**
* @author Maria Farooq ([email protected])
*/
@Immutable
public final class MockFailingMmsConferenceController extends MediaServerController {
// Logging
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Observers
private final List<ActorRef> observers;
private Sid conferenceSid;
public MockFailingMmsConferenceController(final ActorRef mrb) {
super();
// Observers
this.observers = new ArrayList<ActorRef>(2);
}
private void broadcast(Object message) {
if (!this.observers.isEmpty()) {
final ActorRef self = self();
synchronized (this.observers) {
for (ActorRef observer : observers) {
observer.tell(message, self);
}
}
}
}
/*
* EVENTS
*/
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef sender = sender();
final ActorRef self = self();
if(logger.isInfoEnabled()) {
logger.info(" ********** MockFailingMmsConferenceController Conference Controller Processing Message: " + klass.getName());
}
if (Observe.class.equals(klass)) {
onObserve((Observe) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
onStopObserving((StopObserving) message, self, sender);
} else if (CreateMediaSession.class.equals(klass)) {
broadcast(new MediaServerConferenceControllerStateChanged(MediaServerControllerState.ACTIVE, conferenceSid, ""+ConferenceStateChanged.State.RUNNING_MODERATOR_ABSENT, true));
} else if (Stop.class.equals(klass)) {
//do nothing so conference stay in stopping state
} else if(JoinCall.class.equals(klass)){
onJoinCall((JoinCall)message, self, sender);
} else{
logger.error("Unhanldles Request Received.");
}
}
private void onJoinCall(JoinCall message, ActorRef self, ActorRef sender) {
sender.tell(new JoinComplete(), message.getCall());
}
private void onObserve(Observe message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
synchronized (this.observers) {
this.observers.add(observer);
observer.tell(new Observing(self), self);
}
}
}
private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
this.observers.remove(observer);
}
}
}
| 4,888 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CallManager.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/CallManager.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.telephony;
import akka.actor.ActorContext;
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 akka.util.Timeout;
import com.google.i18n.phonenumbers.NumberParseException;
import gov.nist.javax.sip.header.UserAgent;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.patterns.StopObserving;
import org.restcomm.connect.commons.push.PushNotificationServerHelper;
import org.restcomm.connect.commons.telephony.CreateCallType;
import org.restcomm.connect.commons.telephony.ProxyRule;
import org.restcomm.connect.commons.util.DNSUtils;
import org.restcomm.connect.commons.util.SdpUtils;
import org.restcomm.connect.core.service.RestcommConnectServiceProvider;
import org.restcomm.connect.core.service.api.NumberSelectorService;
import org.restcomm.connect.core.service.number.api.NumberSelectionResult;
import org.restcomm.connect.core.service.util.UriUtils;
import org.restcomm.connect.dao.AccountsDao;
import org.restcomm.connect.dao.ApplicationsDao;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.ClientsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.RegistrationsDao;
import org.restcomm.connect.dao.common.OrganizationUtil;
import org.restcomm.connect.dao.entities.Account;
import org.restcomm.connect.dao.entities.Application;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.dao.entities.Client;
import org.restcomm.connect.dao.entities.IncomingPhoneNumber;
import org.restcomm.connect.dao.entities.Notification;
import org.restcomm.connect.dao.entities.Organization;
import org.restcomm.connect.dao.entities.Registration;
import org.restcomm.connect.extension.api.ExtensionResponse;
import org.restcomm.connect.extension.api.ExtensionType;
import org.restcomm.connect.extension.api.IExtensionCreateCallRequest;
import org.restcomm.connect.extension.api.IExtensionFeatureAccessRequest;
import org.restcomm.connect.extension.api.RestcommExtensionException;
import org.restcomm.connect.extension.api.RestcommExtensionGeneric;
import org.restcomm.connect.extension.controller.ExtensionController;
import org.restcomm.connect.http.client.rcmlserver.resolver.RcmlserverResolver;
import org.restcomm.connect.interpreter.SIPOrganizationUtil;
import org.restcomm.connect.interpreter.StartInterpreter;
import org.restcomm.connect.interpreter.StopInterpreter;
import org.restcomm.connect.interpreter.VoiceInterpreter;
import org.restcomm.connect.interpreter.VoiceInterpreterParams;
import org.restcomm.connect.monitoringservice.MonitoringService;
import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory;
import org.restcomm.connect.telephony.api.CallInfo;
import org.restcomm.connect.telephony.api.CallManagerResponse;
import org.restcomm.connect.telephony.api.CallResponse;
import org.restcomm.connect.telephony.api.CallStateChanged;
import org.restcomm.connect.telephony.api.CreateCall;
import org.restcomm.connect.telephony.api.DestroyCall;
import org.restcomm.connect.telephony.api.ExecuteCallScript;
import org.restcomm.connect.telephony.api.FeatureAccessRequest;
import org.restcomm.connect.telephony.api.GetActiveProxy;
import org.restcomm.connect.telephony.api.GetCall;
import org.restcomm.connect.telephony.api.GetCallInfo;
import org.restcomm.connect.telephony.api.GetCallObservers;
import org.restcomm.connect.telephony.api.GetProxies;
import org.restcomm.connect.telephony.api.GetRelatedCall;
import org.restcomm.connect.telephony.api.Hangup;
import org.restcomm.connect.telephony.api.InitializeOutbound;
import org.restcomm.connect.telephony.api.SwitchProxy;
import org.restcomm.connect.telephony.api.UpdateCallScript;
import org.restcomm.connect.telephony.api.util.B2BUAHelper;
import org.restcomm.connect.telephony.api.util.CallControlHelper;
import scala.concurrent.Await;
import scala.concurrent.Future;
import scala.concurrent.duration.Duration;
import javax.sdp.SdpParseException;
import javax.servlet.ServletContext;
import javax.servlet.sip.Address;
import javax.servlet.sip.AuthInfo;
import javax.servlet.sip.ServletParseException;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipApplicationSessionEvent;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipSession;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.TelURL;
import javax.sip.header.RouteHeader;
import javax.sip.message.Response;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
import static akka.pattern.Patterns.ask;
import static javax.servlet.sip.SipServlet.OUTBOUND_INTERFACES;
import static javax.servlet.sip.SipServletResponse.SC_ACCEPTED;
import static javax.servlet.sip.SipServletResponse.SC_BAD_REQUEST;
import static javax.servlet.sip.SipServletResponse.SC_FORBIDDEN;
import static javax.servlet.sip.SipServletResponse.SC_NOT_FOUND;
import static javax.servlet.sip.SipServletResponse.SC_OK;
import static javax.servlet.sip.SipServletResponse.SC_SERVER_INTERNAL_ERROR;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected]
* @author [email protected]
* @author [email protected]
* @author [email protected]
*/
public final class CallManager extends RestcommUntypedActor {
public static final String TIMEOUT_ATT ="org.restcomm.connect.telephony.timeoutProcessed";
static final int ERROR_NOTIFICATION = 0;
static final int WARNING_NOTIFICATION = 1;
static final Pattern PATTERN = Pattern.compile("[\\*#0-9]{1,12}");
static final String EMAIL_SENDER = "[email protected]";
static final String EMAIL_SUBJECT = "RestComm Error Notification - Attention Required";
static final int DEFAUL_IMS_PROXY_PORT = -1;
static final int ACCOUNT_NOT_ACTIVE_FAILURE_RESPONSE_CODE = SC_FORBIDDEN;
private final ActorSystem system;
private final Configuration configuration;
private final ServletContext context;
private final MediaServerControllerFactory msControllerFactory;
private final ActorRef conferences;
private final ActorRef bridges;
private final ActorRef sms;
private final SipFactory sipFactory;
private final DaoManager storage;
private final ActorRef monitoring;
private final NumberSelectorService numberSelector;
// configurable switch whether to use the To field in a SIP header to determine the callee address
// alternatively the Request URI can be used
private boolean useTo;
private boolean authenticateUsers;
private AtomicInteger numberOfFailedCalls;
private AtomicBoolean useFallbackProxy;
private boolean allowFallback;
private boolean allowFallbackToPrimary;
private int maxNumberOfFailedCalls;
private String primaryProxyUri;
private String primaryProxyUsername, primaryProxyPassword;
private String fallBackProxyUri;
private String fallBackProxyUsername, fallBackProxyPassword;
private String activeProxy;
private String activeProxyUsername, activeProxyPassword;
private String mediaExternalIp;
private String myHostIp;
private String proxyIp;
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
private SwitchProxy switchProxyRequest;
//Control whether Restcomm will patch Request-URI and SDP for B2BUA calls
private boolean patchForNatB2BUASessions;
private boolean useSbc;
//List of extensions for CallManager
List<RestcommExtensionGeneric> extensions;
// IMS authentication
private boolean actAsImsUa;
private String imsProxyAddress;
private int imsProxyPort;
private String imsDomain;
private String imsAccount;
//Maximum P2P call length
private int maxP2PCallLength;
private boolean actAsProxyOut;
private List<ProxyRule> proxyOutRules;
private boolean isActAsProxyOutUseFromHeader;
private UriUtils uriUtils;
// Push notification server
private final PushNotificationServerHelper pushNotificationServerHelper;
// used for sending warning and error logs to notification engine and to the console
private void sendNotification(Sid accountId, String errMessage, int errCode, String errType, boolean createNotification) {
NotificationsDao notifications = storage.getNotificationsDao();
Notification notification;
if (errType == "warning") {
if (logger.isDebugEnabled()) {
// https://github.com/RestComm/Restcomm-Connect/issues/1419 moved to debug to avoid polluting logs
logger.debug(errMessage); // send message to console
}
if (createNotification) {
notification = notification(accountId, ERROR_NOTIFICATION, errCode, errMessage);
notifications.addNotification(notification);
}
} else if (errType == "error") {
// https://github.com/RestComm/Restcomm-Connect/issues/1419 moved to debug to avoid polluting logs
if (logger.isDebugEnabled()) {
logger.debug(errMessage); // send message to console
}
if (createNotification) {
notification = notification(accountId, ERROR_NOTIFICATION, errCode, errMessage);
notifications.addNotification(notification);
}
} else if (errType == "info") {
// https://github.com/RestComm/Restcomm-Connect/issues/1419 moved to debug to avoid polluting logs
if (logger.isDebugEnabled()) {
logger.debug(errMessage); // send message to console
}
}
}
public CallManager(final Configuration configuration, final ServletContext context,
final MediaServerControllerFactory msControllerFactory, final ActorRef conferences, final ActorRef bridges,
final ActorRef sms, final SipFactory factory, final DaoManager storage) {
super();
this.system = context().system();
this.configuration = configuration;
this.context = context;
this.msControllerFactory = msControllerFactory;
this.conferences = conferences;
this.bridges = bridges;
this.sms = sms;
this.sipFactory = factory;
this.storage = storage;
numberSelector = (NumberSelectorService)context.getAttribute(NumberSelectorService.class.getName());
final Configuration runtime = configuration.subset("runtime-settings");
final Configuration outboundProxyConfig = runtime.subset("outbound-proxy");
SipURI outboundIntf = outboundInterface("udp");
if (outboundIntf != null) {
myHostIp = ((SipURI) outboundIntf).getHost().toString();
} else {
String errMsg = "SipURI outboundIntf is null";
sendNotification(null, errMsg, 14001, "error", false);
if (context == null)
errMsg = "SipServlet context is null";
sendNotification(null, errMsg, 14002, "error", false);
}
Configuration mediaConf = configuration.subset("media-server-manager");
mediaExternalIp = mediaConf.getString("mgcp-server.external-address");
proxyIp = runtime.subset("telestax-proxy").getString("uri").replaceAll("http://", "").replaceAll(":2080", "");
if (mediaExternalIp == null || mediaExternalIp.isEmpty())
mediaExternalIp = myHostIp;
if (proxyIp == null || proxyIp.isEmpty())
proxyIp = myHostIp;
this.useTo = runtime.getBoolean("use-to");
this.authenticateUsers = runtime.getBoolean("authenticate");
this.primaryProxyUri = outboundProxyConfig.getString("outbound-proxy-uri");
this.primaryProxyUsername = outboundProxyConfig.getString("outbound-proxy-user");
this.primaryProxyPassword = outboundProxyConfig.getString("outbound-proxy-password");
this.fallBackProxyUri = outboundProxyConfig.getString("fallback-outbound-proxy-uri");
this.fallBackProxyUsername = outboundProxyConfig.getString("fallback-outbound-proxy-user");
this.fallBackProxyPassword = outboundProxyConfig.getString("fallback-outbound-proxy-password");
this.activeProxy = primaryProxyUri;
this.activeProxyUsername = primaryProxyUsername;
this.activeProxyPassword = primaryProxyPassword;
numberOfFailedCalls = new AtomicInteger();
numberOfFailedCalls.set(0);
useFallbackProxy = new AtomicBoolean();
useFallbackProxy.set(false);
allowFallback = outboundProxyConfig.getBoolean("allow-fallback", false);
maxNumberOfFailedCalls = outboundProxyConfig.getInt("max-failed-calls", 20);
allowFallbackToPrimary = outboundProxyConfig.getBoolean("allow-fallback-to-primary", false);
patchForNatB2BUASessions = runtime.getBoolean("patch-for-nat-b2bua-sessions", true);
useSbc = runtime.getBoolean("use-sbc", false);
if(useSbc) {
if (logger.isDebugEnabled()) {
logger.debug("CallManager: use-sbc is true, overriding patch-for-nat-b2bua-sessions to false");
}
patchForNatB2BUASessions = false;
}
maxP2PCallLength = runtime.getInt("max-p2p-call-length", 60);
//Monitoring Service
this.monitoring = (ActorRef) context.getAttribute(MonitoringService.class.getName());
extensions = ExtensionController.getInstance().getExtensions(ExtensionType.CallManager);
if (logger.isInfoEnabled()) {
logger.info("CallManager extensions: " + (extensions != null ? extensions.size() : "0"));
}
if (!runtime.subset("ims-authentication").isEmpty()) {
final Configuration imsAuthentication = runtime.subset("ims-authentication");
this.actAsImsUa = imsAuthentication.getBoolean("act-as-ims-ua");
if (actAsImsUa) {
this.imsProxyAddress = imsAuthentication.getString("proxy-address");
this.imsProxyPort = imsAuthentication.getInt("proxy-port");
if (imsProxyPort == 0) {
imsProxyPort = DEFAUL_IMS_PROXY_PORT;
}
this.imsDomain = imsAuthentication.getString("domain");
this.imsAccount = imsAuthentication.getString("account");
if (actAsImsUa && (imsProxyAddress == null || imsProxyAddress.isEmpty()
|| imsDomain == null || imsDomain.isEmpty())) {
logger.warning("ims proxy-address or domain is not configured");
}
this.actAsImsUa = actAsImsUa && imsProxyAddress != null && !imsProxyAddress.isEmpty()
&& imsDomain != null && !imsDomain.isEmpty();
}
}
if (!runtime.subset("acting-as-proxy").isEmpty() && !runtime.subset("acting-as-proxy").subset("proxy-rules").isEmpty()) {
final Configuration proxyConfiguration = runtime.subset("acting-as-proxy");
final Configuration proxyOutRulesConf = proxyConfiguration.subset("proxy-rules");
this.actAsProxyOut = proxyConfiguration.getBoolean("enabled", false);
if (actAsProxyOut) {
isActAsProxyOutUseFromHeader = proxyConfiguration.getBoolean("use-from-header", true);
proxyOutRules = new ArrayList<ProxyRule>();
List<HierarchicalConfiguration> rulesList = ((HierarchicalConfiguration) proxyOutRulesConf).configurationsAt("rule");
for (HierarchicalConfiguration rule : rulesList) {
String fromHost = rule.getString("from-uri");
String toHost = rule.getString("to-uri");
final String username = rule.getString("proxy-to-username");
final String password = rule.getString("proxy-to-password");
ProxyRule proxyRule = new ProxyRule(fromHost, toHost, username, password);
proxyOutRules.add(proxyRule);
}
if (logger.isInfoEnabled()) {
String msg = String.format("`ActAsProxy` feature is enabled with %d rules.", proxyOutRules.size());
logger.info(msg);
}
actAsProxyOut = actAsProxyOut && (proxyOutRules != null) && !proxyOutRules.isEmpty();
}
}
this.uriUtils = RestcommConnectServiceProvider.getInstance().uriUtils();
// Push notification server
this.pushNotificationServerHelper = new PushNotificationServerHelper(system, configuration);
firstTimeCleanup();
}
private void firstTimeCleanup() {
if (logger.isInfoEnabled())
logger.info("Initial CallManager cleanup. Will check running state calls in DB and update state of the calls.");
String instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId();
Sid sid = new Sid(instanceId);
final CallDetailRecordsDao callDetailRecordsDao = storage.getCallDetailRecordsDao();
callDetailRecordsDao.updateInCompleteCallDetailRecordsToCompletedByInstanceId(sid);
List<CallDetailRecord> results = callDetailRecordsDao.getInCompleteCallDetailRecordsByInstanceId(sid);
if (logger.isInfoEnabled()) {
logger.info("There are: " + results.size() + " calls in progress after cleanup.");
}
}
private ActorRef call(final Sid accountSid, final CreateCall request) {
Props props = null;
if (request == null) {
props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new Call(accountSid, sipFactory, msControllerFactory, configuration,
null, null, null, null);
}
});
} else {
props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new Call(accountSid, sipFactory, msControllerFactory, configuration,
request.statusCallback(), request.statusCallbackMethod(), request.statusCallbackEvent(), request.getOutboundProxyHeaders());
}
});
}
return getContext().actorOf(props);
}
private boolean check(final Object message) throws IOException {
final SipServletRequest request = (SipServletRequest) message;
String content = null;
if (request.getRawContent() != null) {
content = new String(request.getRawContent());
}
if (content == null && request.getContentLength() == 0
|| !("application/sdp".equals(request.getContentType()) || content.contains("application/sdp"))) {
final SipServletResponse response = request.createResponse(SC_BAD_REQUEST);
response.send();
return false;
}
return true;
}
private void destroy(final Object message) throws Exception {
final UntypedActorContext context = getContext();
final DestroyCall request = (DestroyCall) message;
ActorRef call = request.call();
if (call != null) {
if (logger.isInfoEnabled()) {
logger.info("About to destroy call: " + request.call().path() + ", call isTerminated(): " + sender().isTerminated() + ", sender: " + sender());
}
getContext().stop(call);
}
}
private void rejectInvite(final SipServletRequest request) throws IOException {
final SipServletResponse response = request.createResponse(ACCOUNT_NOT_ACTIVE_FAILURE_RESPONSE_CODE,
"Account is not ACTIVE");
response.send();
}
private void invite(final Object message) throws IOException, NumberParseException, ServletParseException {
final ActorRef self = self();
final SipServletRequest request = (SipServletRequest) message;
// Make sure we handle re-invites properly.
if (!request.isInitial()) {
SipApplicationSession appSession = request.getApplicationSession();
ActorRef call = null;
if (appSession.getAttribute(Call.class.getName()) != null) {
call = (ActorRef) appSession.getAttribute(Call.class.getName());
}
if (call != null) {
if (logger.isInfoEnabled()) {
logger.info("For In-Dialog INVITE dispatched to Call actor: " + call.path());
}
call.tell(request, self);
return;
}
if (logger.isInfoEnabled()) {
logger.info("No call actor found will respond 200OK for In-dialog INVITE: " + request.getRequestURI().toString());
}
final SipServletResponse okay = request.createResponse(SC_OK);
okay.send();
return;
}
if (actAsImsUa) {
boolean isFromIms = isFromIms(request);
if (!isFromIms) {
//This is a WebRTC client that dials out to IMS
String user = request.getHeader("X-RestComm-Ims-User");
String pass = request.getHeader("X-RestComm-Ims-Password");
request.removeHeader("X-RestComm-Ims-User");
request.removeHeader("X-RestComm-Ims-Password");
imsProxyThroughMediaServer(request, null, request.getTo().getURI(), user, pass, isFromIms);
return;
} else {
//This is a IMS that dials out to WebRTC client
imsProxyThroughMediaServer(request, null, request.getTo().getURI(), "", "", isFromIms);
return;
}
}
//Run proInboundAction Extensions here
// If it's a new invite lets try to handle it.
final AccountsDao accounts = storage.getAccountsDao();
final ApplicationsDao applications = storage.getApplicationsDao();
final ClientsDao clients = storage.getClientsDao();
// Try to find an application defined for the client.
final SipURI fromUri = (SipURI) request.getFrom().getURI();
final String fromUser = fromUri.getUser();
final SipURI toUri = (SipURI) request.getTo().getURI();
String toUser = CallControlHelper.getUserSipId(request, useTo);
final String ruri = ((SipURI) request.getRequestURI()).getHost();
final String toHost = toUri.getHost();
final String toHostIpAddress = DNSUtils.getByName(toHost).getHostAddress();
final String toPort = String.valueOf(((SipURI) request.getTo().getURI()).getPort()).equalsIgnoreCase("-1") ? "5060"
: String.valueOf(((SipURI) request.getTo().getURI()).getHost());
final String transport = ((SipURI) request.getTo().getURI()).getTransportParam() == null ? "udp" : ((SipURI) request
.getTo().getURI()).getTransportParam();
SipURI outboundIntf = outboundInterface(transport);
Sid sourceOrganizationSid = OrganizationUtil.getOrganizationSidBySipURIHost(storage, fromUri);
Sid toOrganizationSid = SIPOrganizationUtil.searchOrganizationBySIPRequest(storage.getOrganizationsDao(), request);
if(logger.isDebugEnabled()) {
logger.debug("sourceOrganizationSid: " + sourceOrganizationSid +" fromUri: "+fromUri);
logger.debug("toOrganizationSid: " + toOrganizationSid +" toUri: "+(SipURI) request.getTo().getURI());
}
if(sourceOrganizationSid == null){
if(logger.isInfoEnabled())
logger.info("Null Organization, call is probably coming from a provider: fromUri: "+fromUri);
}
final Client client = clients.getClient(fromUser,sourceOrganizationSid);
final Client toClient = clients.getClient(toUser, toOrganizationSid);
if (client != null) {
Account fromAccount = accounts.getAccount(client.getAccountSid());
if (!fromAccount.getStatus().equals(Account.Status.ACTIVE)) {
//reject call since the Client belongs to an an account which is not ACTIVE
rejectInvite(request);
String msg = String.format("Restcomm rejects this call because client %s account %s is not ACTIVE, current state %s", client.getFriendlyName(), fromAccount.getSid(), fromAccount.getStatus());
if (logger.isDebugEnabled()) {
logger.debug(msg);
}
sendNotification(null, msg, 11005, "error", true);
return;
}
// Make sure we force clients to authenticate.
if (!authenticateUsers // https://github.com/Mobicents/RestComm/issues/29 Allow disabling of SIP authentication
|| CallControlHelper.checkAuthentication(request, storage, sourceOrganizationSid)) {
// if the client has authenticated, try to redirect to the Client VoiceURL app
// otherwise continue trying to process the Client invite
if (redirectToClientVoiceApp(self, request, accounts, applications, client)) {
return;
} // else continue trying other ways to handle the request
} else {
// Since the client failed to authenticate, we will take no further action at this time.
return;
}
}
if (toClient != null) {
Account toAccount = accounts.getAccount(toClient.getAccountSid());
if (!toAccount.getStatus().equals(Account.Status.ACTIVE)) {
//reject call since the toClient belongs to an an account which is not ACTIVE
rejectInvite(request);
String msg = String.format("Restcomm rejects this call because client %s account %s is not ACTIVE, current state %s", toClient.getFriendlyName(), toAccount.getSid(), toAccount.getStatus());
if (logger.isDebugEnabled()) {
logger.debug(msg);
}
sendNotification(null, msg, 11005, "error", true);
return;
}
}
IncomingPhoneNumber number = null;
if (toClient == null) {
number = getIncomingPhoneNumber(request, toUser, (client != null ? client.getSid() : null),
sourceOrganizationSid, toOrganizationSid);
if (number != null) {
Account numAccount = accounts.getAccount(number.getAccountSid());
if (!numAccount.getStatus().equals(Account.Status.ACTIVE)) {
//reject call since the number belongs to an an account which is not ACTIVE
rejectInvite(request);
String msg = String.format("Restcomm rejects this call because number's %s account %s is not ACTIVE, current state %s", number.getPhoneNumber(), numAccount.getSid(), numAccount.getStatus());
if (logger.isDebugEnabled()) {
logger.debug(msg);
}
sendNotification(null, msg, 11005, "error", true);
return;
}
if (toOrganizationSid == null) {
toOrganizationSid = number.getOrganizationSid();
}
}
}
if (sourceOrganizationSid == null && toOrganizationSid == null) {
//sourceOrganization is null which means we got a call from external provider or unregistered client
// AND toOrganization is null which means there will be no client or number for this INVITE
// THUS we should fail fast
final SipServletResponse response = request.createResponse(SC_NOT_FOUND);
response.send();
// We didn't find anyway to handle the call.
String msg = String.format("Restcomm cannot process this call to %s from %s. Source and To organizations are null", toUser, fromUser);
if (logger.isInfoEnabled()) {
logger.info(msg);
}
sendNotification(null, msg, 11005, "error", true);
}
if (logger.isInfoEnabled()) {
logger.info("ToUser: " + toUser);
logger.info("ToHost: " + toHost);
logger.info("ruri: " + ruri);
logger.info("myHostIp: " + myHostIp);
logger.info("mediaExternalIp: " + mediaExternalIp);
logger.info("proxyIp: " + proxyIp);
}
if (client != null) { // make sure the caller is a registered client and not some external SIP agent that we have little control over
if (toClient != null) { // looks like its a p2p attempt between two valid registered clients, lets redirect to the b2bua
if (logger.isInfoEnabled()) {
logger.info("Client is not null: " + client.getLogin() + " will try to proxy to client: " + toClient);
}
ExtensionController ec = ExtensionController.getInstance();
final IExtensionCreateCallRequest er = new CreateCall(fromUser, toUser, "", "", false, 0, CreateCallType.CLIENT, client.getAccountSid(), null, null, null, null);
ExtensionResponse extRes = ec.executePreOutboundAction(er, extensions);
if (extRes.isAllowed()) {
long delay = pushNotificationServerHelper.sendPushNotificationIfNeeded(toClient.getPushClientIdentity());
system.scheduler().scheduleOnce(Duration.create(delay, TimeUnit.MILLISECONDS), new Runnable() {
@Override
public void run() {
try {
if (B2BUAHelper.redirectToB2BUA(system, request, client, toClient, storage, sipFactory, patchForNatB2BUASessions)) {
if (logger.isInfoEnabled()) {
logger.info("Call to CLIENT. myHostIp: " + myHostIp + " mediaExternalIp: " + mediaExternalIp + " toHost: "
+ toHost + " fromClient: " + client.getUri() + " toClient: " + toClient.getUri());
}
// if all goes well with proxying the invitation on to the next client
// then we can end further processing of this INVITE
} else {
String errMsg = "Cannot Connect to Client: " + toClient.getFriendlyName()
+ " : Make sure the Client exist or is registered with Restcomm";
sendNotification(client.getAccountSid(), errMsg, 11001, "warning", true);
final SipServletResponse resp = request.createResponse(SC_NOT_FOUND, "Cannot complete P2P call");
resp.send();
}
ExtensionController.getInstance().executePostOutboundAction(er, extensions);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, system.dispatcher());
} else {
//Extensions didn't allowed this call
if (logger.isDebugEnabled()) {
final String errMsg = "Client not Allowed to make this outbound call";
logger.debug(errMsg);
}
String errMsg = "Cannot Connect to Client: " + toClient.getFriendlyName()
+ " : Make sure the Client exist or is registered with Restcomm";
sendNotification(client.getAccountSid(), errMsg, 11001, "warning", true);
final SipServletResponse resp = request.createResponse(SC_FORBIDDEN, "Call not allowed");
resp.send();
}
ec.executePostOutboundAction(er, extensions);
return;
} else {
// toClient is null or we couldn't make the b2bua call to another client. check if this call is for a registered
// DID (application)
if (redirectToHostedVoiceApp(request, accounts, applications, toUser, client.getAccountSid(), number)) {
// This is a call to a registered DID (application)
return;
}
// This call is not a registered DID (application). Try to proxy out this call.
// log to console and to notification engine
String errMsg = "A Restcomm Client is trying to call a Number/DID that is not registered with Restcomm";
sendNotification(client.getAccountSid(), errMsg, 11002, "info", true);
if(useSbc) {
toUser = toUser+"@"+ruri;
if (logger.isDebugEnabled()) {
logger.debug("CallManager: use-sbc is true, overriding webrtc toUser to " + toUser);
}
}
ExtensionController ec = ExtensionController.getInstance();
IExtensionCreateCallRequest er = new CreateCall(fromUser, toUser, "", "", false, 0, CreateCallType.PSTN, client.getAccountSid(), null, null, null, null);
ExtensionResponse extRes = ec.executePreOutboundAction(er, this.extensions);
if (extRes.isAllowed()) {
if (actAsProxyOut) {
processRequestAndProxyOut(request, client, toUser);
} else if (isWebRTC(request)) {
//This is a WebRTC client that dials out
//TODO: should we inject headers for this case?
proxyThroughMediaServerAsNumber(request, client, toUser);
} else {
// https://telestax.atlassian.net/browse/RESTCOMM-335
String proxyURI = activeProxy;
String proxyUsername = activeProxyUsername;
String proxyPassword = activeProxyPassword;
SipURI from = null;
SipURI to = null;
boolean callToSipUri = false;
if (er.getOutboundProxy() != null && !er.getOutboundProxy().isEmpty()) {
proxyURI = er.getOutboundProxy();
}
if (er.getOutboundProxyUsername() != null && !er.getOutboundProxyUsername().isEmpty()) {
proxyUsername = er.getOutboundProxyUsername();
}
if (er.getOutboundProxyPassword() != null && !er.getOutboundProxyPassword().isEmpty()) {
proxyPassword = er.getOutboundProxyPassword();
}
// proxy DID or number if the outbound proxy fields are not empty in the restcomm.xml
if (proxyURI != null && !proxyURI.isEmpty()) {
//FIXME: not so nice to just inject headers here
if (er.getOutboundProxyHeaders() != null) {
B2BUAHelper.addHeadersToMessage(request, er.getOutboundProxyHeaders(), sipFactory);
request.getSession().setAttribute(B2BUAHelper.EXTENSION_HEADERS, er.getOutboundProxyHeaders());
}
proxyOut(request, client, toUser, toHost, toHostIpAddress, toPort, outboundIntf, proxyURI, proxyUsername, proxyPassword, from, to, callToSipUri);
} else {
errMsg = "Restcomm tried to proxy this call to an outbound party but it seems the outbound proxy is not configured.";
sendNotification(client.getAccountSid(), errMsg, 11004, "warning", true);
}
}
} else {
//Extensions didn't allow this call
final SipServletResponse response = request.createResponse(SC_FORBIDDEN, "Call request not allowed");
response.send();
if (logger.isDebugEnabled()) {
logger.debug("Call request not allowed: " + er.toString());
}
}
ec.executePostOutboundAction(er, this.extensions);
return;
}
} else {
// Client is null, check if this call is for a registered DID (application)
// First try to check if the call is for a client
if (toClient != null) {
ExtensionController ec = ExtensionController.getInstance();
final IExtensionCreateCallRequest cc = new CreateCall(fromUser, toUser, "", "", false, 0, CreateCallType.CLIENT, toClient.getAccountSid(), null, null, null, null);
ExtensionResponse extRes = ec.executePreInboundAction(cc, this.extensions);
if (extRes.isAllowed()) {
proxyDialClientThroughMediaServer(request, toClient, toClient.getLogin());
return;
} else {
if (logger.isDebugEnabled()) {
final String errMsg = "Inbound PSTN Call to Client not Allowed";
logger.debug(errMsg);
}
String errMsg = "Inbound PSTN Call to Client: " + toClient.getFriendlyName()
+ " is not Allowed";
sendNotification(client.getAccountSid(), errMsg, 11001, "warning", true);
final SipServletResponse resp = request.createResponse(SC_FORBIDDEN, "Call not allowed");
resp.send();
}
ec.executePostInboundAction(cc, extensions);
return;
}
if (redirectToHostedVoiceApp(request, accounts, applications, toUser, null,number)) {
// This is a call to a registered DID (application)
return;
}
if (actAsProxyOut) {
processRequestAndProxyOut(request, client, toUser);
return;
}
}
final SipServletResponse response = request.createResponse(SC_NOT_FOUND);
response.send();
// We didn't find anyway to handle the call.
String errMsg = "Restcomm cannot process this call because the destination number " + toUser
+ "cannot be found or there is application attached to that";
sendNotification(null, errMsg, 11005, "error", true);
}
private boolean proxyOut(SipServletRequest request, Client client, String toUser, String toHost, String toHostIpAddress, String toPort, SipURI outboundIntf, String proxyURI, String proxyUsername, String proxyPassword, SipURI from, SipURI to, boolean callToSipUri) throws UnknownHostException {
final Configuration runtime = configuration.subset("runtime-settings");
final boolean useLocalAddressAtFromHeader = runtime.getBoolean("use-local-address", false);
final boolean outboudproxyUserAtFromHeader = runtime.subset("outbound-proxy").getBoolean(
"outboudproxy-user-at-from-header", true);
final String fromHost = ((SipURI) request.getFrom().getURI()).getHost();
final String fromHostIpAddress = DNSUtils.getByName(fromHost).getHostAddress();
// final String fromPort = String.valueOf(((SipURI) request.getFrom().getURI()).getPort()).equalsIgnoreCase("-1") ? "5060"
// : String.valueOf(((SipURI) request.getFrom().getURI()).getHost());
if (logger.isInfoEnabled()) {
logger.info("fromHost: " + fromHost + "fromHostIP: " + fromHostIpAddress + "myHostIp: " + myHostIp + " mediaExternalIp: " + mediaExternalIp
+ " toHost: " + toHost + " toHostIP: " + toHostIpAddress + " proxyUri: " + proxyURI);
}
if ((myHostIp.equalsIgnoreCase(toHost) || mediaExternalIp.equalsIgnoreCase(toHost)) ||
(myHostIp.equalsIgnoreCase(toHostIpAddress) || mediaExternalIp.equalsIgnoreCase(toHostIpAddress))
// https://github.com/RestComm/Restcomm-Connect/issues/1357
|| (fromHost.equalsIgnoreCase(toHost) || fromHost.equalsIgnoreCase(toHostIpAddress))
|| (fromHostIpAddress.equalsIgnoreCase(toHost) || fromHostIpAddress.equalsIgnoreCase(toHostIpAddress))) {
if (logger.isInfoEnabled()) {
logger.info("Call to NUMBER. myHostIp: " + myHostIp + " mediaExternalIp: " + mediaExternalIp
+ " toHost: " + toHost + " proxyUri: " + proxyURI);
}
try {
if (useLocalAddressAtFromHeader) {
if (outboudproxyUserAtFromHeader) {
from = (SipURI) sipFactory.createSipURI(proxyUsername,
mediaExternalIp + ":" + outboundIntf.getPort());
} else {
from = sipFactory.createSipURI(((SipURI) request.getFrom().getURI()).getUser(),
mediaExternalIp + ":" + outboundIntf.getPort());
}
} else {
if (outboudproxyUserAtFromHeader) {
// https://telestax.atlassian.net/browse/RESTCOMM-633. Use the outbound proxy username as
// the userpart of the sip uri for the From header
from = (SipURI) sipFactory.createSipURI(proxyUsername, proxyURI);
} else {
from = sipFactory.createSipURI(((SipURI) request.getFrom().getURI()).getUser(), proxyURI);
}
}
to = sipFactory.createSipURI(((SipURI) request.getTo().getURI()).getUser(), proxyURI);
} catch (Exception exception) {
if (logger.isInfoEnabled()) {
logger.info("Exception: " + exception);
}
}
} else {
if (logger.isInfoEnabled()) {
logger.info("Call to SIP URI. myHostIp: " + myHostIp + " mediaExternalIp: " + mediaExternalIp
+ " toHost: " + toHost + " proxyUri: " + proxyURI);
}
from = sipFactory.createSipURI(((SipURI) request.getFrom().getURI()).getUser(), outboundIntf.getHost()
+ ":" + outboundIntf.getPort());
to = sipFactory.createSipURI(toUser, toHost + ":" + toPort);
callToSipUri = true;
}
if (B2BUAHelper.redirectToB2BUA(system, request, client, from, to, proxyUsername, proxyPassword, storage,
sipFactory, callToSipUri, patchForNatB2BUASessions)) {
return true;
}
return false;
}
private boolean isWebRTC(final SipServletRequest request) {
String transport = request.getTransport();
String userAgent = request.getHeader(UserAgent.NAME);
//The check for request.getHeader(UserAgentHeader.NAME).equals("sipunit") has been added in order to be able to test this feature with sipunit at the Restcomm testsuite
if (userAgent != null && !userAgent.isEmpty() && userAgent.equalsIgnoreCase("wss-sipunit")) {
return true;
}
if (!request.getInitialTransport().equalsIgnoreCase(transport)) {
transport = request.getInitialTransport();
if ("ws".equalsIgnoreCase(transport) || "wss".equalsIgnoreCase(transport))
return true;
}
try {
if (SdpUtils.isWebRTCSDP(request.getContentType(), request.getRawContent())) {
return true;
}
} catch (SdpParseException e) {
} catch (IOException e) {
}
return false;
}
private void processRequestAndProxyOut(final SipServletRequest request, final Client client, final String destNumber) {
String requestFromHost = null;
ProxyRule matchedProxyRule = null;
SipURI fromUri = null;
try {
if (isActAsProxyOutUseFromHeader) {
fromUri = ((SipURI) request.getFrom().getURI());
} else {
fromUri = ((SipURI) request.getAddressHeader("Contact").getURI());
}
} catch (ServletParseException e) {
logger.error("Problem while trying to process an `ActAsProxy` request, " + e);
}
requestFromHost = fromUri.getHost() + ":" + fromUri.getPort();
for (ProxyRule proxyRule : proxyOutRules) {
if (requestFromHost != null) {
if (requestFromHost.equalsIgnoreCase(proxyRule.getFromUri())) {
matchedProxyRule = proxyRule;
break;
}
}
}
if (matchedProxyRule != null) {
String sipUri = String.format("sip:%s@%s", destNumber, matchedProxyRule.getToUri());
String rcml;
if (matchedProxyRule.getUsername() != null && !matchedProxyRule.getUsername().isEmpty() && matchedProxyRule.getPassword() != null && !matchedProxyRule.getPassword().isEmpty()) {
rcml = String.format("<Response><Dial><Sip username=\"%s\" password=\"%s\">%s</Sip></Dial></Response>", matchedProxyRule.getUsername(), matchedProxyRule.getPassword(), sipUri);
} else {
rcml = String.format("<Response><Dial><Sip>%s</Sip></Dial></Response>", sipUri);
}
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self());
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
Sid accountSid = null;
String apiVersion = null;
if (client != null) {
accountSid = client.getAccountSid();
apiVersion = client.getApiVersion();
} else {
//Todo get Administrators account from RestcommConfiguration
accountSid = new Sid("ACae6e420f425248d6a26948c17a9e2acf");
apiVersion = RestcommConfiguration.getInstance().getMain().getApiVersion();
}
builder.setAccount(accountSid);
builder.setVersion(apiVersion);
final Account account = storage.getAccountsDao().getAccount(accountSid);
builder.setEmailAddress(account.getEmailAddress());
builder.setRcml(rcml);
builder.setMonitoring(monitoring);
final Props props = VoiceInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
final ActorRef call = call(accountSid, null);
final SipApplicationSession application = request.getApplicationSession();
application.setAttribute(Call.class.getName(), call);
call.tell(request, self());
interpreter.tell(new StartInterpreter(call), self());
} else {
if (logger.isInfoEnabled()) {
logger.info("No rule matched for the `ActAsProxy` feature");
}
}
}
private void proxyThroughMediaServerAsNumber(final SipServletRequest request, final Client client, final String destNumber) {
String number = destNumber;
String customHeaders = customHeaders(request);
if (customHeaders != null && !customHeaders.equals("")) {
number = destNumber+"?"+customHeaders;
}
String rcml = "<Response><Dial>" + number + "</Dial></Response>";
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self());
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
builder.setAccount(client.getAccountSid());
builder.setVersion(client.getApiVersion());
final Account account = storage.getAccountsDao().getAccount(client.getAccountSid());
builder.setEmailAddress(account.getEmailAddress());
builder.setRcml(rcml);
builder.setMonitoring(monitoring);
final Props props = VoiceInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
final ActorRef call = call(client.getAccountSid(), null);
final SipApplicationSession application = request.getApplicationSession();
application.setAttribute(Call.class.getName(), call);
call.tell(request, self());
interpreter.tell(new StartInterpreter(call), self());
}
private void proxyDialClientThroughMediaServer(final SipServletRequest request, final Client client, final String destNumber) {
String number = destNumber;
String customHeaders = customHeaders(request);
if (customHeaders != null && !customHeaders.equals("")) {
number = destNumber+"?"+customHeaders;
}
String rcml = "<Response><Dial><Client>" + number + "</Client></Dial></Response>";
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self());
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
builder.setAccount(client.getAccountSid());
builder.setVersion(client.getApiVersion());
final Account account = storage.getAccountsDao().getAccount(client.getAccountSid());
builder.setEmailAddress(account.getEmailAddress());
builder.setRcml(rcml);
builder.setMonitoring(monitoring);
final Props props = VoiceInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
final ActorRef call = call(client.getAccountSid(), null);
final SipApplicationSession application = request.getApplicationSession();
application.setAttribute(Call.class.getName(), call);
call.tell(request, self());
interpreter.tell(new StartInterpreter(call), self());
}
private String customHeaders (final SipServletRequest request) {
StringBuffer customHeaders = new StringBuffer();
Iterator<String> headerNames = request.getHeaderNames();
while (headerNames.hasNext()) {
String headerName = headerNames.next();
if (headerName.startsWith("X-")) {
if (logger.isDebugEnabled()) {
logger.debug("Identified customer header at SipServletRequest : " + headerName);
}
if (customHeaders.length()>0) {
customHeaders.append("&");
}
customHeaders.append(headerName+"="+request.getHeader(headerName));
}
}
return customHeaders.toString();
}
private void info(final SipServletRequest request) throws IOException {
final ActorRef self = self();
final SipApplicationSession application = request.getApplicationSession();
// if this response is coming from a client that is in a p2p session with another registered client
// we will just proxy the response
SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(request);
if (linkedB2BUASession != null) {
if (logger.isInfoEnabled()) {
logger.info(String.format("B2BUA: Got INFO request: \n %s", request));
}
request.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, request);
SipServletRequest clonedInfo = linkedB2BUASession.createRequest("INFO");
linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedInfo);
// Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
SipURI toInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.TO_INET_URI);
SipURI fromInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.FROM_INET_URI);
InetAddress infoRURI = null;
try {
infoRURI = DNSUtils.getByName(((SipURI) clonedInfo.getRequestURI()).getHost());
} catch (UnknownHostException e) {
}
if (patchForNatB2BUASessions) {
if (toInetUri != null && infoRURI == null) {
if (logger.isInfoEnabled()) {
logger.info("Using the real ip address of the sip client " + toInetUri.toString()
+ " as a request uri of the CloneBye request");
}
clonedInfo.setRequestURI(toInetUri);
} else if (toInetUri != null
&& (infoRURI.isSiteLocalAddress() || infoRURI.isAnyLocalAddress() || infoRURI.isLoopbackAddress())) {
if (logger.isInfoEnabled()) {
logger.info("Using the real ip address of the sip client " + toInetUri.toString()
+ " as a request uri of the CloneInfo request");
}
clonedInfo.setRequestURI(toInetUri);
} else if (fromInetUri != null
&& (infoRURI.isSiteLocalAddress() || infoRURI.isAnyLocalAddress() || infoRURI.isLoopbackAddress())) {
if (logger.isInfoEnabled()) {
logger.info("Using the real ip address of the sip client " + fromInetUri.toString()
+ " as a request uri of the CloneInfo request");
}
clonedInfo.setRequestURI(fromInetUri);
}
}
clonedInfo.send();
} else {
final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
call.tell(request, self);
}
}
private void transfer(SipServletRequest request) throws Exception {
//Transferor is the one that initates the transfer
String transferor = ((SipURI) request.getAddressHeader("Contact").getURI()).getUser();
//Transferee is the one that gets transfered
String transferee = ((SipURI) request.getAddressHeader("To").getURI()).getUser();
//Trasnfer target, where the transferee will be transfered
String transferTarget = ((SipURI) request.getAddressHeader("Refer-To").getURI()).getUser();
CallDetailRecord cdr = null;
CallDetailRecordsDao dao = storage.getCallDetailRecordsDao();
SipServletResponse servletResponse = null;
final SipApplicationSession appSession = request.getApplicationSession();
//Initates the transfer
ActorRef transferorActor = (ActorRef) appSession.getAttribute(Call.class.getName());
if (transferorActor == null) {
if (logger.isInfoEnabled()) {
logger.info("Transferor Call Actor is null, cannot proceed with SIP Refer");
}
servletResponse = request.createResponse(SC_NOT_FOUND);
servletResponse.setHeader("Reason", "SIP REFER should be sent in dialog");
servletResponse.setHeader("Event", "refer");
servletResponse.send();
return;
}
final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS));
Future<Object> infoFuture = (Future<Object>) ask(transferorActor, new GetCallInfo(), expires);
CallResponse<CallInfo> infoResponse = (CallResponse<CallInfo>) Await.result(infoFuture,
Duration.create(10, TimeUnit.SECONDS));
CallInfo callInfo = infoResponse.get();
//Call must be in-progress to accept Sip Refer
if (callInfo != null && callInfo.state().equals(CallStateChanged.State.IN_PROGRESS)) {
try {
if (callInfo.direction().equalsIgnoreCase("inbound")) {
//Transferror is the inbound leg of the call
cdr = dao.getCallDetailRecord(callInfo.sid());
} else {
//Transferor is the outbound leg of the call
cdr = dao.getCallDetailRecord(dao.getCallDetailRecord(callInfo.sid()).getParentCallSid());
}
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Problem while trying to get the CDR of the call");
}
servletResponse = request.createResponse(SC_SERVER_INTERNAL_ERROR);
servletResponse.setHeader("Reason", "SIP Refer problem during execution");
servletResponse.setHeader("Event", "refer");
servletResponse.send();
return;
}
} else {
if (logger.isInfoEnabled()) {
logger.info("CallInfo is null or call state not in-progress. Cannot proceed to call transfer");
}
servletResponse = request.createResponse(SC_NOT_FOUND);
servletResponse.setHeader("Reason", "SIP Refer pre-conditions failed, call info is null or call not in progress");
servletResponse.setHeader("Event", "refer");
servletResponse.send();
return;
}
String phone = cdr.getTo();
Sid sourceOrganizationSid = storage.getAccountsDao().getAccount(cdr.getAccountSid()).getOrganizationSid();
Sid destOrg = SIPOrganizationUtil.searchOrganizationBySIPRequest(storage.getOrganizationsDao(), request);
IncomingPhoneNumber number = numberSelector.searchNumber(phone, sourceOrganizationSid, destOrg);
if (number == null || (number.getReferUrl() == null && number.getReferApplicationSid() == null)) {
if (logger.isInfoEnabled()) {
logger.info("Refer URL or Refer Applicatio for incoming phone number is null, cannot proceed with SIP Refer");
}
servletResponse = request.createResponse(SC_NOT_FOUND);
servletResponse.setHeader("Reason", "SIP Refer failed. Set Refer URL or Refer application for incoming phone number");
servletResponse.setHeader("Event", "refer");
servletResponse.send();
return;
}
// Get first transferorActor leg observers
Future<Object> future = (Future<Object>) ask(transferorActor, new GetCallObservers(), expires);
CallResponse<List<ActorRef>> response = (CallResponse<List<ActorRef>>) Await.result(future,
Duration.create(10, TimeUnit.SECONDS));
List<ActorRef> callObservers = response.get();
// Get the Voice Interpreter currently handling the transferorActor
ActorRef existingInterpreter = callObservers.iterator().next();
// Get the outbound leg of this transferorActor
future = (Future<Object>) ask(existingInterpreter, new GetRelatedCall(transferorActor), expires);
Object answer = (Object) Await.result(future, Duration.create(10, TimeUnit.SECONDS));
//Transferee will be transfered to the transfer target
ActorRef transfereeActor = null;
if (answer instanceof ActorRef) {
transfereeActor = (ActorRef) answer;
} else {
if (logger.isInfoEnabled()) {
logger.info("Transferee is not a Call actor, probably call is on conference");
}
servletResponse = request.createResponse(SC_NOT_FOUND);
servletResponse.setHeader("Reason", "SIP Refer failed. Transferee is not a Call actor, probably this is a conference");
servletResponse.setHeader("Event", "refer");
servletResponse.send();
transferorActor.tell(new Hangup(), null);
return;
}
servletResponse = request.createResponse(SC_ACCEPTED);
servletResponse.setHeader("Event", "refer");
servletResponse.send();
if (logger.isInfoEnabled()) {
logger.info("About to start Call Transfer");
logger.info("Transferor Call path: " + transferorActor.path());
if (transfereeActor != null) {
logger.info("Transferee Call path: " + transfereeActor.path());
}
// Cleanup all observers from both transferorActor legs
logger.info("Will tell Call actors to stop observing existing Interpreters");
}
if (logger.isDebugEnabled()) {
logger.debug("Call Transfer account: " + cdr.getAccountSid() + ", new RCML url: " + number.getReferUrl());
}
transferorActor.tell(new StopObserving(), self());
if (transfereeActor != null) {
transfereeActor.tell(new StopObserving(), self());
}
if (logger.isInfoEnabled()) {
logger.info("Existing observers removed from Calls actors");
// Cleanup existing Interpreter
logger.info("Existing Interpreter path: " + existingInterpreter.path() + " will be stopped");
}
existingInterpreter.tell(new StopInterpreter(true), null);
// Build a new VoiceInterpreter
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self());
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
builder.setAccount(cdr.getAccountSid());
builder.setVersion(cdr.getApiVersion());
if (number.getReferApplicationSid() != null) {
Application application = storage.getApplicationsDao().getApplication(number.getReferApplicationSid());
RcmlserverConfigurationSet rcmlserverConfig = RestcommConfiguration.getInstance().getRcmlserver();
RcmlserverResolver resolver = RcmlserverResolver.getInstance(rcmlserverConfig.getBaseUrl(), rcmlserverConfig.getApiPath());
builder.setUrl(uriUtils.resolve(resolver.resolveRelative(application.getRcmlUrl()), number.getAccountSid()));
} else {
builder.setUrl(uriUtils.resolve(number.getReferUrl(), number.getAccountSid()));
}
builder.setMethod((number.getReferMethod() != null && number.getReferMethod().length() > 0) ? number.getReferMethod() : "POST");
builder.setReferTarget(transferTarget);
builder.setTransferor(transferor);
builder.setTransferee(transferee);
builder.setFallbackUrl(null);
builder.setFallbackMethod("POST");
builder.setStatusCallback(null);
builder.setStatusCallbackMethod("POST");
builder.setMonitoring(monitoring);
// Ask first transferorActor leg to execute with the new Interpreter
final Props props = VoiceInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
system.scheduler().scheduleOnce(Duration.create(500, TimeUnit.MILLISECONDS), interpreter,
new StartInterpreter(transfereeActor), system.dispatcher());
if (logger.isInfoEnabled()) {
logger.info("New Intepreter for transfereeActor call leg: " + interpreter.path() + " started");
}
if (logger.isInfoEnabled()) {
logger.info("will hangup transferorActor: " + transferorActor.path());
}
transferorActor.tell(new Hangup(), null);
}
private void sendNotFound(final SipServletRequest request, Sid sourceOrganizationSid, String phone, Sid fromClientAccountSid) throws IOException {
//organization was not proper.
final SipServletResponse response = request.createResponse(SC_NOT_FOUND);
response.send();
String sourceDomainName = "";
if (sourceOrganizationSid != null) {
sourceDomainName = storage.getOrganizationsDao().getOrganization(sourceOrganizationSid).getDomainName();
}
// We found the number but organization was not proper
String errMsg = String.format("provided number %s does not belong to your domain %s.", phone, sourceDomainName);
logger.warning(errMsg+" Requiested URI was: "+ request.getRequestURI());
sendNotification(fromClientAccountSid, errMsg, 11005, "error", true);
}
private IncomingPhoneNumber getIncomingPhoneNumber (final SipServletRequest request, String phone, Sid fromClientAccountSid,
Sid sourceOrganizationSid, Sid toOrganization) {
IncomingPhoneNumber number = null;
try {
NumberSelectionResult result = numberSelector.searchNumberWithResult(phone, sourceOrganizationSid, toOrganization);
if (numberSelector.isFailedCall(result, sourceOrganizationSid, toOrganization)) {
// We found the number but organization was not proper
if (logger.isDebugEnabled()) {
String msg = String.format("Number found %s, but source org %s and destination org %s are not proper", number, sourceOrganizationSid.toString(), toOrganization.toString());
logger.debug(msg);
}
sendNotFound(request, sourceOrganizationSid, phone, fromClientAccountSid);
return null;
}
number = result.getNumber();
} catch (Exception notANumber) {
String errMsg;
if (number != null) {
errMsg = String.format("IncomingPhoneNumber %s does not have a Restcomm hosted application attached, exception %s", number.getPhoneNumber(), notANumber);
} else {
errMsg = String.format("IncomingPhoneNumber for %s, does not exist, exception %s", phone, notANumber);
}
sendNotification(fromClientAccountSid, errMsg, 11007, "error", false);
logger.warning(errMsg);
}
return number;
}
/**
* Try to locate a hosted voice app corresponding to the callee/To address. If one is found, begin execution, otherwise
* return false;
*
* @param request
* @param accounts
* @param applications
* @param phone
*/
private boolean redirectToHostedVoiceApp (final SipServletRequest request, final AccountsDao accounts,
final ApplicationsDao applications, String phone, Sid fromClientAccountSid,
IncomingPhoneNumber number) {
boolean isFoundHostedApp = false;
try {
if (number != null) {
ExtensionController ec = ExtensionController.getInstance();
IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.INBOUND_VOICE, number.getAccountSid());
ExtensionResponse er = ec.executePreInboundAction(far, extensions);
if (er.isAllowed()) {
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self());
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
//https://github.com/RestComm/Restcomm-Connect/issues/1939
Sid accSid = fromClientAccountSid == null ? number.getAccountSid() : fromClientAccountSid;
builder.setAccount(accSid);
builder.setPhone(number.getAccountSid());
builder.setVersion(number.getApiVersion());
// notifications should go to fromClientAccountSid email if not present then to number account
// https://github.com/RestComm/Restcomm-Connect/issues/2011
final Account account = accounts.getAccount(accSid);
builder.setEmailAddress(account.getEmailAddress());
final Sid sid = number.getVoiceApplicationSid();
if (sid != null) {
final Application application = applications.getApplication(sid);
RcmlserverConfigurationSet rcmlserverConfig = RestcommConfiguration.getInstance().getRcmlserver();
RcmlserverResolver rcmlserverResolver = RcmlserverResolver.getInstance(rcmlserverConfig.getBaseUrl(), rcmlserverConfig.getApiPath());
builder.setUrl(uriUtils.resolve(rcmlserverResolver.resolveRelative(application.getRcmlUrl()), number.getAccountSid()));
} else {
builder.setUrl(uriUtils.resolve(number.getVoiceUrl(), number.getAccountSid()));
}
final String voiceMethod = number.getVoiceMethod();
if (voiceMethod == null || voiceMethod.isEmpty()) {
builder.setMethod("POST");
} else {
builder.setMethod(voiceMethod);
}
URI uri = number.getVoiceFallbackUrl();
if (uri != null)
builder.setFallbackUrl(uriUtils.resolve(uri, number.getAccountSid()));
else
builder.setFallbackUrl(null);
builder.setFallbackMethod(number.getVoiceFallbackMethod());
builder.setStatusCallback(number.getStatusCallback());
builder.setStatusCallbackMethod(number.getStatusCallbackMethod());
builder.setMonitoring(monitoring);
final Props props = VoiceInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
final ActorRef call = call(accSid, null);
final SipApplicationSession application = request.getApplicationSession();
application.setAttribute(Call.class.getName(), call);
call.tell(request, self());
interpreter.tell(new StartInterpreter(call), self());
isFoundHostedApp = true;
ec.executePostInboundAction(far, extensions);
} else {
//Extensions didn't allowed this call
String errMsg = "Inbound call to Number: " + number.getPhoneNumber()
+ " is not allowed";
if (logger.isDebugEnabled()) {
logger.debug(errMsg);
}
sendNotification(number.getAccountSid(), errMsg, 11001, "warning", true);
final SipServletResponse resp = request.createResponse(SC_FORBIDDEN, "Call not allowed");
resp.send();
ec.executePostInboundAction(far, extensions);
return false;
}
}
} catch (Exception notANumber) {
String errMsg;
if (number != null) {
errMsg = String.format("IncomingPhoneNumber %s does not have a Restcomm hosted application attached, exception %s", number.getPhoneNumber(), notANumber);
} else {
errMsg = String.format("IncomingPhoneNumber for %s, does not exist, exception %s", phone, notANumber);
}
sendNotification(fromClientAccountSid, errMsg, 11007, "error", false);
logger.warning(errMsg);
isFoundHostedApp = false;
}
return isFoundHostedApp;
}
/**
* If there is VoiceUrl provided for a Client configuration, try to begin execution of the RCML app, otherwise return false.
*
* @param self
* @param request
* @param accounts
* @param applications
* @param client
*/
private boolean redirectToClientVoiceApp(final ActorRef self, final SipServletRequest request, final AccountsDao accounts,
final ApplicationsDao applications, final Client client) {
Sid applicationSid = client.getVoiceApplicationSid();
URI clientAppVoiceUrl = null;
if (applicationSid != null) {
final Application application = applications.getApplication(applicationSid);
RcmlserverConfigurationSet rcmlserverConfig = RestcommConfiguration.getInstance().getRcmlserver();
RcmlserverResolver resolver = RcmlserverResolver.getInstance(rcmlserverConfig.getBaseUrl(), rcmlserverConfig.getApiPath());
clientAppVoiceUrl = uriUtils.resolve(resolver.resolveRelative(application.getRcmlUrl()), client.getAccountSid());
}
if (clientAppVoiceUrl == null) {
clientAppVoiceUrl = client.getVoiceUrl();
}
boolean isClientManaged = ((applicationSid != null && !applicationSid.toString().isEmpty() && !applicationSid.toString().equals("")) ||
(clientAppVoiceUrl != null && !clientAppVoiceUrl.toString().isEmpty() && !clientAppVoiceUrl.toString().equals("")));
if (isClientManaged) {
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self);
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
builder.setAccount(client.getAccountSid());
builder.setVersion(client.getApiVersion());
final Account account = accounts.getAccount(client.getAccountSid());
builder.setEmailAddress(account.getEmailAddress());
final Sid sid = client.getVoiceApplicationSid();
builder.setUrl(clientAppVoiceUrl);
builder.setMethod(client.getVoiceMethod());
URI uri = client.getVoiceFallbackUrl();
if (uri != null)
builder.setFallbackUrl(uriUtils.resolve(uri, client.getAccountSid()));
else
builder.setFallbackUrl(null);
builder.setFallbackMethod(client.getVoiceFallbackMethod());
builder.setMonitoring(monitoring);
final Props props = VoiceInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
final ActorRef call = call(client.getAccountSid(), null);
final SipApplicationSession application = request.getApplicationSession();
application.setAttribute(Call.class.getName(), call);
call.tell(request, self);
interpreter.tell(new StartInterpreter(call), self);
}
return isClientManaged;
}
private void pong(final Object message) throws IOException {
final SipServletRequest request = (SipServletRequest) message;
final SipServletResponse response = request.createResponse(SC_OK);
response.send();
}
@Override
public void onReceive(final Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
if (logger.isDebugEnabled()) {
logger.debug("######### CallManager new message received, message instanceof : " + klass + " from sender : "
+ sender.getClass());
}
if (message instanceof SipServletRequest) {
final SipServletRequest request = (SipServletRequest) message;
final String method = request.getMethod();
if (request != null) {
if ("INVITE".equals(method)) {
if (check(request))
invite(request);
} else if ("OPTIONS".equals(method)) {
pong(request);
} else if ("ACK".equals(method)) {
ack(request);
} else if ("CANCEL".equals(method)) {
cancel(request);
} else if ("BYE".equals(method)) {
bye(request);
} else if ("INFO".equals(method)) {
info(request);
} else if ("REFER".equals(method)) {
transfer(request);
}
}
} else if (CreateCall.class.equals(klass)) {
outbound(message, sender);
} else if (ExecuteCallScript.class.equals(klass)) {
execute(message);
} else if (UpdateCallScript.class.equals(klass)) {
try {
update(message);
} catch (final Exception exception) {
sender.tell(new CallManagerResponse<ActorRef>(exception), self);
}
} else if (DestroyCall.class.equals(klass)) {
destroy(message);
} else if (message instanceof SipServletResponse) {
response(message);
} else if (message instanceof SipApplicationSessionEvent) {
timeout(message);
} else if (GetCall.class.equals(klass)) {
sender.tell(lookup(message), self);
} else if (GetActiveProxy.class.equals(klass)) {
sender.tell(getActiveProxy(), self);
} else if (SwitchProxy.class.equals(klass)) {
this.switchProxyRequest = (SwitchProxy) message;
sender.tell(switchProxy(), self);
} else if (GetProxies.class.equals(klass)) {
sender.tell(getProxies(message), self);
}
}
private void ack(SipServletRequest request) throws IOException {
SipServletResponse response = B2BUAHelper.getLinkedResponse(request);
// if this is an ACK that belongs to a B2BUA session, then we proxy it to the other client
if (response != null) {
SipServletRequest ack = response.createAck();
// if (!ack.getHeaders("Route").hasNext() && patchForNatB2BUASessions) {
if (patchForNatB2BUASessions) {
InetAddress ackRURI = null;
try {
ackRURI = DNSUtils.getByName(((SipURI) ack.getRequestURI()).getHost());
} catch (UnknownHostException e) {
}
boolean isBehindLB = false;
final String initialIpBeforeLB = response.getHeader("X-Sip-Balancer-InitialRemoteAddr");
String initialPortBeforeLB = response.getHeader("X-Sip-Balancer-InitialRemotePort");
if (initialIpBeforeLB != null) {
if (initialPortBeforeLB == null)
initialPortBeforeLB = "5060";
if (logger.isDebugEnabled()) {
logger.debug("We are behind load balancer, checking if the request URI needs to be patched");
}
isBehindLB = true;
}
// Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
SipURI toInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.TO_INET_URI);
if (toInetUri != null && ackRURI == null) {
if (isBehindLB) {
// https://github.com/RestComm/Restcomm-Connect/issues/1357
boolean patchRURI = isLBPatchRURI(ack, initialIpBeforeLB, initialPortBeforeLB);
if (patchRURI) {
if (logger.isDebugEnabled()) {
logger.debug("We are behind load balancer, but Using the real ip address of the sip client " + toInetUri.toString()
+ " as a request uri of the ACK request");
}
ack.setRequestURI(toInetUri);
} else {
// https://github.com/RestComm/Restcomm-Connect/issues/1357
if (logger.isDebugEnabled()) {
logger.debug("removing the toInetUri to avoid the other subsequent requests using it " + toInetUri.toString());
}
request.getSession().removeAttribute(B2BUAHelper.TO_INET_URI);
}
} else {
if (logger.isInfoEnabled()) {
logger.info("Using the real ip address of the sip client " + toInetUri.toString()
+ " as a request uri of the ACK request");
}
ack.setRequestURI(toInetUri);
}
} else if (toInetUri != null
&& (ackRURI.isSiteLocalAddress() || ackRURI.isAnyLocalAddress() || ackRURI.isLoopbackAddress())) {
if (isBehindLB) {
// https://github.com/RestComm/Restcomm-Connect/issues/1357
boolean patchRURI = isLBPatchRURI(ack, initialIpBeforeLB, initialPortBeforeLB);
if (patchRURI) {
if (logger.isDebugEnabled()) {
logger.debug("We are behind load balancer, but Using the real ip address of the sip client " + toInetUri.toString()
+ " as a request uri of the ACK request");
}
ack.setRequestURI(toInetUri);
} else {
// https://github.com/RestComm/Restcomm-Connect/issues/1357
if (logger.isDebugEnabled()) {
logger.debug("removing the toInetUri to avoid the other subsequent requests using it " + toInetUri.toString());
}
request.getSession().removeAttribute(B2BUAHelper.TO_INET_URI);
}
} else {
if (logger.isInfoEnabled()) {
logger.info("Using the real ip address of the sip client " + toInetUri.toString()
+ " as a request uri of the ACK request");
}
ack.setRequestURI(toInetUri);
}
} else if (toInetUri == null
&& (ackRURI.isSiteLocalAddress() || ackRURI.isAnyLocalAddress() || ackRURI.isLoopbackAddress())) {
if (logger.isInfoEnabled()) {
logger.info("Public IP toInetUri from SipSession is null, will check LB headers from last Response");
}
if (isBehindLB) {
String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
SipURI uri = sipFactory.createSipURI(null, realIP);
boolean patchRURI = isLBPatchRURI(ack, initialIpBeforeLB, initialPortBeforeLB);
if (patchRURI) {
if (logger.isDebugEnabled()) {
logger.debug("We are behind load balancer, will use Initial Remote Address " + initialIpBeforeLB + ":"
+ initialPortBeforeLB + " for the ACK request");
}
ack.setRequestURI(uri);
}
} else {
if (logger.isInfoEnabled()) {
logger.info("LB Headers are also null");
}
}
}
}
ack.send();
SipApplicationSession sipApplicationSession = request.getApplicationSession();
// Defaulting the sip application session to 1h
sipApplicationSession.setExpires(maxP2PCallLength);
} else {
if (logger.isInfoEnabled()) {
logger.info("Linked Response couldn't be found for ACK request");
}
final ActorRef call = (ActorRef) request.getApplicationSession().getAttribute(Call.class.getName());
if (call != null) {
if (logger.isInfoEnabled()) {
logger.info("Will send ACK to call actor: " + call.path());
}
call.tell(request, self());
}
}
// else {
// SipSession sipSession = request.getSession();
// SipApplicationSession sipAppSession = request.getApplicationSession();
// if(sipSession.getInvalidateWhenReady()){
// logger.info("Invalidating sipSession: "+sipSession.getId());
// sipSession.invalidate();
// }
// if(sipAppSession.getInvalidateWhenReady()){
// logger.info("Invalidating sipAppSession: "+sipAppSession.getId());
// sipAppSession.invalidate();
// }
// }
}
private boolean isLBPatchRURI(SipServletRequest request,
final String initialIpBeforeLB, String initialPortBeforeLB) {
try {
// https://github.com/RestComm/Restcomm-Connect/issues/1336 checking if the initial IP and Port behind LB is part of the route set or not
ListIterator<? extends Address> routes = request.getAddressHeaders(RouteHeader.NAME);
while (routes.hasNext()) {
SipURI route = (SipURI) routes.next().getURI();
String routeHost = route.getHost();
int routePort = route.getPort();
if (routePort < 0) {
routePort = 5060;
}
if (logger.isDebugEnabled()) {
logger.debug("Checking if route " + routeHost + ":" + routePort + " is matching ip and port before LB " + initialIpBeforeLB + ":"
+ initialPortBeforeLB + " for the " + request.getMethod() + " request");
}
if (routeHost.equalsIgnoreCase(initialIpBeforeLB) && routePort == Integer.parseInt(initialPortBeforeLB)) {
if (logger.isDebugEnabled()) {
logger.debug("route " + route + " is matching ip and port before LB " + initialIpBeforeLB + ":"
+ initialPortBeforeLB + " for the " + request.getMethod() + " request, so not patching the Request-URI");
}
return false;
}
}
} catch (ServletParseException e) {
logger.error("Impossible to parse the route set from the request " + request, e);
}
return true;
}
private void execute(final Object message) {
final ExecuteCallScript request = (ExecuteCallScript) message;
final ActorRef self = self();
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self);
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
builder.setAccount(request.account());
builder.setVersion(request.version());
builder.setUrl(request.url());
builder.setMethod(request.method());
builder.setFallbackUrl(request.fallbackUrl());
builder.setFallbackMethod(request.fallbackMethod());
builder.setMonitoring(monitoring);
builder.setTimeout(request.timeout());
final Props props = VoiceInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
interpreter.tell(new StartInterpreter(request.call()), self);
}
@SuppressWarnings("unchecked")
private void update(final Object message) throws Exception {
final UpdateCallScript request = (UpdateCallScript) message;
final ActorRef self = self();
final ActorRef call = request.call();
final Boolean moveConnectedCallLeg = request.moveConnecteCallLeg();
// Get first call leg observers
final Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS));
Future<Object> future = (Future<Object>) ask(call, new GetCallObservers(), expires);
CallResponse<List<ActorRef>> response = (CallResponse<List<ActorRef>>) Await.result(future,
Duration.create(10, TimeUnit.SECONDS));
List<ActorRef> callObservers = response.get();
// Get the Voice Interpreter currently handling the call
//TODO possible bug here. Since we have more than one call observer, later there might be the case that the first one is not the VI
//TODO set the VI using specific message, also get the VI using specific message. The VI will still be in the observers list but it will set/get using specific method
ActorRef existingInterpreter = callObservers.iterator().next();
// Get the outbound leg of this call
future = (Future<Object>) ask(existingInterpreter, new GetRelatedCall(call), expires);
Object answer = (Object) Await.result(future, Duration.create(10, TimeUnit.SECONDS));
ActorRef relatedCall = null;
List<ActorRef> listOfRelatedCalls = null;
if (answer instanceof ActorRef) {
relatedCall = (ActorRef) answer;
} else if (answer instanceof List) {
listOfRelatedCalls = (List<ActorRef>) answer;
}
if (logger.isInfoEnabled()) {
logger.info("About to start Live Call Modification, moveConnectedCallLeg: " + moveConnectedCallLeg);
logger.info("Initial Call path: " + call.path());
if (relatedCall != null) {
logger.info("Related Call path: " + relatedCall.path());
}
if (listOfRelatedCalls != null) {
logger.info("List of related calls received, size of the list: " + listOfRelatedCalls.size());
}
// Cleanup all observers from both call legs
logger.info("Will tell Call actors to stop observing existing Interpreters");
}
if (logger.isDebugEnabled()) {
logger.debug("LCM account: " + request.account() + ", moveConnectedCallLeg: " + moveConnectedCallLeg + ", new RCML url: " + request.url());
}
call.tell(new StopObserving(), self());
if (relatedCall != null) {
relatedCall.tell(new StopObserving(), self());
}
if (listOfRelatedCalls != null) {
for (ActorRef branch : listOfRelatedCalls) {
branch.tell(new StopObserving(), self());
}
}
if (logger.isInfoEnabled()) {
logger.info("Existing observers removed from Calls actors");
// Cleanup existing Interpreter
logger.info("Existing Interpreter path: " + existingInterpreter.path() + " will be stopped");
}
existingInterpreter.tell(new StopInterpreter(true), null);
// Build a new VoiceInterpreter
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self);
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
builder.setAccount(request.account());
builder.setVersion(request.version());
builder.setUrl(request.url());
builder.setMethod(request.method());
builder.setFallbackUrl(request.fallbackUrl());
builder.setFallbackMethod(request.fallbackMethod());
builder.setStatusCallback(request.callback());
builder.setStatusCallbackMethod(request.callbackMethod());
builder.setMonitoring(monitoring);
final Props props = VoiceInterpreter.props(builder.build());
// Ask first call leg to execute with the new Interpreter
final ActorRef interpreter = getContext().actorOf(props);
system.scheduler().scheduleOnce(Duration.create(500, TimeUnit.MILLISECONDS), interpreter,
new StartInterpreter(request.call()), system.dispatcher());
// interpreter.tell(new StartInterpreter(request.call()), self);
if (logger.isInfoEnabled()) {
logger.info("New Intepreter for first call leg: " + interpreter.path() + " started");
}
// Check what to do with the second/outbound call leg of the call
if (relatedCall != null && listOfRelatedCalls == null) {
if (moveConnectedCallLeg) {
final ActorRef relatedInterpreter = getContext().actorOf(props);
if (logger.isInfoEnabled()) {
logger.info("About to redirect related Call :" + relatedCall.path()
+ " with 200ms delay to related interpreter: " + relatedInterpreter.path());
}
system.scheduler().scheduleOnce(Duration.create(1000, TimeUnit.MILLISECONDS), relatedInterpreter,
new StartInterpreter(relatedCall), system.dispatcher());
if (logger.isInfoEnabled()) {
logger.info("New Intepreter for Second call leg: " + relatedInterpreter.path() + " started");
}
} else {
if (logger.isInfoEnabled()) {
logger.info("moveConnectedCallLeg is: " + moveConnectedCallLeg + " so will hangup relatedCall: " + relatedCall.path());
}
relatedCall.tell(new Hangup(), null);
// getContext().stop(relatedCall);
}
}
if (listOfRelatedCalls != null) {
for (ActorRef branch : listOfRelatedCalls) {
branch.tell(new Hangup(), null);
}
if (logger.isInfoEnabled()) {
String msg = String.format("LiveCallModification request while dial forking, terminated %d calls", listOfRelatedCalls.size());
logger.info(msg);
}
}
}
private void outbound(final Object message, final ActorRef sender) throws ServletParseException {
final CreateCall request = (CreateCall) message;
ExtensionController ec = ExtensionController.getInstance();
ExtensionResponse extRes = ec.executePreOutboundAction(request, this.extensions);
switch (request.type()) {
case CLIENT: {
if (extRes.isAllowed()) {
ClientsDao clients = storage.getClientsDao();
String clientName = request.to().replaceFirst("client:", "");
final Client client = clients.getClient(clientName, storage.getAccountsDao().getAccount(request.accountId()).getOrganizationSid());
if (client != null) {
long delay = pushNotificationServerHelper.sendPushNotificationIfNeeded(client.getPushClientIdentity());
system.scheduler().scheduleOnce(Duration.create(delay, TimeUnit.MILLISECONDS), new Runnable() {
@Override
public void run() {
try {
outboundToClient(request, sender, client);
ExtensionController.getInstance().executePostOutboundAction(request, extensions);
} catch (ServletParseException e) {
throw new RuntimeException(e);
}
}
}, system.dispatcher());
} else {
String errMsg = "The SIP Client " + request.to() + " is not registered or does not exist";
logger.warning(errMsg);
sendNotification(request.accountId(), errMsg, 11008, "error", true);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
}
} else {
//Extensions didn't allowed this call
final String errMsg = "Not Allowed to make this outbound call";
logger.warning(errMsg);
sender.tell(new CallManagerResponse<ActorRef>(new RestcommExtensionException(errMsg), request), self());
}
ec.executePostOutboundAction(request, this.extensions);
break;
}
case PSTN: {
if (extRes.isAllowed()) {
outboundToPstn(request, sender);
} else {
//Extensions didn't allowed this call
final String errMsg = "Not Allowed to make this outbound call";
logger.warning(errMsg);
sender.tell(new CallManagerResponse<ActorRef>(new RestcommExtensionException(errMsg), request), self());
}
ec.executePostOutboundAction(request, this.extensions);
break;
}
case SIP: {
if (actAsImsUa) {
outboundToIms(request, sender);
} else if (request.isAllowed()) {
outboundToSip(request, sender);
} else {
//Extensions didn't allowed this call
final String errMsg = "Not Allowed to make this outbound call";
logger.warning(errMsg);
sender.tell(new CallManagerResponse<ActorRef>(new RestcommExtensionException(errMsg), request), self());
}
ec.executePostOutboundAction(request, this.extensions);
break;
}
}
}
private void outboundToClient(final CreateCall request, final ActorRef sender, final Client client) throws ServletParseException {
SipURI outboundIntf = null;
SipURI from = null;
SipURI to = null;
boolean webRTC = false;
boolean isLBPresent = false;
String customHeaders = request.getCustomHeaders();
final RegistrationsDao registrationsDao = storage.getRegistrationsDao();
//1, If this is a WebRTC client check if the instance is the current instance
//2. Check if the client has more than one registrations
List<Registration> registrationToDial = new CopyOnWriteArrayList<Registration>();
Sid organizationSid = storage.getAccountsDao().getAccount(request.accountId()).getOrganizationSid();
List<Registration> registrations = registrationsDao.getRegistrations(client.getLogin(), organizationSid);
if (registrations != null && registrations.size() > 0) {
if (logger.isInfoEnabled()) {
logger.info("Preparing call for client: " + client + ". There are " + registrations.size() + " registrations at the database for this client");
}
for (Registration registration : registrations) {
if (registration.isWebRTC()) {
if (registration.isLBPresent()) {
if (logger.isInfoEnabled())
logger.info("WebRTC registration behind LB. Will add WebRTC registration: " + registration.getLocation() + " to the list to be dialed for client: " + client);
registrationToDial.add(registration);
} else {
//If this is a WebRTC client registration, check that the InstanceId of the registration is for the current Restcomm instance
if ((registration.getInstanceId() != null && !registration.getInstanceId().equals(RestcommConfiguration.getInstance().getMain().getInstanceId()))) {
logger.warning("Cannot create call for user agent: " + registration.getLocation() + " since this is a webrtc client registered in another Restcomm instance.");
} else {
if (logger.isInfoEnabled())
logger.info("Will add WebRTC registration: " + registration.getLocation() + " to the list to be dialed for client: " + client);
registrationToDial.add(registration);
}
}
} else {
if (logger.isInfoEnabled())
logger.info("Will add registration: " + registration.getLocation() + " to the list to be dialed for client: " + client);
registrationToDial.add(registration);
}
}
} else {
String errMsg = "The SIP Client " + request.to() + " is not registered or does not exist";
logger.warning(errMsg);
sendNotification(request.accountId(), errMsg, 11008, "error", true);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
return;
}
if (registrationToDial.size() > 0) {
if (logger.isInfoEnabled()) {
if (registrationToDial.size() > 1) {
logger.info("Preparing call for client: " + client + ", after WebRTC check, Restcomm have to dial :" + registrationToDial.size() + " registrations");
}
}
List<ActorRef> calls = new CopyOnWriteArrayList<>();
for (Registration registration : registrationToDial) {
if (logger.isInfoEnabled())
logger.info("Will proceed to create call for client: " + registration.getLocation() + " registration instanceId: " + registration.getInstanceId() + " own InstanceId: " + RestcommConfiguration.getInstance().getMain().getInstanceId());
String transport;
if (registration.getLocation().contains("transport")) {
transport = registration.getLocation().split(";")[1].replace("transport=", "");
outboundIntf = outboundInterface(transport);
} else {
transport = "udp";
outboundIntf = outboundInterface(transport);
}
if (outboundIntf == null) {
String errMsg = "The outbound interface for transport: " + transport + " is NULL, something is wrong with container, cannot proceed to call client " + request.to();
logger.error(errMsg);
sendNotification(request.accountId(), errMsg, 11008, "error", true);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
return;
}
if (request.from() != null && request.from().contains("@")) {
// https://github.com/Mobicents/RestComm/issues/150 if it contains @ it means this is a sip uri and we allow
// to use it directly
//from = (SipURI) sipFactory.createURI(request.from());
String[] f = request.from().split("@");
from = sipFactory.createSipURI(f[0], f[1]);
} else if (request.from() != null) {
if (outboundIntf != null) {
from = sipFactory.createSipURI(request.from(), mediaExternalIp + ":" + outboundIntf.getPort());
} else {
logger.error("Outbound interface is null, cannot create From header to be used to Dial client: " + client);
}
} else {
from = outboundIntf;
}
final String location = registration.getLocation();
to = (SipURI) sipFactory.createURI(location);
if (customHeaders != null) {
to = addCustomHeadersForToUri(customHeaders, to);
}
webRTC = registration.isWebRTC();
if (from == null || to == null) {
//In case From or To are null we have to cancel outbound call and hnagup initial call if needed
final String errMsg = "From and/or To are null, we cannot proceed to the outbound call to: " + request.to();
logger.warning(errMsg);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
} else {
if(useSbc) {
// To avoid using SDP with encryption enabled between RC and the SBC
// we need to disable webRTC as it will be handled on the last mile
// ie between SBC and Client and SBC will be responsible for that not RC
webRTC = false;
}
calls.add(createOutbound(request, from, to, webRTC));
}
}
if (calls.size() > 0) {
sender.tell(new CallManagerResponse<List<ActorRef>>(calls), self());
}
} else {
String errMsg = "The SIP Client " + request.to() + " is not registered or does not exist";
logger.warning(errMsg);
sendNotification(request.accountId(), errMsg, 11008, "error", true);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
}
}
private SipURI addCustomHeadersForToUri (String customHeaders, SipURI to) {
for (String customHeader: customHeaders.split("&")) {
if (customHeader.contains("=")) {
to.setHeader(customHeader.split("=")[0], customHeader.split("=")[1]);
} else {
String msg = String.format("Custom header %s not properly formatted", customHeader);
if (logger.isDebugEnabled()) {
logger.debug(msg);
}
}
}
return to;
}
private void outboundToPstn(final CreateCall request, final ActorRef sender) throws ServletParseException {
final String uri = (request.getOutboundProxy() != null && (!request.getOutboundProxy().isEmpty())) ? request.getOutboundProxy() : activeProxy;
SipURI outboundIntf = null;
SipURI from = null;
SipURI to = null;
String customHeaders = request.getCustomHeaders();
final Configuration runtime = configuration.subset("runtime-settings");
final boolean useLocalAddressAtFromHeader = runtime.getBoolean("use-local-address", false);
final String proxyUsername = (request.username() != null) ? request.username() : activeProxyUsername;
if (uri != null) {
try {
to = sipFactory.createSipURI(request.to(), uri);
if (customHeaders != null) {
to = addCustomHeadersForToUri(customHeaders, to);
}
String transport = (to.getTransportParam() != null) ? to.getTransportParam() : "udp";
outboundIntf = outboundInterface(transport);
final boolean outboudproxyUserAtFromHeader = runtime.subset("outbound-proxy").getBoolean(
"outboudproxy-user-at-from-header");
if (request.from() != null && request.from().contains("@")) {
// https://github.com/Mobicents/RestComm/issues/150 if it contains @ it means this is a sip uri and we allow
// to use it directly
from = (SipURI) sipFactory.createURI(request.from());
} else if (useLocalAddressAtFromHeader) {
from = sipFactory.createSipURI(request.from(), mediaExternalIp + ":" + outboundIntf.getPort());
} else {
if (outboudproxyUserAtFromHeader) {
// https://telestax.atlassian.net/browse/RESTCOMM-633. Use the outbound proxy username as the userpart
// of the sip uri for the From header
from = (SipURI) sipFactory.createSipURI(proxyUsername, uri);
} else {
from = sipFactory.createSipURI(request.from(), uri);
}
}
if (((SipURI) from).getUser() == null || ((SipURI) from).getUser() == "") {
if (uri != null) {
from = sipFactory.createSipURI(request.from(), uri);
} else {
from = (SipURI) sipFactory.createURI(request.from());
}
}
} catch (Exception exception) {
sender.tell(new CallManagerResponse<ActorRef>(exception, request), self());
}
if (from == null || to == null) {
//In case From or To are null we have to cancel outbound call and hnagup initial call if needed
final String errMsg = "From and/or To are null, we cannot proceed to the outbound call to: " + request.to();
logger.warning(errMsg);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
} else {
sender.tell(new CallManagerResponse<ActorRef>(createOutbound(request, from, to, false)), self());
}
} else {
String errMsg = "Cannot create call to: " + request.to() + ". The Active Outbound Proxy is null. Please check configuration";
logger.warning(errMsg);
sendNotification(request.accountId(), errMsg, 11008, "error", true);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
}
}
private void outboundToSip(final CreateCall request, final ActorRef sender) throws ServletParseException {
final String uri = (request.getOutboundProxy() != null && (!request.getOutboundProxy().isEmpty())) ? request.getOutboundProxy() : "";
SipURI outboundIntf = null;
SipURI from = null;
String customHeaders = request.getCustomHeaders();
SipURI to = (SipURI) sipFactory.createURI(request.to());
if (customHeaders != null) {
to = addCustomHeadersForToUri(customHeaders, to);
}
SipURI outboundProxyURI;
try {
//NB: ifblock not really necessary, but we dont want
//exceptions all the time
if(!uri.isEmpty()){
outboundProxyURI = (SipURI) sipFactory.createSipURI(null, uri);
to.setHost(outboundProxyURI.getHost());
if(outboundProxyURI.getPort()!= -1){
to.setPort(outboundProxyURI.getPort());
}
Iterator<String> params = outboundProxyURI.getParameterNames();
while(params.hasNext()){
String param = params.next();
to.setParameter(param, outboundProxyURI.getParameter(param));
}
}
} catch (Exception e) {
if(logger.isDebugEnabled()){
logger.debug("Exception: outboundProxy is "+uri+" "+e.getMessage());
}
}
String transport = (to.getTransportParam() != null) ? to.getTransportParam() : "udp";
outboundIntf = outboundInterface(transport);
if (request.from() == null) {
from = outboundInterface(transport);
} else {
if (request.from() != null && request.from().contains("@")) {
// https://github.com/Mobicents/RestComm/issues/150 if it contains @ it means this is a sip uri and we
// allow to use it directly
from = (SipURI) sipFactory.createURI(request.from());
} else {
if(request.accountId() != null){
Organization fromOrganization = storage.getOrganizationsDao().getOrganization(storage.getAccountsDao().getAccount(request.accountId()).getOrganizationSid());
from = sipFactory.createSipURI(request.from(), fromOrganization.getDomainName());
} else {
from = sipFactory.createSipURI(request.from(), outboundIntf.getHost() + ":" + outboundIntf.getPort());
}
}
}
if (from == null || to == null) {
//In case From or To are null we have to cancel outbound call and hnagup initial call if needed
final String errMsg = "From and/or To are null, we cannot proceed to the outbound call to: " + request.to();
logger.warning(errMsg);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
} else {
sender.tell(new CallManagerResponse<ActorRef>(createOutbound(request, from, to, false)), self());
}
}
private ActorRef createOutbound(final CreateCall request, final SipURI from, final SipURI to, final boolean webRTC) {
final Configuration runtime = configuration.subset("runtime-settings");
final String proxyUsername = (request.username() != null) ? request.username() : activeProxyUsername;
final String proxyPassword = (request.password() != null) ? request.password() : activeProxyPassword;
final ActorRef call = call(null, request);
final ActorRef self = self();
final boolean userAtDisplayedName = runtime.subset("outbound-proxy").getBoolean("user-at-displayed-name");
InitializeOutbound init;
if (request.from() != null && !request.from().contains("@") && userAtDisplayedName) {
init = new InitializeOutbound(request.from(), from, to, proxyUsername, proxyPassword, request.timeout(),
request.isFromApi(), runtime.getString("api-version"), request.accountId(), request.type(), storage, webRTC, request.mediaAttributes());
} else {
init = new InitializeOutbound(null, from, to, proxyUsername, proxyPassword, request.timeout(), request.isFromApi(),
runtime.getString("api-version"), request.accountId(), request.type(), storage, webRTC, request.mediaAttributes());
}
if (request.parentCallSid() != null) {
init.setParentCallSid(request.parentCallSid());
}
call.tell(init, self);
return call;
}
public void cancel(final Object message) throws IOException {
final ActorRef self = self();
final SipServletRequest request = (SipServletRequest) message;
final SipApplicationSession application = request.getApplicationSession();
// if this response is coming from a client that is in a p2p session with another registered client
// we will just proxy the response
SipServletRequest originalRequest = B2BUAHelper.getLinkedRequest(request);
SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(request);
if (originalRequest != null) {
if (logger.isInfoEnabled()) {
logger.info(String.format("B2BUA: Got CANCEL request: \n %s", request));
}
// SipServletRequest cancel = originalRequest.createCancel();
request.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, request);
String sessionState = linkedB2BUASession.getState().name();
SipServletResponse lastFinalResponse = (SipServletResponse) originalRequest.getSession().getAttribute(
B2BUAHelper.B2BUA_LAST_FINAL_RESPONSE);
if ((sessionState == SipSession.State.INITIAL.name() || sessionState == SipSession.State.EARLY.name())
&& !(lastFinalResponse != null && (lastFinalResponse.getStatus() == 401 || lastFinalResponse.getStatus() == 407))) {
SipServletRequest clonedCancel = originalRequest.createCancel();
linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedCancel);
clonedCancel.send();
} else {
SipServletRequest clonedBye = linkedB2BUASession.createRequest("BYE");
linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedBye);
clonedBye.send();
}
// SipServletRequest cancel = originalRequest.createCancel();
// cancel.send();
// originalRequest.createCancel().send();
} else {
final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
if (call != null)
call.tell(request, self);
}
}
public void bye(final Object message) throws IOException {
final ActorRef self = self();
final SipServletRequest request = (SipServletRequest) message;
final SipApplicationSession application = request.getApplicationSession();
// if this response is coming from a client that is in a p2p session with another registered client
// we will just proxy the response
SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(request);
if (linkedB2BUASession != null) {
if (logger.isInfoEnabled()) {
logger.info(String.format("B2BUA: Got BYE request: \n %s", request));
}
//Prepare the BYE request to the linked session
request.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, request);
SipServletRequest clonedBye = linkedB2BUASession.createRequest("BYE");
linkedB2BUASession.setAttribute(B2BUAHelper.B2BUA_LAST_REQUEST, clonedBye);
if (patchForNatB2BUASessions) {
// Issue #307: https://telestax.atlassian.net/browse/RESTCOMM-307
SipURI toInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.TO_INET_URI);
SipURI fromInetUri = (SipURI) request.getSession().getAttribute(B2BUAHelper.FROM_INET_URI);
InetAddress byeRURI = null;
try {
byeRURI = DNSUtils.getByName(((SipURI) clonedBye.getRequestURI()).getHost());
} catch (UnknownHostException e) {
}
boolean isBehindLB = false;
final String initialIpBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemoteAddr");
String initialPortBeforeLB = request.getHeader("X-Sip-Balancer-InitialRemotePort");
if (initialIpBeforeLB != null) {
if (initialPortBeforeLB == null)
initialPortBeforeLB = "5060";
if (logger.isDebugEnabled()) {
logger.debug("We are behind load balancer, checking if the request URI needs to be patched");
}
isBehindLB = true;
}
if (logger.isDebugEnabled()) {
logger.debug("toInetUri: " + toInetUri + " fromInetUri: " + fromInetUri + " byeRURI: " + byeRURI + " initialIpBeforeLB: " + initialIpBeforeLB
+ " initialPortBeforeLB: " + initialPortBeforeLB);
}
if (toInetUri != null && byeRURI == null) {
if (logger.isInfoEnabled()) {
logger.info("Using the real To inet ip address of the sip client " + toInetUri.toString()
+ " as a request uri of the CloneBye request");
}
clonedBye.setRequestURI(toInetUri);
} else if (toInetUri != null
&& (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress() || byeRURI.isLoopbackAddress())) {
if (logger.isInfoEnabled()) {
logger.info("Using the real To inet ip address of the sip client " + toInetUri.toString()
+ " as a request uri of the CloneBye request");
}
clonedBye.setRequestURI(toInetUri);
} else if (fromInetUri != null
&& (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress() || byeRURI.isLoopbackAddress())) {
if (isBehindLB) {
// https://github.com/RestComm/Restcomm-Connect/issues/1357
boolean patchRURI = isLBPatchRURI(clonedBye, initialIpBeforeLB, initialPortBeforeLB);
if (patchRURI) {
if (logger.isDebugEnabled()) {
logger.debug("We are behind load balancer, but Using the real ip address of the sip client " + fromInetUri.toString()
+ " as a request uri of the CloneBye request");
}
clonedBye.setRequestURI(fromInetUri);
}
} else {
if (logger.isInfoEnabled()) {
logger.info("Using the real From inet ip address of the sip client " + fromInetUri.toString()
+ " as a request uri of the CloneBye request");
}
clonedBye.setRequestURI(fromInetUri);
}
} else if (toInetUri == null
&& (byeRURI.isSiteLocalAddress() || byeRURI.isAnyLocalAddress() || byeRURI.isLoopbackAddress())) {
if (logger.isInfoEnabled()) {
logger.info("Public IP toInetUri from SipSession is null, will check LB headers from last Response");
}
if (isBehindLB) {
String realIP = initialIpBeforeLB + ":" + initialPortBeforeLB;
SipURI uri = sipFactory.createSipURI(null, realIP);
boolean patchRURI = isLBPatchRURI(clonedBye, initialIpBeforeLB, initialPortBeforeLB);
if (patchRURI) {
if (logger.isDebugEnabled()) {
logger.debug("We are behind load balancer, will use: " + initialIpBeforeLB + ":"
+ initialPortBeforeLB + " for the cloned BYE message");
}
clonedBye.setRequestURI(uri);
}
if (logger.isInfoEnabled()) {
logger.info("We are behind load balancer, will use Initial Remote Address " + initialIpBeforeLB + ":"
+ initialPortBeforeLB + " for the cloned BYE request");
}
} else {
if (logger.isInfoEnabled()) {
logger.info("LB Headers are also null");
}
}
}
}
B2BUAHelper.updateCDR(system, request, CallStateChanged.State.COMPLETED);
//Prepare 200 OK for received BYE
SipServletResponse okay = request.createResponse(Response.OK);
okay.send();
//Send the Cloned BYE
if (logger.isInfoEnabled()) {
logger.info(String.format("B2BUA: Will send out Cloned BYE request: \n %s", clonedBye));
}
clonedBye.send();
} else {
final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
if (call != null)
call.tell(request, self);
}
}
public void response(final Object message) throws IOException {
final ActorRef self = self();
final SipServletResponse response = (SipServletResponse) message;
// If Allow-Falback is true, check for error reponses and switch proxy if needed
if (allowFallback)
checkErrorResponse(response);
final SipApplicationSession application = response.getApplicationSession();
// if this response is coming from a client that is in a p2p session with another registered client
// we will just proxy the response
SipSession linkedB2BUASession = B2BUAHelper.getLinkedSession(response);
if (linkedB2BUASession!=null) {
if (response.getStatus() == SipServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED
|| response.getStatus() == SipServletResponse.SC_UNAUTHORIZED) {
AuthInfo authInfo = sipFactory.createAuthInfo();
String authHeader = response.getHeader("Proxy-Authenticate");
if (authHeader == null) {
authHeader = response.getHeader("WWW-Authenticate");
}
String tempRealm = authHeader.substring(authHeader.indexOf("realm=\"") + "realm=\"".length());
String realm = tempRealm.substring(0, tempRealm.indexOf("\""));
authInfo.addAuthInfo(response.getStatus(), realm, activeProxyUsername, activeProxyPassword);
SipServletRequest challengeRequest = response.getSession().createRequest(response.getRequest().getMethod());
response.getSession().setAttribute(B2BUAHelper.B2BUA_LAST_FINAL_RESPONSE, response);
challengeRequest.addAuthHeader(response, authInfo);
SipServletRequest invite = response.getRequest();
challengeRequest.setContent(invite.getContent(), invite.getContentType());
invite = challengeRequest;
Map<String,ArrayList<String>> extensionHeaders = (Map<String,ArrayList<String>>)linkedB2BUASession.getAttribute(B2BUAHelper.EXTENSION_HEADERS);
B2BUAHelper.addHeadersToMessage(challengeRequest, extensionHeaders, sipFactory);
challengeRequest.send();
} else {
B2BUAHelper.forwardResponse(system, response, patchForNatB2BUASessions);
}
} else {
if (application.isValid()) {
// otherwise the response is coming back to a Voice app hosted by Restcomm
final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
call.tell(response, self);
}
}
}
public ActorRef lookup(final Object message) {
final GetCall getCall = (GetCall) message;
final String callPath = getCall.getIdentifier();
final ActorContext context = getContext();
// TODO: The context.actorFor has been depreciated for actorSelection at the latest Akka release.
ActorRef call = null;
if (callPath != null) {
try {
call = context.actorFor(callPath);
} catch (Exception e) {
if (logger.isInfoEnabled()) {
logger.info("Problem during call lookup, callPath: " + callPath);
}
return null;
}
} else {
if (logger.isInfoEnabled()) {
logger.info("CallPath is null, call lookup cannot be executed");
}
}
return call;
}
public void timeout(final Object message) {
final ActorRef self = self();
final SipApplicationSessionEvent event = (SipApplicationSessionEvent) message;
final SipApplicationSession application = event.getApplicationSession();
final ActorRef call = (ActorRef) application.getAttribute(Call.class.getName());
if (call == null) {
if (application.isValid()) {
B2BUAHelper.dropB2BUA(application);
}
}
//if there is Call actor, session was set to never expired, since Call
//Akka actor is handling its own call expiration. so, do nothing in that case
//mark timeout as processed
application.setAttribute(TIMEOUT_ATT, "completed");
}
public void checkErrorResponse(SipServletResponse response) {
// Response should not be a proxy branch response and request should be initial and INVITE
if (!response.isBranchResponse()
&& (response.getRequest().getMethod().equalsIgnoreCase("INVITE") && response.getRequest().isInitial())) {
final int status = response.getStatus();
// Response status should be > 400 BUT NOT 401, 404, 407
if (status != SipServletResponse.SC_UNAUTHORIZED && status != SipServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED
&& status != SipServletResponse.SC_NOT_FOUND && status > 400) {
int failures = numberOfFailedCalls.incrementAndGet();
if (logger.isInfoEnabled()) {
logger.info("A total number of " + failures + " failures have now been counted.");
}
if (failures >= maxNumberOfFailedCalls) {
if (logger.isInfoEnabled()) {
logger.info("Max number of failed calls has been reached trying to switch over proxy.");
logger.info("Current proxy: " + getActiveProxy().get("ActiveProxy"));
}
switchProxy();
if (logger.isInfoEnabled()) {
logger.info("Switched to proxy: " + getActiveProxy().get("ActiveProxy"));
}
numberOfFailedCalls.set(0);
}
}
}
}
public Map<String, String> getActiveProxy() {
Map<String, String> activeProxyMap = new ConcurrentHashMap<String, String>();
activeProxyMap.put("ActiveProxy", this.activeProxy);
return activeProxyMap;
}
public Map<String, String> switchProxy() {
if (activeProxy.equalsIgnoreCase(primaryProxyUri)) {
activeProxy = fallBackProxyUri;
activeProxyUsername = fallBackProxyUsername;
activeProxyPassword = fallBackProxyPassword;
useFallbackProxy.set(true);
} else if (allowFallbackToPrimary) {
activeProxy = primaryProxyUri;
activeProxyUsername = primaryProxyUsername;
activeProxyPassword = primaryProxyPassword;
useFallbackProxy.set(false);
}
final Notification notification = notification(null, WARNING_NOTIFICATION, 14110,
"Max number of failed calls has been reached! Outbound proxy switched");
final NotificationsDao notifications = storage.getNotificationsDao();
notifications.addNotification(notification);
return getActiveProxy();
}
public Map<String, String> getProxies(final Object message) {
Map<String, String> proxies = new ConcurrentHashMap<String, String>();
proxies.put("ActiveProxy", activeProxy);
proxies.put("UsingFallBackProxy", useFallbackProxy.toString());
proxies.put("AllowFallbackToPrimary", String.valueOf(allowFallbackToPrimary));
proxies.put("PrimaryProxy", primaryProxyUri);
proxies.put("FallbackProxy", fallBackProxyUri);
return proxies;
}
private Notification notification(Sid accountId, final int log, final int error, final String message) {
String version = configuration.subset("runtime-settings").getString("api-version");
if (accountId == null) {
if (switchProxyRequest != null) {
accountId = switchProxyRequest.getSid();
} else {
accountId = new Sid("ACae6e420f425248d6a26948c17a9e2acf");
}
}
final Notification.Builder builder = Notification.builder();
final Sid sid = Sid.generate(Sid.Type.NOTIFICATION);
builder.setSid(sid);
builder.setAccountSid(accountId);
// builder.setCallSid(callSid);
builder.setApiVersion(version);
builder.setLog(log);
builder.setErrorCode(error);
final String base = configuration.subset("runtime-settings").getString("error-dictionary-uri");
StringBuilder buffer = new StringBuilder();
buffer.append(base);
if (!base.endsWith("/")) {
buffer.append("/");
}
buffer.append(error).append(".html");
final URI info = URI.create(buffer.toString());
builder.setMoreInfo(info);
builder.setMessageText(message);
final DateTime now = DateTime.now();
builder.setMessageDate(now);
try {
builder.setRequestUrl(new URI(""));
} catch (URISyntaxException e) {
e.printStackTrace();
}
builder.setRequestMethod("");
builder.setRequestVariables("");
buffer = new StringBuilder();
buffer.append("/").append(version).append("/Accounts/");
buffer.append(accountId.toString()).append("/Notifications/");
buffer.append(sid.toString());
final URI uri = URI.create(buffer.toString());
builder.setUri(uri);
return builder.build();
}
private SipURI outboundInterface(String transport) {
SipURI result = null;
@SuppressWarnings("unchecked") final List<SipURI> uris = (List<SipURI>) context.getAttribute(OUTBOUND_INTERFACES);
for (final SipURI uri : uris) {
final String interfaceTransport = uri.getTransportParam();
if (transport.equalsIgnoreCase(interfaceTransport)) {
result = uri;
}
}
return result;
}
private boolean isFromIms(final SipServletRequest request) throws ServletParseException {
SipURI uri = (SipURI) request.getRequestURI();
return uri.getUser() == null;
}
private Registration findRegistration(javax.servlet.sip.URI regUri) {
if (regUri == null) {
return null;
}
String formattedNumber = null;
if (regUri.isSipURI()) {
formattedNumber = ((SipURI) regUri).getUser().replaceFirst("\\+", "");
} else {
formattedNumber = ((TelURL) regUri).getPhoneNumber().replaceFirst("\\+", "");
}
if (logger.isInfoEnabled()) {
logger.info("looking for registrations for number: " + formattedNumber);
}
final RegistrationsDao registrationsDao = storage.getRegistrationsDao();
Sid orgSid = OrganizationUtil.getOrganizationSidBySipURIHost(storage, (SipURI)regUri);
if(orgSid == null){
logger.error("Null Organization: regUri: "+regUri);
}
List<Registration> registrations = registrationsDao.getRegistrations(formattedNumber, orgSid);
if (registrations == null || registrations.size() == 0) {
return null;
} else {
return registrations.get(0);
}
}
private void imsProxyThroughMediaServer(final SipServletRequest request, final Client client,
final javax.servlet.sip.URI destUri, final String user, final String password, boolean isFromIms)
throws IOException {
javax.servlet.sip.URI srcUri = request.getFrom().getURI();
if (logger.isInfoEnabled()) {
logger.info("imsProxyThroughMediaServer, isFromIms: " + isFromIms +
", destUri: " + destUri + ", srcUri: " + srcUri);
}
final Configuration runtime = configuration.subset("runtime-settings");
String destNumber = destUri.toString();
String rcml = "<Response><Dial>" + destNumber + "</Dial></Response>";
javax.servlet.sip.URI regUri = null;
if (isFromIms) {
regUri = destUri;
} else {
regUri = srcUri;
}
// Lookup of registration is based on srcUri (if call is toward IMS),
// or is based on destUri (if call is from IMS)
Registration reg = findRegistration(regUri);
if (reg == null) {
if (logger.isInfoEnabled()) {
logger.info("registrations not found");
}
final SipServletResponse response = request.createResponse(SC_NOT_FOUND);
response.send();
// We didn't find anyway to handle the call.
String errMsg = "Call cannot be processed because the registration: " + regUri.toString()
+ "cannot be found";
sendNotification(null, errMsg, 11005, "error", true);
return;
} else {
if (isFromIms) {
rcml = "<Response><Dial><Client>" + reg.getUserName() + "</Client></Dial></Response>";
}
if (logger.isInfoEnabled()) {
logger.info("rcml: " + rcml);
}
final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder();
builder.setConfiguration(configuration);
builder.setStorage(storage);
builder.setCallManager(self());
builder.setConferenceCenter(conferences);
builder.setBridgeManager(bridges);
builder.setSmsService(sms);
builder.setAccount(Sid.generate(Sid.Type.ACCOUNT, imsAccount));
builder.setVersion(runtime.getString("api-version"));
builder.setRcml(rcml);
builder.setMonitoring(monitoring);
builder.setAsImsUa(actAsImsUa);
if (actAsImsUa) {
builder.setImsUaLogin(user);
builder.setImsUaPassword(password);
}
final Props props = VoiceInterpreter.props(builder.build());
final ActorRef interpreter = getContext().actorOf(props);
final ActorRef call = call(null, null);
final SipApplicationSession application = request.getApplicationSession();
application.setAttribute(Call.class.getName(), call);
call.tell(request, self());
interpreter.tell(new StartInterpreter(call), self());
}
}
private void outboundToIms(final CreateCall request, final ActorRef sender) throws ServletParseException {
if (logger.isInfoEnabled()) {
logger.info("outboundToIms: " + request);
}
SipURI from;
SipURI to;
String customHeaders = request.getCustomHeaders();
to = (SipURI) sipFactory.createURI(request.to());
if (customHeaders != null) {
to = addCustomHeadersForToUri(customHeaders, to);
}
if (request.from() == null) {
from = sipFactory.createSipURI(null, imsDomain);
} else {
if (request.from() != null && request.from().contains("@")) {
// https://github.com/Mobicents/RestComm/issues/150 if it contains @ it means this is a sip uri and we
// allow to use it directly
String[] f = request.from().split("@");
from = sipFactory.createSipURI(f[0], f[1]);
} else {
from = sipFactory.createSipURI(request.from(), imsDomain);
}
}
if (from == null || to == null) {
//In case From or To are null we have to cancel outbound call and hnagup initial call if needed
final String errMsg = "From and/or To are null, we cannot proceed to the outbound call to: " + request.to();
logger.error(errMsg);
sender.tell(new CallManagerResponse<ActorRef>(new NullPointerException(errMsg), request), self());
} else {
final ActorRef call = call(null, request);
final ActorRef self = self();
final Configuration runtime = configuration.subset("runtime-settings");
if (logger.isInfoEnabled()) {
logger.info("outboundToIms: from: " + from + ", to: " + to);
}
final String proxyUsername = (request.username() != null) ? request.username() : activeProxyUsername;
final String proxyPassword = (request.password() != null) ? request.password() : activeProxyPassword;
boolean isToWebRTC = false;
Registration toReg = findRegistration(to);
if (toReg != null) {
isToWebRTC = toReg.isWebRTC();
}
if (logger.isInfoEnabled()) {
logger.info("outboundToIms: isToWebRTC: " + isToWebRTC);
}
InitializeOutbound init = new InitializeOutbound(request.from(), from, to, proxyUsername, proxyPassword, request.timeout(),
request.isFromApi(), runtime.getString("api-version"), request.accountId(), request.type(), storage, isToWebRTC,
true, imsProxyAddress, imsProxyPort, request.mediaAttributes());
if (request.parentCallSid() != null) {
init.setParentCallSid(request.parentCallSid());
}
call.tell(init, self);
sender.tell(new CallManagerResponse<ActorRef>(call), self());
}
}
}
| 143,871 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ConferenceCenter.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/ConferenceCenter.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.telephony;
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 org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.patterns.Observe;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory;
import org.restcomm.connect.telephony.api.ConferenceCenterResponse;
import org.restcomm.connect.telephony.api.ConferenceStateChanged;
import org.restcomm.connect.telephony.api.CreateConference;
import org.restcomm.connect.telephony.api.DestroyConference;
import org.restcomm.connect.telephony.api.StartConference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (Amit Bhayani)
* @author [email protected] (Maria Farooq)
*/
public final class ConferenceCenter extends RestcommUntypedActor {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
private final MediaServerControllerFactory factory;
private final Map<String, ActorRef> conferences;
private final Map<String, List<ActorRef>> initializing;
private final DaoManager storage;
public ConferenceCenter(final MediaServerControllerFactory factory, final DaoManager storage) {
super();
this.factory = factory;
this.conferences = new HashMap<String, ActorRef>();
this.initializing = new HashMap<String, List<ActorRef>>();
this.storage = storage;
}
private ActorRef getConference(final String name) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
//Here Here we can pass Gateway where call is connected
return new Conference(name, factory, storage, getSelf());
}
});
return getContext().actorOf(props);
}
@Override
public void onReceive(final Object message) throws Exception {
if (logger.isInfoEnabled()) {
logger.info(" ********** ConferenceCenter " + self().path() + ", Processing Message: " + message.getClass().getName() + " isTerminated? "+self().isTerminated());
}
final Class<?> klass = message.getClass();
final ActorRef sender = sender();
if (CreateConference.class.equals(klass)) {
create(message, sender);
} else if (ConferenceStateChanged.class.equals(klass)) {
notify(message, sender);
} else if (DestroyConference.class.equals(klass)) {
destroy(message);
}
}
private void destroy(final Object message) {
final DestroyConference request = (DestroyConference) message;
final String name = request.name();
final ActorRef conference = conferences.remove(name);
final UntypedActorContext context = getContext();
if (conference != null) {
context.stop(conference);
}
}
private void notify(final Object message, final ActorRef sender) {
final ConferenceStateChanged update = (ConferenceStateChanged) message;
final String name = update.name();
final ActorRef self = self();
// Stop observing events from the conference room.
// sender.tell(new StopObserving(self), self);
// Figure out what happened.
ConferenceCenterResponse response = null;
if (isRunning(update.state())) {
// Only executes during a conference initialization
// Adds conference to collection if started successfully
if (!conferences.containsKey(name)) {
if(logger.isInfoEnabled()) {
logger.info("Conference " + name + " started successfully");
}
conferences.put(name, sender);
response = new ConferenceCenterResponse(sender);
}
} else if (ConferenceStateChanged.State.COMPLETED.equals(update.state())) {
// A conference completed with no errors
// Remove it from conference collection and stop the actor
if(logger.isInfoEnabled()) {
logger.info("Conference " + name + " completed without issues");
}
conferences.remove(update.name());
//stop sender(conference who sent this msg) bcz it was already removed from map in Stopping state
context().stop(sender);
} else if (ConferenceStateChanged.State.STOPPING.equals(update.state())) {
// A conference is in stopping state
// Remove it from conference collection
// https://github.com/RestComm/Restcomm-Connect/issues/2312
if(logger.isInfoEnabled()) {
logger.info("Conference " + name + " is going to stop, will remove it from available conferences.");
}
conferences.remove(update.name());
} else if (ConferenceStateChanged.State.FAILED.equals(update.state())) {
if (conferences.containsKey(name)) {
// A conference completed with errors
// Remove it from conference collection and stop the actor
if(logger.isInfoEnabled()) {
logger.info("Conference " + name + " completed with issues");
}
ActorRef conference = conferences.remove(update.name());
context().stop(conference);
} else {
// Failed to initialize a conference
// Warn voice interpreter conference initialization failed
if(logger.isInfoEnabled()) {
logger.info("Conference " + name + " failed to initialize");
}
final StringBuilder buffer = new StringBuilder();
buffer.append("The conference room ").append(name).append(" failed to initialize.");
final CreateConferenceException exception = new CreateConferenceException(buffer.toString());
response = new ConferenceCenterResponse(exception);
}
}
// Notify the observers if any
final List<ActorRef> observers = initializing.remove(name);
if (observers != null) {
for (final ActorRef observer : observers) {
observer.tell(response, self);
}
observers.clear();
}
}
private boolean isRunning(ConferenceStateChanged.State state) {
return ConferenceStateChanged.State.RUNNING_MODERATOR_ABSENT.equals(state)
|| ConferenceStateChanged.State.RUNNING_MODERATOR_PRESENT.equals(state);
}
private void create(final Object message, final ActorRef sender) {
final CreateConference request = (CreateConference) message;
final String name = request.name();
final ActorRef self = self();
// Check to see if the conference already exists.
ActorRef conference = conferences.get(name);
if(logger.isDebugEnabled()) {
logger.debug("ConferenceCenter conference: " + conference + " name: "+name);
}
if (conference != null && !conference.isTerminated()) {
sender.tell(new ConferenceCenterResponse(conference), self);
return;
}
// Check to see if it's already created but not initialized.
// If it is then just add it to the list of observers that will
// be notified when the conference room is ready.
List<ActorRef> observers = initializing.get(name);
if (observers != null) {
if(logger.isDebugEnabled()) {
logger.debug("ConferenceCenter this conference is already being initialize. sender will be notied when conference is successfuly started."+ " ConferenceCenter isTerminated? "+self().isTerminated());
}
observers.add(sender);
} else {
if(logger.isDebugEnabled()) {
logger.debug("ConferenceCenter this conference initialization started. sender will be notied when conference is successfuly started."+ " ConferenceCenter isTerminated? "+self().isTerminated());
}
observers = new ArrayList<ActorRef>();
observers.add(sender);
conference = getConference(name);
conference.tell(new Observe(self), self);
conference.tell(new StartConference(request.initialitingCallSid(), request.mediaAttributes()), self);
initializing.put(name, observers);
if(logger.isDebugEnabled()) {
logger.debug("Conference: "+ conference +" "+ " Conference isTerminated? "+conference.isTerminated()+ " ConferenceCenter isTerminated? "+self().isTerminated());
}
}
}
}
| 9,932 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Bridge.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/Bridge.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.telephony;
import akka.actor.ActorRef;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import jain.protocol.ip.mgcp.message.parms.ConnectionMode;
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 org.restcomm.connect.dao.entities.MediaAttributes;
import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory;
import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession;
import org.restcomm.connect.mscontrol.api.messages.JoinCall;
import org.restcomm.connect.mscontrol.api.messages.JoinComplete;
import org.restcomm.connect.mscontrol.api.messages.Leave;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged.MediaServerControllerState;
import org.restcomm.connect.mscontrol.api.messages.StartRecording;
import org.restcomm.connect.mscontrol.api.messages.Stop;
import org.restcomm.connect.telephony.api.BridgeStateChanged;
import org.restcomm.connect.telephony.api.BridgeStateChanged.BridgeState;
import org.restcomm.connect.telephony.api.JoinCalls;
import org.restcomm.connect.telephony.api.StartBridge;
import org.restcomm.connect.telephony.api.StopBridge;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Henrique Rosa ([email protected])
*
*/
public class Bridge extends RestcommUntypedActor {
private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this);
// Finite State Machine
private final FiniteStateMachine fsm;
private final State uninitialized;
private final State initializing;
private final State ready;
private final State bridging;
private final State halfBridged;
private final State bridged;
private final State stopping;
private final State failed;
private final State complete;
// Media Server Controller
private final ActorRef mscontroller;
// Call bridging
private ActorRef inboundCall;
private ActorRef outboundCall;
// Observer pattern
private final List<ActorRef> observers;
// Media
private final MediaAttributes mediaAttributes;
public Bridge(MediaServerControllerFactory factory, final MediaAttributes mediaAttributes) {
final ActorRef source = self();
// Media Server Controller
this.mscontroller = getContext().actorOf(factory.provideBridgeControllerProps());
// States for the FSM
this.uninitialized = new State("uninitialized", null, null);
this.initializing = new State("initializing", new Initializing(source), null);
this.ready = new State("ready", new Ready(source), null);
this.bridging = new State("bridging", new Bridging(source), null);
this.halfBridged = new State("half bridged", new HalfBridged(source), null);
this.bridged = new State("bridged", new Bridged(source), null);
this.stopping = new State("stopping", new Stopping(source), null);
this.failed = new State("failed", new Failed(source), null);
this.complete = new State("complete", new Complete(source), null);
// State transitions
final Set<Transition> transitions = new HashSet<Transition>();
transitions.add(new Transition(uninitialized, initializing));
transitions.add(new Transition(initializing, failed));
transitions.add(new Transition(initializing, ready));
transitions.add(new Transition(ready, bridging));
transitions.add(new Transition(ready, stopping));
transitions.add(new Transition(bridging, halfBridged));
transitions.add(new Transition(bridging, stopping));
transitions.add(new Transition(halfBridged, stopping));
transitions.add(new Transition(halfBridged, bridged));
transitions.add(new Transition(bridged, stopping));
transitions.add(new Transition(stopping, failed));
transitions.add(new Transition(stopping, complete));
// Finite State Machine
this.fsm = new FiniteStateMachine(uninitialized, transitions);
// Observer pattern
this.observers = new ArrayList<ActorRef>(3);
// Media
this.mediaAttributes = mediaAttributes;
}
private boolean is(final State state) {
return this.fsm.state().equals(state);
}
private void broadcast(final Object message) {
if (!this.observers.isEmpty()) {
final ActorRef self = self();
for (ActorRef observer : observers) {
observer.tell(message, self);
}
}
}
/*
* Events
*/
@Override
public void onReceive(Object message) throws Exception {
final Class<?> klass = message.getClass();
final ActorRef self = self();
final ActorRef sender = sender();
final State state = fsm.state();
if(logger.isInfoEnabled()) {
logger.info("********** Bridge " + self.path() + " State: \"" + state.toString());
logger.info("********** Bridge " + self.path() + " Processing: \"" + klass.getName() + " Sender: " + sender.path());
}
if (Observe.class.equals(klass)) {
onObserve((Observe) message, self, sender);
} else if (StopObserving.class.equals(klass)) {
onStopObserving((StopObserving) message, self, sender);
} else if (StartBridge.class.equals(klass)) {
onStartBridge((StartBridge) message, self, sender);
} else if (JoinCalls.class.equals(klass)) {
onJoinCalls((JoinCalls) message, self, sender);
} else if (JoinComplete.class.equals(klass)) {
onJoinComplete((JoinComplete) message, self, sender);
} else if (MediaServerControllerStateChanged.class.equals(klass)) {
onMediaServerControllerStateChanged((MediaServerControllerStateChanged) message, self, sender);
} else if (StopBridge.class.equals(klass)) {
onStopBridge((StopBridge) message, self, sender);
} else if (StartRecording.class.equals(klass)) {
onStartRecording((StartRecording) message, self, sender);
}
}
private void onObserve(Observe message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
synchronized (this.observers) {
this.observers.add(observer);
observer.tell(new Observing(self), self);
}
}
}
private void onStopObserving(StopObserving message, ActorRef self, ActorRef sender) {
final ActorRef observer = message.observer();
if (observer != null) {
this.observers.remove(observer);
}
}
private void onStartBridge(StartBridge message, ActorRef self, ActorRef sender) throws Exception {
if (is(uninitialized)) {
this.fsm.transition(message, initializing);
}
}
private void onJoinCalls(JoinCalls message, ActorRef self, ActorRef sender) throws Exception {
if (is(ready)) {
this.inboundCall = message.getInboundCall();
this.outboundCall = message.getOutboundCall();
fsm.transition(message, bridging);
}
}
private void onJoinComplete(JoinComplete message, ActorRef self, ActorRef sender) throws Exception {
if (is(bridging)) {
this.fsm.transition(message, halfBridged);
} else if (is(halfBridged)) {
this.fsm.transition(message, bridged);
}
}
private void onMediaServerControllerStateChanged(MediaServerControllerStateChanged message, ActorRef self, ActorRef sender)
throws Exception {
MediaServerControllerState state = message.getState();
switch (state) {
case ACTIVE:
if (is(initializing)) {
this.fsm.transition(message, ready);
}
break;
case INACTIVE:
if (is(stopping)) {
this.fsm.transition(message, complete);
}
break;
case FAILED:
if (is(initializing)) {
this.fsm.transition(message, failed);
}
break;
default:
// ignore unknown state
break;
}
}
private void onStopBridge(StopBridge message, ActorRef self, ActorRef sender) throws Exception {
if (is(ready) || is(bridging) || is(halfBridged) || is(bridged)) {
this.fsm.transition(message, stopping);
}
}
private void onStartRecording(StartRecording message, ActorRef self, ActorRef sender) throws Exception {
if (is(bridged)) {
// Forward message to MS Controller
this.mscontroller.tell(message, sender);
}
}
/*
* Actions
*/
private abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
private class Initializing extends AbstractAction {
public Initializing(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
// Start observing state changes in the MSController
final Observe observe = new Observe(super.source);
mscontroller.tell(observe, super.source);
// Initialize the MS Controller
final CreateMediaSession createMediaSession = new CreateMediaSession(mediaAttributes);
mscontroller.tell(createMediaSession, super.source);
}
}
private class Ready extends AbstractAction {
public Ready(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
final BridgeStateChanged notification = new BridgeStateChanged(BridgeStateChanged.BridgeState.READY);
broadcast(notification);
}
}
private class Bridging extends AbstractAction {
public Bridging(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
// Ask mscontroller to join inbound call
final JoinCall join = new JoinCall(inboundCall, ConnectionMode.SendRecv);
mscontroller.tell(join, super.source);
}
}
private class HalfBridged extends AbstractAction {
public HalfBridged(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
// Notify observers that inbound call has been bridged successfully
final BridgeStateChanged notification = new BridgeStateChanged(BridgeStateChanged.BridgeState.HALF_BRIDGED);
broadcast(notification);
// Ask mscontroller to join outbound call
final JoinCall join = new JoinCall(outboundCall, ConnectionMode.SendRecv);
mscontroller.tell(join, super.source);
}
}
private class Bridged extends AbstractAction {
public Bridged(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
final BridgeStateChanged notification = new BridgeStateChanged(BridgeStateChanged.BridgeState.BRIDGED);
broadcast(notification);
}
}
private class Stopping extends AbstractAction {
public Stopping(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
boolean liveCallModification = ((StopBridge)message).isLiveCallModification();
// Disconnect both call legs from the bridge
// NOTE: Null-check necessary in case bridge is stopped because
// of timeout and bridging process has not taken place.
if (!liveCallModification) {
if (logger.isInfoEnabled()) {
logger.info("Stopping the Bridge, will ask calls to leave the bridge");
}
if (inboundCall != null) {
inboundCall.tell(new Leave(), super.source);
inboundCall = null;
}
if (outboundCall != null) {
outboundCall.tell(new Leave(), super.source);
outboundCall = null;
}
} else {
if (logger.isInfoEnabled()) {
logger.info("Stopping the Bridge, will NOT ask calls to leave the bridge because liveCallModification: "+liveCallModification);
}
}
// Ask the MS Controller to stop
// This will stop any current media operations and clean media resources
mscontroller.tell(new Stop(), super.source);
}
}
private class Complete extends AbstractAction {
public Complete(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
final BridgeStateChanged notification = new BridgeStateChanged(BridgeState.INACTIVE);
broadcast(notification);
observers.clear();
}
}
private class Failed extends AbstractAction {
public Failed(ActorRef source) {
super(source);
}
@Override
public void execute(Object message) throws Exception {
final BridgeStateChanged notification = new BridgeStateChanged(BridgeState.FAILED);
broadcast(notification);
observers.clear();
}
}
}
| 15,310 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CreateConferenceException.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/CreateConferenceException.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.telephony;
/**
* @author [email protected] (Thomas Quintana)
*/
public final class CreateConferenceException extends Exception {
private static final long serialVersionUID = 1L;
public CreateConferenceException(final String message) {
super(message);
}
public CreateConferenceException(final Throwable cause) {
super(cause);
}
public CreateConferenceException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,340 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CallManagerProxy.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/CallManagerProxy.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.telephony;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.actor.UntypedActorFactory;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory;
import org.restcomm.connect.sms.SmsService;
import org.restcomm.connect.telephony.api.util.B2BUAHelper;
import org.restcomm.connect.ussd.telephony.UssdCallManager;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.sip.SipApplicationSession;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipServletContextEvent;
import javax.servlet.sip.SipServletListener;
import javax.servlet.sip.SipServletMessage;
import javax.servlet.sip.SipServletRequest;
import javax.servlet.sip.SipServletResponse;
import javax.servlet.sip.SipSession;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.io.IOException;
import javax.servlet.sip.SipApplicationSessionEvent;
import javax.servlet.sip.SipApplicationSessionListener;
/**
* @author [email protected] (Thomas Quintana)
* @author <a href="mailto:[email protected]">gvagenas</a>
*/
public final class CallManagerProxy extends SipServlet implements SipServletListener, SipApplicationSessionListener {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(CallManagerProxy.class);
private boolean sendTryingForInitalRequests = false;
private ActorSystem system;
private ActorRef manager;
private ActorRef ussdManager;
private ServletContext context;
private Configuration configuration;
public CallManagerProxy() {
super();
}
@Override
public void destroy() {
if (system != null) {
system.shutdown();
system.awaitTermination();
}
}
@Override
protected void doRequest(final SipServletRequest request) throws ServletException, IOException {
if (isUssdMessage(request)) {
ussdManager.tell(request, null);
} else {
if (request.isInitial() && sendTryingForInitalRequests) {
SipServletResponse resp = request.createResponse(Response.TRYING);
resp.send();
}
manager.tell(request, null);
}
}
@Override
protected void doResponse(final SipServletResponse response) throws ServletException, IOException {
if (response.getMethod().equals(Request.BYE) && response.getStatus() >= 200) {
SipSession sipSession = response.getSession();
SipApplicationSession sipApplicationSession = response.getApplicationSession();
if (sipSession.isValid()) {
sipSession.setInvalidateWhenReady(true);
}
if (sipApplicationSession.isValid()) {
sipApplicationSession.setInvalidateWhenReady(true);
}
return;
}
if (isUssdMessage(response)) {
ussdManager.tell(response, null);
} else {
manager.tell(response, null);
}
}
@Override
public void init(final ServletConfig config) throws ServletException {
super.init(config);
}
private ActorRef manager(final Configuration configuration, final ServletContext context,
final MediaServerControllerFactory msControllerfactory, final ActorRef conferences, final ActorRef bridges,
final ActorRef sms, final SipFactory factory, final DaoManager storage) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new CallManager(configuration, context, msControllerfactory, conferences, bridges, sms, factory, storage);
}
});
return system.actorOf(props);
}
private ActorRef ussdManager(final Configuration configuration, final ServletContext context, final SipFactory factory, final DaoManager storage) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new UssdCallManager(configuration, context, factory, storage);
}
});
return system.actorOf(props);
}
private ActorRef conferences(final MediaServerControllerFactory factory, final DaoManager storage) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new ConferenceCenter(factory, storage);
}
});
return system.actorOf(props);
}
private ActorRef bridges(final MediaServerControllerFactory factory) {
final Props props = new Props(new UntypedActorFactory() {
private static final long serialVersionUID = 1L;
@Override
public UntypedActor create() throws Exception {
return new BridgeManager(factory);
}
});
return system.actorOf(props);
}
private boolean isUssdMessage(SipServletMessage message) {
Boolean isUssd = false;
String contentType = null;
try {
contentType = message.getContentType();
} catch (Exception e) {
}
if (contentType != null) {
isUssd = contentType.equalsIgnoreCase("application/vnd.3gpp.ussd+xml");
} else {
if (message.getApplicationSession().getAttribute("UssdCall") != null) {
isUssd = true;
}
}
return isUssd;
}
@Override
public void servletInitialized(SipServletContextEvent event) {
if (event.getSipServlet().getClass().equals(CallManagerProxy.class)) {
if(logger.isInfoEnabled()) {
logger.info("CallManagerProxy sip servlet initialized. Will proceed to create CallManager and UssdManager");
}
context = event.getServletContext();
configuration = (Configuration) context.getAttribute(Configuration.class.getName());
sendTryingForInitalRequests = Boolean.parseBoolean(configuration.subset("runtime-settings").getString("send-trying-for-initial-requests", "false"));
system = (ActorSystem) context.getAttribute(ActorSystem.class.getName());
final DaoManager storage = (DaoManager) context.getAttribute(DaoManager.class.getName());
final MediaServerControllerFactory mscontrolFactory = (MediaServerControllerFactory) context
.getAttribute(MediaServerControllerFactory.class.getName());
// Create the call manager.
final SipFactory factory = (SipFactory) context.getAttribute(SIP_FACTORY);
final ActorRef conferences = conferences(mscontrolFactory, storage);
final ActorRef bridges = bridges(mscontrolFactory);
final ActorRef sms = (ActorRef) context.getAttribute(SmsService.class.getName());
manager = manager(configuration, context, mscontrolFactory, conferences, bridges, sms, factory, storage);
ussdManager = ussdManager(configuration, context, factory, storage);
context.setAttribute(CallManager.class.getName(), manager);
context.setAttribute(UssdCallManager.class.getName(), ussdManager);
}
}
@Override
public void sessionCreated(SipApplicationSessionEvent sase) {
}
@Override
public void sessionDestroyed(SipApplicationSessionEvent sase) {
}
/**
* extension time added on expiration.
*/
private static final int EXPIRATION_GRACE_PERIOD = 1;
@Override
public void sessionExpired(SipApplicationSessionEvent sase) {
//check attribute signlling Akka actor completed timeout processing
//if att is present, let the sesion just expire
logger.debug("Session expired");
if (sase.getApplicationSession().getAttribute(B2BUAHelper.B2BUA_CALL) != null && sase.getApplicationSession().getAttribute(CallManager.TIMEOUT_ATT) == null) {
logger.debug("Session expired still not processed");
//extend expiration a bit,to let sessions be properly disconnected
sase.getApplicationSession().setExpires(EXPIRATION_GRACE_PERIOD);
manager.tell(sase, manager);
}
}
@Override
public void sessionReadyToInvalidate(SipApplicationSessionEvent sase) {
}
}
| 9,769 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
TooManyParticipantsException.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony/src/main/java/org/restcomm/connect/telephony/TooManyParticipantsException.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.telephony;
/**
* @author [email protected] (Thomas Quintana)
*/
public final class TooManyParticipantsException extends Exception {
private static final long serialVersionUID = 1L;
public TooManyParticipantsException() {
super();
}
public TooManyParticipantsException(final String message) {
super(message);
}
public TooManyParticipantsException(final Throwable cause) {
super(cause);
}
public TooManyParticipantsException(final String message, final Throwable cause) {
super(message, cause);
}
}
| 1,420 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.