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
CallControlHelper.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.telephony.api/src/main/java/org/restcomm/connect/telephony/api/util/CallControlHelper.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.api.util; import static javax.servlet.sip.SipServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED; import static org.restcomm.connect.commons.util.HexadecimalUtils.toHex; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipServletResponse; import javax.servlet.sip.SipURI; import org.apache.log4j.Logger; import org.restcomm.connect.dao.ClientsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Client; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.DigestAuthentication; /** * * Helper class for managing SIP interactions * * * @author [email protected] * */ public class CallControlHelper { private static Logger logger = Logger.getLogger(CallControlHelper.class); public static boolean permitted(final String authorization, final String method, DaoManager daoManager, final Sid organizationSid) { final Map<String, String> map = authHeaderToMap(authorization); final String user = map.get("username"); String authHeaderAlgorithm = map.get("algorithm"); final String realm = map.get("realm"); final String uri = map.get("uri"); final String nonce = map.get("nonce"); final String nc = map.get("nc"); final String cnonce = map.get("cnonce"); final String qop = map.get("qop"); final String response = map.get("response"); final ClientsDao clients = daoManager.getClientsDao(); final Client client = clients.getClient(user, organizationSid); if (client != null && daoManager.getAccountsDao().getAccount(client.getAccountSid()).getStatus() != Account.Status.ACTIVE) { return false; } if (client != null && Client.ENABLED == client.getStatus()) { final String password = client.getPassword(); final String clientPasswordAlgorithm = client.getPasswordAlgorithm(); if (authHeaderAlgorithm == null) { authHeaderAlgorithm = clientPasswordAlgorithm; } final String result = DigestAuthentication.response(authHeaderAlgorithm, user, realm, password,clientPasswordAlgorithm, nonce, nc, cnonce, method, uri, null, qop); if (logger.isDebugEnabled()) { String msg = String.format("Provided response [%s], generated response [%s]", response, result); logger.debug(msg); } return result.equals(response); } else { if (logger.isDebugEnabled()) { String msg = String.format("Authorization check failed, [if(client!=null) evaluates %s] or [if(client.getStatus()==Client.ENABLED) evaluates %s]", client!=null, client != null ? Client.ENABLED == client.getStatus() : "client is null"); logger.debug(msg); } return false; } } /** * Check if a client is authenticated. If so, return true. Otherwise request authentication and return false; * @param request * @param storage * @param organizationSid * @return * @throws IOException */ public static boolean checkAuthentication(SipServletRequest request, DaoManager storage, Sid organizationSid) throws IOException { // Make sure we force clients to authenticate. final String authorization = request.getHeader("Proxy-Authorization"); final String method = request.getMethod(); if (authorization == null || !CallControlHelper.permitted(authorization, method, storage, organizationSid)) { if (logger.isDebugEnabled()) { String msg = String.format("Either authorization header is null [if(authorization==null) evaluates %s], or CallControlHelper.permitted() method failed, will send \"407 Proxy Authentication required\"", authorization==null); logger.debug(msg); } authenticate(request, storage.getOrganizationsDao().getOrganization(organizationSid).getDomainName()); return false; } else { return true; } } static void authenticate(final SipServletRequest request, String realm) throws IOException { final SipServletResponse response = request.createResponse(SC_PROXY_AUTHENTICATION_REQUIRED); final String nonce = nonce(); String algorithm = RestcommConfiguration.getInstance().getMain().getClientAlgorithm(); String qop = RestcommConfiguration.getInstance().getMain().getClientQOP(); final String header = header(nonce, realm, "Digest", algorithm, qop); response.addHeader("Proxy-Authenticate", header); response.send(); } private static Map<String, String> authHeaderToMap(final String header) { final Map<String, String> map = new HashMap<String, String>(); final int endOfScheme = header.indexOf(" "); map.put("scheme", header.substring(0, endOfScheme).trim()); final String[] tokens = header.substring(endOfScheme + 1).split(","); for (final String token : tokens) { final String[] values = token.trim().split("=",2); //Issue #935, split only for first occurrence of "=" map.put(values[0].toLowerCase(), values[1].replace("\"", "")); } return map; } static String nonce() { final byte[] uuid = UUID.randomUUID().toString().getBytes(); final char[] hex = toHex(uuid); return new String(hex).substring(0, 31); } static String header(final String nonce, final String realm, final String scheme, String algo, String qop) { final StringBuilder buffer = new StringBuilder(); buffer.append(scheme).append(" "); if(!algo.isEmpty()){ //NB: we dont support "algorithm-sess" yet buffer.append("algorithm=\"").append(algo).append("\", "); buffer.append("qop=\"").append(qop).append("\", "); } buffer.append("realm=\"").append(realm).append("\", "); buffer.append("nonce=\"").append(nonce).append("\""); return buffer.toString(); } /** * * Extracts the User SIP identity from a request header * * @param request * @param useTo Whether or not to use the To field in the SIP header * @return */ public static String getUserSipId(final SipServletRequest request, boolean useTo) { final SipURI toUri; final String toUser; if (useTo) { toUri = (SipURI) request.getTo().getURI(); toUser = toUri.getUser(); } else { toUri = (SipURI) request.getRequestURI(); toUser = toUri.getUser(); } return toUser; } }
7,820
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ExtensionRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/ExtensionRequest.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.api; public class ExtensionRequest implements IExtensionRequest{ private boolean allowed = true; private String accountSid; public ExtensionRequest() { this("", true); } public ExtensionRequest(String accountSid, boolean allowed) { this.accountSid = accountSid; this.allowed = allowed; } /** * IExtensionRequest * @return get accountSid */ @Override public String getAccountSid() { return this.accountSid; } /** * IExtensionRequest * @return is allowed */ @Override public boolean isAllowed() { return this.allowed; } /** * IExtensionRequest * @param is allowed */ @Override public void setAllowed(boolean allowed) { this.allowed = allowed; } }
1,772
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ExtensionConfiguration.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/ExtensionConfiguration.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.api; import org.joda.time.DateTime; import org.restcomm.connect.commons.dao.Sid; /** * Created by gvagenas on 12/10/2016. */ public class ExtensionConfiguration { public enum configurationType { XML, JSON } private Sid sid; private String extensionName; private boolean enabled; private Object configurationData; private configurationType configurationType; private DateTime dateCreated; private DateTime dateUpdated; public ExtensionConfiguration(Sid sid, String extensionName, boolean enabled, Object configurationData, configurationType configurationType, DateTime dateCreated, DateTime dateUpdated) { this.sid = sid; this.extensionName = extensionName; this.enabled = enabled; this.configurationData = configurationData; this.configurationType = configurationType; this.dateCreated = dateCreated; this.dateUpdated = dateUpdated; } public ExtensionConfiguration(Sid sid, String extensionName, boolean enabled, Object configurationData, configurationType configurationType, DateTime dateCreated) { this(sid, extensionName, enabled, configurationData, configurationType, dateCreated, DateTime.now()); } public Sid getSid() { return sid; } public String getExtensionName() { return extensionName; } public boolean isEnabled() { return enabled; } public Object getConfigurationData() { return configurationData; } public configurationType getConfigurationType() { return configurationType; } public DateTime getDateCreated() { return dateCreated; } public DateTime getDateUpdated() { return dateUpdated; } public void setDateUpdated(DateTime dateUpdated) { this.dateUpdated = dateUpdated; } public void setConfigurationData(Object configurationData, configurationType configurationType) { this.configurationData = configurationData; this.configurationType = configurationType; this.dateUpdated = DateTime.now(); } }
3,031
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IExtensionCreateSmsSessionRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/IExtensionCreateSmsSessionRequest.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.api; import org.apache.commons.configuration.Configuration; public interface IExtensionCreateSmsSessionRequest extends IExtensionRequest { /** * FIXME: potentially we will change this to be specific properties * rather than a whole Config object * @param set Configuration object */ void setConfiguration(Configuration configuration); /** * FIXME: potentially we will change this to be specific properties * rather than a whole Config object * @return the Configuration object */ Configuration getConfiguration(); }
1,532
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommExtensionGeneric.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/RestcommExtensionGeneric.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.api; import javax.servlet.ServletContext; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public interface RestcommExtensionGeneric { /** * Use this method to initialize the Extension */ void init(ServletContext context); /** * Check if extensions is enabled * @return */ boolean isEnabled(); /** * Method that will be executed BEFORE the process of an Incoming session * Implement this method so you will be able to check the Incoming session * and either block/allow or modify the session before Restcomm process it * @return ExtensionResponse see ExtensionResponse */ ExtensionResponse preInboundAction(IExtensionRequest extensionRequest); /** * Method that will be executed AFTER the process of an Incoming session * Implement this method so you will be able to check the Incoming session * and either block or allow or modify the session after Restcomm process it * @return ExtensionResponse see ExtensionResponse */ ExtensionResponse postInboundAction(IExtensionRequest extensionRequest); /** * Method that will be executed before the process of an Outbound session * Implement this method so you will be able to check the Outbound session * and either block/allow it or modify the session before Restcomm process it * @return ExtensionResponse see ExtensionResponse */ ExtensionResponse preOutboundAction(IExtensionRequest extensionRequest); /** * Method that will be executed AFTER the process of an Outbound session * Implement this method so you will be able to check the Outgoing session * and either block or allow or modify the session after Restcomm process it * @return ExtensionResponse see ExtensionResponse */ ExtensionResponse postOutboundAction(IExtensionRequest extensionRequest); /** * Method that will be executed before the process of an API action, such as DID purchase (but after security checks) * @return ExtensionResponse see ExtensionResponse */ ExtensionResponse preApiAction(ApiRequest apiRequest); /** * Method that will be executed after the process of an API action, such as DID purchase * @return */ ExtensionResponse postApiAction(ApiRequest apiRequest); /** * Extension name getter * @return String name of Extension */ String getName(); /** * Extension version getter * @return String version of Extension */ String getVersion(); }
3,522
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ExtensionResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/ExtensionResponse.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.api; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public class ExtensionResponse { private Object object; private boolean allowed = true; public ExtensionResponse() {} public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public boolean isAllowed() { return allowed; } public void setAllowed(boolean allowed) { this.allowed = allowed; } }
1,458
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ExtensionType.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/ExtensionType.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.api; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public enum ExtensionType { CallManager, SmsService, UssdCallManager,RestApi, FeatureAccessControl }
1,135
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommExtension.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/RestcommExtension.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.api; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ @Retention(RetentionPolicy.RUNTIME) @Target(value = {ElementType.TYPE}) public @interface RestcommExtension { String author(); String version() default "1.0.0-SNAPSHOT"; ExtensionType[] type(); }
1,404
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConfigurationException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/ConfigurationException.java
package org.restcomm.connect.extension.api; /** * Exception for configuration related issues * Created by gvagenas on 30/10/2016. */ public class ConfigurationException extends Exception { public ConfigurationException(String message) { super(message); } }
277
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IExtensionCreateCallRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/IExtensionCreateCallRequest.java
package org.restcomm.connect.extension.api; import java.util.ArrayList; import java.util.Map; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.telephony.CreateCallType; public interface IExtensionCreateCallRequest extends IExtensionRequest { /** * @return the from address */ String getFrom(); /** * @return the to address */ String getTo(); /** * @return the accountId */ Sid getAccountId(); /** * @return boolean if is from EP */ boolean isFromApi(); /** * @return boolean if this is a child call */ boolean isParentCallSidExists(); /** * @return the CreateCallType */ CreateCallType getType(); /** * @return the outboundProxy */ String getOutboundProxy(); /** * @param outboundProxy the outboundProxy to set */ void setOutboundProxy(String outboundProxy); /** * @return the outboundProxyUsername */ String getOutboundProxyUsername(); /** * @param outboundProxyUsername the outboundProxyUsername to set */ void setOutboundProxyUsername(String outboundProxyUsername); /** * @return the outboundProxyPassword */ String getOutboundProxyPassword(); /** * @param outboundProxyPassword the outboundProxyPassword to set */ void setOutboundProxyPassword(String outboundProxyPassword); /** * @return the outboundProxyHeaders */ Map<String,ArrayList<String>> getOutboundProxyHeaders(); /** * @param outboundProxyHeaders the outboundProxyHeaders to set */ void setOutboundProxyHeaders(Map<String,ArrayList<String>> outboundProxyHeaders); /** * @return the Request URI */ String getRequestURI(); }
1,829
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommExtensionException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/RestcommExtensionException.java
package org.restcomm.connect.extension.api; /** * Created by gvagenas on 03/11/2016. */ public class RestcommExtensionException extends Exception { public RestcommExtensionException(String message) { super(message); } }
239
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IExtensionFeatureAccessRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/IExtensionFeatureAccessRequest.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.api; import org.restcomm.connect.commons.dao.Sid; public interface IExtensionFeatureAccessRequest extends IExtensionRequest{ void setAccountSid (Sid accountSid); String getDestinationNumber(); void setDestinationNumber(String destinationNumber); }
1,224
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApiRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/ApiRequest.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.api; import javax.ws.rs.core.MultivaluedMap; /** * Created by gvagenas on 10/10/2016. */ public class ApiRequest { public static enum Type { AVAILABLEPHONENUMBER,INCOMINGPHONENUMBER, CREATE_SUBACCOUNT }; final String requestedAccountSid; final MultivaluedMap<String, String> data; final Type type; public ApiRequest(final String requestedAccountSid, final MultivaluedMap<String, String> data, final Type type) { this.requestedAccountSid = requestedAccountSid; this.data = data; this.type = type; } public MultivaluedMap<String, String> getData() { return data; } public String getRequestedAccountSid() { return requestedAccountSid; } public Type getType() { return type; } }
1,653
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IExtensionRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.extension.api/src/main/java/org/restcomm/connect/extension/api/IExtensionRequest.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.api; public interface IExtensionRequest { /** * @return the accountId as String * FIXME: should this be at this level? */ String getAccountSid(); /** * @return whether request should proceed */ boolean isAllowed(); /** * @param set to allow/restrict request */ void setAllowed(boolean allowed); }
1,317
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Jsr309ControllerFactory.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.jsr309/src/main/java/org/restcomm/connect/mscontrol/jsr309/Jsr309ControllerFactory.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.jsr309; import akka.actor.Actor; import akka.actor.Props; import akka.actor.UntypedActorFactory; import org.apache.log4j.Logger; import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory; import org.restcomm.connect.mscontrol.api.MediaServerInfo; import javax.media.mscontrol.MsControlFactory; /** * @author Henrique Rosa ([email protected]) * */ public class Jsr309ControllerFactory implements MediaServerControllerFactory { private static Logger logger = Logger.getLogger(Jsr309ControllerFactory.class); // JSR-309 private final MsControlFactory msControlFactory; // Factories private final CallControllerFactory callControllerFactory; private final ConferenceControllerFactory conferenceControllerFactory; private final BridgeControllerFactory bridgeControllerFactory; // Media Server Info private final MediaServerInfo mediaServerInfo; public Jsr309ControllerFactory(MediaServerInfo mediaServerInfo, MsControlFactory msControlFactory) { // Factories this.msControlFactory = msControlFactory; this.callControllerFactory = new CallControllerFactory(); this.conferenceControllerFactory = new ConferenceControllerFactory(); this.bridgeControllerFactory = new BridgeControllerFactory(); // Media Server Info this.mediaServerInfo = mediaServerInfo; } @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 = 8689899689896436910L; @Override public Actor create() throws Exception { if (msControlFactory == null) { throw new IllegalStateException("No media server control factory has been set."); } return new Jsr309CallController(msControlFactory, mediaServerInfo); } } private final class ConferenceControllerFactory implements UntypedActorFactory { private static final long serialVersionUID = -4095666710038438897L; @Override public Actor create() throws Exception { if (msControlFactory == null) { throw new IllegalStateException("No media server control factory has been set."); } return new Jsr309ConferenceController(msControlFactory, mediaServerInfo); } } private final class BridgeControllerFactory implements UntypedActorFactory { private static final long serialVersionUID = -4095666710038438897L; @Override public Actor create() throws Exception { if (msControlFactory == null) { throw new IllegalStateException("No media server control factory has been set."); } return new Jsr309BridgeController(msControlFactory, mediaServerInfo); } } }
4,178
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Jsr309ConferenceController.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.jsr309/src/main/java/org/restcomm/connect/mscontrol/jsr309/Jsr309ConferenceController.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.jsr309; import java.io.Serializable; import java.net.URI; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.media.mscontrol.EventType; import javax.media.mscontrol.MediaEvent; import javax.media.mscontrol.MediaEventListener; import javax.media.mscontrol.MediaSession; import javax.media.mscontrol.MsControlException; import javax.media.mscontrol.MsControlFactory; import javax.media.mscontrol.Parameters; import javax.media.mscontrol.join.Joinable.Direction; import javax.media.mscontrol.mediagroup.MediaGroup; import javax.media.mscontrol.mediagroup.Player; import javax.media.mscontrol.mediagroup.PlayerEvent; import javax.media.mscontrol.mixer.MediaMixer; import javax.media.mscontrol.resource.AllocationEvent; import javax.media.mscontrol.resource.AllocationEventListener; import javax.media.mscontrol.resource.RTC; import org.mobicents.servlet.restcomm.mscontrol.messages.MediaServerConferenceControllerStateChanged; 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.dao.entities.MediaAttributes; import org.restcomm.connect.mscontrol.api.MediaServerController; import org.restcomm.connect.mscontrol.api.MediaServerInfo; import org.restcomm.connect.mscontrol.api.exceptions.MediaServerControllerException; import org.restcomm.connect.mscontrol.api.messages.CreateMediaSession; import org.restcomm.connect.mscontrol.api.messages.JoinCall; import org.restcomm.connect.mscontrol.api.messages.JoinConference; import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerError; import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged.MediaServerControllerState; import org.restcomm.connect.mscontrol.api.messages.Play; import org.restcomm.connect.mscontrol.api.messages.Stop; import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; /** * @author Henrique Rosa ([email protected]) * */ public class Jsr309ConferenceController extends MediaServerController { // Logging private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // Finite State Machine private final FiniteStateMachine fsm; // Finite states private final State uninitialized; private final State initializing; private final State active; private final State inactive; private final State failed; // Conference runtime stuff private ActorRef conference; // JSR-309 runtime stuff private final MsControlFactory msControlFactory; private final MediaServerInfo mediaServerInfo; private MediaSession mediaSession; private MediaGroup mediaGroup; private MediaMixer mediaMixer; private final PlayerListener playerListener; private final MixerAllocationListener mixerAllocationListener; // Media Operations private Boolean playing; // Observers private final List<ActorRef> observers; public Jsr309ConferenceController(MsControlFactory msControlFactory, MediaServerInfo mediaServerInfo) { super(); final ActorRef source = self(); // JSR-309 runtime stuff this.msControlFactory = msControlFactory; this.mediaServerInfo = mediaServerInfo; this.playerListener = new PlayerListener(); this.mixerAllocationListener = new MixerAllocationListener(); // Media Operations this.playing = Boolean.FALSE; // Initialize the states for the FSM this.uninitialized = new State("uninitialized", null); this.initializing = new State("initializing", new Initializing(source)); this.active = new State("active", new Active(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(uninitialized, initializing)); transitions.add(new Transition(initializing, failed)); transitions.add(new Transition(initializing, active)); transitions.add(new Transition(initializing, inactive)); transitions.add(new Transition(active, inactive)); // Finite state machine this.fsm = new FiniteStateMachine(this.uninitialized, transitions); // Observers this.observers = new ArrayList<ActorRef>(); } 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 stopMediaOperations() throws MsControlException { // Stop ongoing recording if (playing) { mediaGroup.getPlayer().stop(true); this.playing = Boolean.FALSE; } } private void cleanMediaResources() { // Release media resources mediaSession.release(); mediaSession = null; mediaGroup = null; mediaMixer = null; } /* * JSR-309 - EVENT LISTENERS */ private abstract class MediaListener<T extends MediaEvent<?>> implements MediaEventListener<T>, Serializable { private static final long serialVersionUID = 4712964810787577487L; protected ActorRef remote; public void setRemote(ActorRef sender) { this.remote = sender; } } private final class PlayerListener extends MediaListener<PlayerEvent> { private static final long serialVersionUID = 391225908543565230L; @Override public void onEvent(PlayerEvent event) { EventType eventType = event.getEventType(); if(logger.isInfoEnabled()) { logger.info("********** Conference Controller Current State: \"" + fsm.state().toString() + "\""); logger.info("********** Conference Controller Processing Event: \"PlayerEvent\" (type = " + eventType + ")"); } if (PlayerEvent.PLAY_COMPLETED.equals(eventType)) { MediaGroupResponse<String> response; if (event.isSuccessful()) { response = new MediaGroupResponse<String>(eventType.toString()); } else { String reason = event.getErrorText(); MediaServerControllerException error = new MediaServerControllerException(reason); response = new MediaGroupResponse<String>(error, reason); } playing = Boolean.FALSE; super.remote.tell(response, self()); } } } private class MixerAllocationListener implements AllocationEventListener, Serializable { private static final long serialVersionUID = 6579306945384115627L; @Override public void onEvent(AllocationEvent event) { EventType eventType = event.getEventType(); if(logger.isInfoEnabled()) { logger.info("********** Conference Controller Current State: \"" + fsm.state().toString() + "\""); logger.info("********** Conference Controller Processing Event: \"AllocationEventListener - Mixer\" (type = " + eventType + ")"); } try { if (AllocationEvent.ALLOCATION_CONFIRMED.equals(eventType)) { // No need to be notified anymore mediaMixer.removeListener(this); // join the media group to the mixer try { mediaGroup.join(Direction.DUPLEX, mediaMixer); } catch (MsControlException e) { fsm.transition(e, failed); } // Conference room has been properly activated and is now ready to receive connections fsm.transition(event, active); } else if (AllocationEvent.IRRECOVERABLE_FAILURE.equals(eventType)) { // Failed to activate media session fsm.transition(event, failed); } } catch (TransitionFailedException | TransitionNotFoundException | TransitionRollbackException e) { logger.error(e.getMessage(), e); } } } /* * 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("********** Conference Controller Current State: \"" + state.toString()); logger.info("********** Conference Controller Processing Message: \"" + klass.getName() + " sender : " + sender.getClass()); } 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 (Stop.class.equals(klass)) { onStop((Stop) message, self, sender); } else if (StopMediaGroup.class.equals(klass)) { onStopMediaGroup((StopMediaGroup) message, self, sender); } else if (JoinCall.class.equals(klass)) { onJoinCall((JoinCall) message, self, sender); } else if (Play.class.equals(klass)) { onPlay((Play) message, self, sender); } } private void onObserve(Observe message, ActorRef self, ActorRef sender) throws Exception { 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) throws Exception { final ActorRef observer = message.observer(); if (observer != null) { this.observers.remove(observer); } else { this.observers.clear(); } } private void onCreateMediaSession(CreateMediaSession message, ActorRef self, ActorRef sender) throws Exception { if (is(uninitialized)) { this.conference = sender; fsm.transition(message, initializing); } } private void onStop(Stop message, ActorRef self, ActorRef sender) throws Exception { if (is(initializing) || is(active)) { this.fsm.transition(message, inactive); } } private void onStopMediaGroup(StopMediaGroup message, ActorRef self, ActorRef sender) { if (is(active)) { try { if (this.playing) { this.mediaGroup.getPlayer().stop(true); this.playing = Boolean.FALSE; } } catch (MsControlException e) { conference.tell(new MediaServerControllerError(e), self); } } } private void onJoinCall(JoinCall message, ActorRef self, ActorRef sender) { if (is(active)) { // Tell call to join conference by passing reference of the media mixer final JoinConference join = new JoinConference(this.mediaMixer, message.getConnectionMode(), message.getSid(), message.mediaAttributes()); message.getCall().tell(join, sender); } } private void onPlay(Play message, ActorRef self, ActorRef sender) { if (is(active)) { try { List<URI> uris = message.uris(); Parameters params = this.mediaGroup.createParameters(); int repeatCount = message.iterations() <= 0 ? Player.FOREVER : message.iterations() - 1; params.put(Player.REPEAT_COUNT, repeatCount); this.playerListener.setRemote(sender); this.mediaGroup.getPlayer().play(uris.toArray(new URI[uris.size()]), RTC.NO_RTC, params); this.playing = Boolean.TRUE; } catch (MsControlException e) { logger.error("Play failed: " + e.getMessage()); this.playing = Boolean.FALSE; final MediaGroupResponse<String> response = new MediaGroupResponse<String>(e); broadcast(response); } } } /* * ACTIONS */ private final class Initializing extends AbstractAction { public Initializing(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { try { CreateMediaSession msg = (CreateMediaSession) message; MediaAttributes mediaAttributes = msg.mediaAttributes(); // Create media session mediaSession = msControlFactory.createMediaSession(); // Create the media group with recording capabilities mediaGroup = mediaSession.createMediaGroup(MediaGroup.PLAYER_RECORDER_SIGNALDETECTOR); mediaGroup.getPlayer().addListener(playerListener); if (!MediaAttributes.MediaType.AUDIO_ONLY.equals(mediaAttributes.getMediaType())) { // video only or audio and video (video only is controlled by codec policy) configureVideoMediaSession(mediaAttributes); Parameters mixerParams = createMixerParams(); mediaMixer = mediaSession.createMediaMixer(MediaMixer.AUDIO_VIDEO, mixerParams); } else { // audio only Parameters mixerParams = createMixerParams(); mediaMixer = mediaSession.createMediaMixer(MediaMixer.AUDIO, mixerParams); } mediaMixer.addListener(mixerAllocationListener); mediaMixer.confirm(); // Wait for event confirmation before sending response to the conference } catch (MsControlException e) { // Move to a failed state, cleaning all resources and closing media session fsm.transition(e, failed); } } private void configureVideoMediaSession(final MediaAttributes mediaAttributes) { // mode configuration if (MediaAttributes.VideoMode.SFU.equals(mediaAttributes.getVideoMode())) { // sfu not fully supported yet, waiting for next jsr309 connector release, using default mcu // mediaSession.setAttribute("mediaMixerMode", mediaAttributes.getVideoMode().toString()); } // resolution configuration mediaSession.setAttribute("CONFERENCE_VIDEO_SIZE", mediaAttributes.getVideoResolution().toString()); // layout configuration mediaSession.setAttribute("REGION", mediaAttributes.getVideoLayout().toString()); } private Parameters createMixerParams() { Parameters mixerParams = mediaSession.createParameters(); mixerParams.put(MediaMixer.MAX_PORTS, 900); return mixerParams; } } private final class Active extends AbstractAction { public Active(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { broadcast(new MediaServerConferenceControllerStateChanged(MediaServerControllerState.ACTIVE, null)); } } private final class Inactive extends AbstractAction { public Inactive(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { try { stopMediaOperations(); } catch (MsControlException e) { logger.error(e, "Could not stop ongoing media operations in an elegant manner"); } cleanMediaResources(); // Broadcast state changed broadcast(new MediaServerConferenceControllerStateChanged(MediaServerControllerState.INACTIVE, null)); // Clear observers observers.clear(); // Terminate actor getContext().stop(super.source); } } private final class Failed extends AbstractAction { public Failed(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Clean resources cleanMediaResources(); // Broadcast state changed broadcast(new MediaServerConferenceControllerStateChanged(MediaServerControllerState.FAILED, null)); // Clear observers observers.clear(); // Terminate actor getContext().stop(super.source); } } }
19,000
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Jsr309BridgeController.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.jsr309/src/main/java/org/restcomm/connect/mscontrol/jsr309/Jsr309BridgeController.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.jsr309; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import org.apache.commons.configuration.Configuration; 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.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.mscontrol.api.MediaServerController; import org.restcomm.connect.mscontrol.api.MediaServerInfo; import org.restcomm.connect.mscontrol.api.exceptions.MediaServerControllerException; 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.MediaServerControllerError; 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 javax.media.mscontrol.EventType; import javax.media.mscontrol.MediaEvent; import javax.media.mscontrol.MediaEventListener; import javax.media.mscontrol.MediaSession; import javax.media.mscontrol.MsControlException; import javax.media.mscontrol.MsControlFactory; import javax.media.mscontrol.Parameters; import javax.media.mscontrol.join.Joinable.Direction; import javax.media.mscontrol.mediagroup.MediaGroup; import javax.media.mscontrol.mediagroup.Recorder; import javax.media.mscontrol.mediagroup.RecorderEvent; import javax.media.mscontrol.mediagroup.SpeechDetectorConstants; import javax.media.mscontrol.mediagroup.signals.SignalDetector; import javax.media.mscontrol.mixer.MediaMixer; import javax.media.mscontrol.resource.AllocationEvent; import javax.media.mscontrol.resource.AllocationEventListener; import javax.media.mscontrol.resource.RTC; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.io.Serializable; 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]) * */ public class Jsr309BridgeController 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 initializing; private final State active; private final State inactive; private final State failed; // Telephony actors private ActorRef bridge; // JSR-309 components private final MsControlFactory msControlFactory; private final MediaServerInfo mediaServerInfo; private MediaSession mediaSession; private MediaGroup mediaGroup; private MediaMixer mediaMixer; private final RecorderListener recorderListener; private final MixerAllocationListener mixerAllocationListener; // Media Operations private Boolean recording; private StartRecording recordingRequest; // Observers private final List<ActorRef> observers; public Jsr309BridgeController(MsControlFactory msControlFactory, MediaServerInfo mediaServerInfo) { super(); final ActorRef source = self(); // JSR-309 resources this.msControlFactory = msControlFactory; this.mediaServerInfo = mediaServerInfo; this.recorderListener = new RecorderListener(); this.mixerAllocationListener = new MixerAllocationListener(); // Media Operations this.recording = Boolean.FALSE; // States for the FSM this.uninitialized = new State("uninitialized", null); this.initializing = new State("initializing", new Initializing(source)); this.active = new State("active", new Active(source)); this.inactive = new State("inactive", new Inactive(source)); this.failed = new State("failed", new Failed(source)); // Finite state machine final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(uninitialized, initializing)); transitions.add(new Transition(initializing, failed)); transitions.add(new Transition(initializing, active)); transitions.add(new Transition(initializing, inactive)); transitions.add(new Transition(active, inactive)); this.fsm = new FiniteStateMachine(this.uninitialized, transitions); // 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 stopMediaOperations() throws MsControlException { // Stop ongoing recording if (recording) { mediaGroup.getRecorder().stop(); } } private void cleanMediaResources() { // Release media resources mediaSession.release(); mediaSession = null; mediaGroup = null; mediaMixer = null; } /* * JSR-309 - EVENT LISTENERS */ private abstract class MediaListener<T extends MediaEvent<?>> implements MediaEventListener<T>, Serializable { private static final long serialVersionUID = 4712964810787577487L; protected ActorRef remote; public void setRemote(ActorRef sender) { this.remote = sender; } } private final class RecorderListener extends MediaListener<RecorderEvent> { private static final long serialVersionUID = 2145317407008648018L; private String endOnKey = ""; public void setEndOnKey(String endOnKey) { this.endOnKey = endOnKey; } @Override public void onEvent(RecorderEvent event) { EventType eventType = event.getEventType(); if(logger.isInfoEnabled()) { logger.info("********** Bridge Controller Current State: \"" + fsm.state().toString() + "\""); logger.info("********** Bridge Controller Processing Event: \"RecorderEvent\" (type = " + eventType + ")"); } if (RecorderEvent.RECORD_COMPLETED.equals(eventType)) { MediaGroupResponse<String> response = null; if (event.isSuccessful()) { String digits = ""; if (RecorderEvent.STOPPED.equals(event.getQualifier())) { digits = endOnKey; } saveRecording(); response = new MediaGroupResponse<String>(digits); } else { String reason = event.getErrorText(); MediaServerControllerException error = new MediaServerControllerException(reason); logger.error("Recording event failed: " + reason); response = new MediaGroupResponse<String>(error, reason); } recording = Boolean.FALSE; recordingRequest = null; super.remote.tell(response, 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, length: " + (new File(recordingUri).length())); } 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"); } } } } private class MixerAllocationListener implements AllocationEventListener, Serializable { private static final long serialVersionUID = -8450656267936666492L; @Override public void onEvent(AllocationEvent event) { EventType eventType = event.getEventType(); if(logger.isInfoEnabled()) { logger.info("********** Bridge Controller Current State: \"" + fsm.state().toString() + "\""); logger.info("********** Bridge Controller Processing Event: \"AllocationEventListener - Mixer\" (type = " + eventType + ")"); } try { if (AllocationEvent.ALLOCATION_CONFIRMED.equals(eventType)) { // No need to be notified anymore mediaMixer.removeListener(this); // join the media group to the mixer try { mediaGroup.join(Direction.DUPLEX, mediaMixer); } catch (MsControlException e) { fsm.transition(e, failed); } // Conference room has been properly activated and is now ready to receive connections fsm.transition(event, active); } else if (AllocationEvent.IRRECOVERABLE_FAILURE.equals(eventType)) { // Failed to allocate media mixer fsm.transition(event, failed); } } catch (TransitionFailedException | TransitionNotFoundException | TransitionRollbackException e) { logger.error(e.getMessage(), e); } } } /* * 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.getClass()); } 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 (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 onCreateMediaSession(CreateMediaSession message, ActorRef self, ActorRef sender) throws Exception { if (is(uninitialized)) { this.bridge = sender; this.fsm.transition(message, initializing); } } 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.mediaMixer, message.getConnectionMode()); message.getCall().tell(join, sender); } private void onStop(Stop message, ActorRef self, ActorRef sender) throws Exception { if (is(initializing) || is(active)) { this.fsm.transition(message, inactive); } } private void onStartRecording(StartRecording message, ActorRef self, ActorRef sender) throws Exception { if (is(active)) { try { if(logger.isInfoEnabled()) { logger.info("Start recording bridged call"); } Parameters params = this.mediaGroup.createParameters(); // Finish on key String endOnKey = "1234567890*#"; RTC[] rtcs; params.put(SignalDetector.PATTERN[0], endOnKey); params.put(SignalDetector.INTER_SIG_TIMEOUT, new Integer(10000)); rtcs = new RTC[] { MediaGroup.SIGDET_STOPPLAY }; // Recording length params.put(Recorder.MAX_DURATION, 3600 * 1000); // Recording timeout int timeout = 5; params.put(SpeechDetectorConstants.INITIAL_TIMEOUT, timeout); params.put(SpeechDetectorConstants.FINAL_TIMEOUT, timeout); // Other parameters params.put(Recorder.APPEND, Boolean.FALSE); // TODO set as definitive media group parameter - handled by RestComm params.put(Recorder.START_BEEP, Boolean.FALSE); this.recorderListener.setEndOnKey(endOnKey); this.recorderListener.setRemote(sender); this.mediaGroup.getRecorder().record(message.getRecordingUri(), rtcs, params); this.recording = Boolean.TRUE; this.recordingRequest = message; } catch (MsControlException e) { logger.error("Recording failed: " + e.getMessage()); final MediaServerControllerError error = new MediaServerControllerError(e); bridge.tell(error, self); } } } /* * Actions */ private final class Initializing extends AbstractAction { public Initializing(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { try { CreateMediaSession msg = (CreateMediaSession) message; MediaAttributes mediaAttributes = msg.mediaAttributes(); // Create media session mediaSession = msControlFactory.createMediaSession(); // Create the media group with recording capabilities mediaGroup = mediaSession.createMediaGroup(MediaGroup.PLAYER_RECORDER_SIGNALDETECTOR); mediaGroup.getRecorder().addListener(recorderListener); if (!MediaAttributes.MediaType.AUDIO_ONLY.equals(mediaAttributes.getMediaType())) { // video only or audio and video (video only is controlled by codec policy) configureVideoMediaSession(mediaAttributes); Parameters mixerParams = createMixerParams(); mediaMixer = mediaSession.createMediaMixer(MediaMixer.AUDIO_VIDEO, mixerParams); } else { // audio only Parameters mixerParams = createMixerParams(); mediaMixer = mediaSession.createMediaMixer(MediaMixer.AUDIO, mixerParams); } mediaMixer.addListener(mixerAllocationListener); mediaMixer.confirm(); // Wait for event confirmation before sending response to the conference } catch (MsControlException e) { // Move to a failed state, cleaning all resources and closing media session fsm.transition(e, failed); } } private void configureVideoMediaSession(final MediaAttributes mediaAttributes) { // resolution configuration mediaSession.setAttribute("NC_VIDEO_SIZE", mediaAttributes.getVideoResolution().toString()); } private Parameters createMixerParams() { // Allow only two participants and one media group Parameters mixerParams = mediaSession.createParameters(); mixerParams.put(MediaMixer.MAX_PORTS, 3); return mixerParams; } } 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 Inactive extends AbstractAction { public Inactive(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { try { stopMediaOperations(); } catch (MsControlException e) { logger.error(e, "Could not stop ongoing media operations in an elegant manner"); } cleanMediaResources(); // Broadcast state changed broadcast(new MediaServerControllerStateChanged(MediaServerControllerState.INACTIVE)); // Clear observers observers.clear(); // Terminate actor getContext().stop(super.source); } } private final class Failed extends AbstractAction { public Failed(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Clean resources cleanMediaResources(); // Broadcast state changed broadcast(new MediaServerControllerStateChanged(MediaServerControllerState.FAILED)); // Clear observers observers.clear(); // Terminate actor getContext().stop(super.source); } } }
22,328
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Jsr309CallController.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.jsr309/src/main/java/org/restcomm/connect/mscontrol/jsr309/Jsr309CallController.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.jsr309; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; 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.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.mscontrol.api.MediaServerController; import org.restcomm.connect.mscontrol.api.MediaServerInfo; import org.restcomm.connect.mscontrol.api.exceptions.MediaServerControllerException; 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.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerError; 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.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.api.messages.Unmute; import org.restcomm.connect.mscontrol.api.messages.UpdateMediaSession; import org.restcomm.connect.mscontrol.api.messages.RecordStoped; import javax.media.mscontrol.EventType; import javax.media.mscontrol.MediaEvent; import javax.media.mscontrol.MediaEventListener; import javax.media.mscontrol.MediaSession; import javax.media.mscontrol.MsControlException; import javax.media.mscontrol.MsControlFactory; import javax.media.mscontrol.Parameter; import javax.media.mscontrol.Parameters; import javax.media.mscontrol.join.Joinable.Direction; import javax.media.mscontrol.mediagroup.CodecConstants; import javax.media.mscontrol.mediagroup.MediaGroup; import javax.media.mscontrol.mediagroup.Player; import javax.media.mscontrol.mediagroup.PlayerEvent; import javax.media.mscontrol.mediagroup.Recorder; import javax.media.mscontrol.mediagroup.RecorderEvent; import javax.media.mscontrol.mediagroup.SpeechDetectorConstants; import javax.media.mscontrol.mediagroup.signals.SignalDetector; import javax.media.mscontrol.mediagroup.signals.SignalDetectorEvent; import javax.media.mscontrol.mixer.MediaMixer; import javax.media.mscontrol.networkconnection.CodecPolicy; import javax.media.mscontrol.networkconnection.NetworkConnection; import javax.media.mscontrol.networkconnection.SdpPortManager; import javax.media.mscontrol.networkconnection.SdpPortManagerEvent; import javax.media.mscontrol.resource.RTC; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.File; import java.io.IOException; import java.io.Serializable; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Henrique Rosa ([email protected]) * */ public class Jsr309CallController extends MediaServerController { // Logging private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // FSM. private final FiniteStateMachine fsm; // FSM states private final State uninitialized; private final State initializing; private final State active; private final State pending; private final State updatingMediaSession; private final State inactive; private final State failed; // JSR-309 runtime stuff private final MsControlFactory msControlFactory; private final MediaServerInfo mediaServerInfo; private MediaSession mediaSession; private NetworkConnection networkConnection; private MediaGroup mediaGroup; private MediaMixer mediaMixer; private final SdpListener sdpListener; private final PlayerListener playerListener; private final DtmfListener dtmfListener; private final RecorderListener recorderListener; // Call runtime stuff private ActorRef call; private Sid callId; private String localSdp; private String remoteSdp; private String connectionMode; private boolean callOutbound; private boolean webrtc; // Conference runtime stuff private ActorRef bridge; // Call Media Operations private Sid accountId; private Sid recordingSid; private URI recordingUri; private Boolean recording; private Boolean playing; private Boolean collecting; private DaoManager daoManager; private MediaAttributes.MediaType recordingMediaType; // Runtime Setting private Configuration runtimeSettings; // Observers private final List<ActorRef> observers; public Jsr309CallController(MsControlFactory msControlFactory, MediaServerInfo mediaServerInfo) { super(); final ActorRef source = self(); // JSR-309 runtime stuff this.msControlFactory = msControlFactory; this.mediaServerInfo = mediaServerInfo; this.sdpListener = new SdpListener(); this.playerListener = new PlayerListener(); this.dtmfListener = new DtmfListener(); this.recorderListener = new RecorderListener(); // Initialize the states for the FSM this.uninitialized = new State("uninitialized", null); this.initializing = new State("initializing", new Initializing(source)); this.active = new State("active", new Active(source)); this.pending = new State("pending", new Pending(source)); this.updatingMediaSession = new State("updating media session", new UpdatingMediaSession(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(uninitialized, initializing)); transitions.add(new Transition(uninitialized, failed)); transitions.add(new Transition(initializing, failed)); transitions.add(new Transition(initializing, active)); transitions.add(new Transition(initializing, pending)); transitions.add(new Transition(initializing, inactive)); transitions.add(new Transition(pending, updatingMediaSession)); transitions.add(new Transition(pending, inactive)); transitions.add(new Transition(pending, failed)); transitions.add(new Transition(active, updatingMediaSession)); transitions.add(new Transition(active, inactive)); transitions.add(new Transition(active, failed)); transitions.add(new Transition(updatingMediaSession, active)); transitions.add(new Transition(updatingMediaSession, inactive)); transitions.add(new Transition(updatingMediaSession, failed)); // Finite state machine this.fsm = new FiniteStateMachine(this.uninitialized, transitions); // Observers this.observers = new ArrayList<ActorRef>(2); // Call runtime stuff this.localSdp = ""; this.remoteSdp = ""; this.callOutbound = false; this.webrtc = false; this.connectionMode = "inactive"; this.recording = Boolean.FALSE; this.playing = Boolean.FALSE; this.collecting = Boolean.FALSE; this.recordingMediaType = null; } private boolean is(State state) { return fsm.state().equals(state); } private void notifyObservers(Object message, ActorRef self) { for (final ActorRef observer : observers) { observer.tell(message, self); } } /* * LISTENERS - MSCONTROL */ private abstract class MediaListener<T extends MediaEvent<?>> implements MediaEventListener<T>, Serializable { private static final long serialVersionUID = 7103112381914312776L; protected ActorRef originator; public void setRemote(ActorRef sender) { this.originator = sender; } } private final class SdpListener extends MediaListener<SdpPortManagerEvent> { private static final long serialVersionUID = 1578203803932778931L; @Override public void onEvent(SdpPortManagerEvent event) { EventType eventType = event.getEventType(); if(logger.isInfoEnabled()) { logger.info("********** Call Controller Current State: \"" + fsm.state().toString() + "\""); logger.info("********** Call Controller Processing Event: \"SdpPortManagerEvent\" (type = " + eventType + ")"); } try { if (event.isSuccessful()) { if (is(initializing) || is(updatingMediaSession)) { networkConnection.getSdpPortManager().removeListener(this); if (SdpPortManagerEvent.ANSWER_GENERATED.equals(eventType)) { if (is(initializing)) { // Get the generated answer localSdp = new String(event.getMediaServerSdp()); // Join the media group to the network connection // Perform this operation only once, when initializing the controller for first time. networkConnection.join(Direction.DUPLEX, mediaGroup); // Move to active state fsm.transition(event, active); } } else if (SdpPortManagerEvent.OFFER_GENERATED.equals(eventType)) { if (is(initializing)) { // Get the generated offer localSdp = new String(event.getMediaServerSdp()); // hrosa - necessary patch for Dialogic XMS WebRTC calls // https://github.com/RestComm/Restcomm-Connect/issues/986 if (webrtc) { localSdp = localSdp.replaceAll("SAVP ", "SAVPF "); } // Move to a pending state waiting for an answer fsm.transition(event, pending); } } else if (SdpPortManagerEvent.ANSWER_PROCESSED.equals(eventType)) { if (is(updatingMediaSession)) { // Join the media group to the network connection // Perform this operation only once, when initializing the controller for first time. if (mediaGroup.getJoinees().length == 0) { networkConnection.join(Direction.DUPLEX, mediaGroup); } // Move to an active state fsm.transition(event, active); } } else if (SdpPortManagerEvent.NETWORK_STREAM_FAILURE.equals(eventType)) { // Unable to negotiate session over SDP // Move to a failed state fsm.transition(event, failed); } } } else { fsm.transition(event, failed); } } catch (Exception e) { logger.error(e, "Could not set up the network connection"); } } } private final class PlayerListener extends MediaListener<PlayerEvent> { private static final long serialVersionUID = -1814168664061905439L; @Override public void onEvent(PlayerEvent event) { EventType eventType = event.getEventType(); if(logger.isInfoEnabled()) { logger.info("********** Call Controller Current State: \"" + fsm.state().toString() + "\""); logger.info("********** Call Controller Processing Event: \"PlayerEvent\" (type = " + eventType + ")"); } if (PlayerEvent.PLAY_COMPLETED.equals(eventType)) { MediaGroupResponse<String> response; if (event.isSuccessful()) { response = new MediaGroupResponse<String>(eventType.toString()); } else { String reason = event.getErrorText(); MediaServerControllerException error = new MediaServerControllerException(reason); response = new MediaGroupResponse<String>(error, reason); } playing = Boolean.FALSE; super.originator.tell(response, self()); } } } private final class DtmfListener extends MediaListener<SignalDetectorEvent> { private static final long serialVersionUID = -96652040901361098L; @Override public void onEvent(SignalDetectorEvent event) { EventType eventType = event.getEventType(); if(logger.isInfoEnabled()) { logger.info("********** Call Controller Current State: \"" + fsm.state().toString() + "\""); logger.info("********** Call Controller Processing Event: \"SignalDetectorEvent\" (type = " + eventType + ")"); } if (SignalDetectorEvent.RECEIVE_SIGNALS_COMPLETED.equals(eventType)) { MediaGroupResponse<String> response; if (event.isSuccessful()) { response = new MediaGroupResponse<String>(event.getSignalString()); } else { String reason = event.getErrorText(); MediaServerControllerException error = new MediaServerControllerException(reason); response = new MediaGroupResponse<String>(error, reason); } collecting = Boolean.FALSE; super.originator.tell(response, self()); } } } private final class RecorderListener extends MediaListener<RecorderEvent> { private static final long serialVersionUID = -8952464412809110917L; private String endOnKey = ""; public void setEndOnKey(String endOnKey) { this.endOnKey = endOnKey; } @Override public void onEvent(RecorderEvent event) { EventType eventType = event.getEventType(); if(logger.isInfoEnabled()) { logger.info("********** Call Controller Current State: \"" + fsm.state().toString() + "\""); logger.info("********** Call Controller Processing Event: \"RecorderEvent\" (type = " + eventType + ")"); } if (RecorderEvent.RECORD_COMPLETED.equals(eventType)) { MediaGroupResponse<String> response = null; if (event.isSuccessful()) { String digits = ""; if (RecorderEvent.STOPPED.equals(event.getQualifier())) { digits = endOnKey; } response = new MediaGroupResponse<String>(digits); } else { String reason = event.getErrorText(); MediaServerControllerException error = new MediaServerControllerException(reason); logger.error("Recording event failed: " + reason); response = new MediaGroupResponse<String>(error, reason); } recording = Boolean.FALSE; super.originator.tell(response, 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("********** Call Controller Current State: \"" + state.toString()); logger.info("********** Call Controller Processing Message: \"" + klass.getName() + " sender : " + sender.getClass()); } 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 (StopMediaGroup.class.equals(klass)) { onStopMediaGroup((StopMediaGroup) 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 (StartRecording.class.equals(klass)) { onStartRecordingCall((StartRecording) message, self, sender); } else if (StopRecording.class.equals(klass)) { onStopRecordingCall((StopRecording) 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 (Record.class.equals(klass)) { onRecord((Record) message, self, sender); } else if (JoinBridge.class.equals(klass)) { onJoinBridge((JoinBridge) message, self, sender); } else if (JoinConference.class.equals(klass)) { onJoinConference((JoinConference) message, self, sender); } else if (Stop.class.equals(klass)) { onStop((Stop) message, self, sender); } else if (Leave.class.equals(klass)) { onLeave((Leave) message, self, sender); } } private void onObserve(Observe message, ActorRef self, ActorRef sender) throws Exception { 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) throws Exception { final ActorRef observer = message.observer(); if (observer != null) { this.observers.remove(observer); } else { this.observers.clear(); } } private void onCreateMediaSession(CreateMediaSession message, ActorRef self, ActorRef sender) throws Exception { if (is(uninitialized)) { this.call = sender; this.callOutbound = message.isOutbound(); this.connectionMode = message.getConnectionMode(); this.remoteSdp = message.getSessionDescription(); this.webrtc = message.isWebrtc(); fsm.transition(message, initializing); } } private void onCloseMediaSession(CloseMediaSession message, ActorRef self, ActorRef sender) throws Exception { if (is(active) || is(initializing) || is(updatingMediaSession) || is(pending)) { fsm.transition(message, inactive); } } private void onUpdateMediaSession(UpdateMediaSession message, ActorRef self, ActorRef sender) throws Exception { if (is(pending) || is(active)) { this.remoteSdp = message.getSessionDescription(); fsm.transition(message, updatingMediaSession); } } private void onStopMediaGroup(StopMediaGroup message, ActorRef self, ActorRef sender) throws Exception { try { if (this.mediaGroup != null) { // XXX mediaGroup.stop() not implemented on dialogic connector if (this.playing) { this.mediaGroup.getPlayer().stop(true); this.playing = Boolean.FALSE; } if (this.recording) { this.mediaGroup.getRecorder().stop(); this.recording = Boolean.FALSE; } if (this.collecting) { this.mediaGroup.getSignalDetector().stop(); this.collecting = Boolean.FALSE; } } } catch (MsControlException e) { fsm.transition(e, failed); } } private void onMute(Mute message, ActorRef self, ActorRef sender) { if (is(active) && (this.mediaMixer != null)) { try { this.networkConnection.join(Direction.RECV, this.mediaMixer); } catch (MsControlException e) { logger.error("Could not mute call: " + e.getMessage(), e); } } } private void onUnmute(Unmute message, ActorRef self, ActorRef sender) throws Exception { if (is(active) && (this.mediaMixer != null)) { try { this.networkConnection.join(Direction.DUPLEX, this.mediaMixer); } catch (MsControlException e) { logger.error("Could not unmute call: " + e.getMessage(), e); } } } private void onStartRecordingCall(StartRecording message, ActorRef self, ActorRef sender) { if (is(active)) { if (runtimeSettings == null) { this.runtimeSettings = message.getRuntimeSetting(); } if (daoManager == null) { daoManager = message.getDaoManager(); } if (accountId == null) { accountId = message.getAccountId(); } this.callId = message.getCallId(); this.recordingSid = message.getRecordingSid(); this.recordingUri = message.getRecordingUri(); this.recording = true; if(logger.isInfoEnabled()) { logger.info("Start recording call"); } // Tell media group to start recording final Record record = new Record(recordingUri, 5, 3600, "1234567890*#", MediaAttributes.MediaType.AUDIO_ONLY); onRecord(record, self, sender); } } private void onStopRecordingCall(StopRecording message, ActorRef self, ActorRef sender) { if (is(active) && recording) { if (runtimeSettings == null) { this.runtimeSettings = message.getRuntimeSetting(); } if (daoManager == null) { this.daoManager = message.getDaoManager(); } if (accountId == null) { this.accountId = message.getAccountId(); } // Tell media group to stop recording if(logger.isInfoEnabled()) { logger.info("Stop recording call"); } onStop(new Stop(false), self, sender); } } private void onPlay(Play message, ActorRef self, ActorRef sender) { if (is(active)) { try { List<URI> uris = message.uris(); Parameters params = this.mediaGroup.createParameters(); int repeatCount = message.iterations() <= 0 ? Player.FOREVER : message.iterations() - 1; params.put(Player.REPEAT_COUNT, repeatCount); this.playerListener.setRemote(sender); this.mediaGroup.getPlayer().play(uris.toArray(new URI[uris.size()]), RTC.NO_RTC, params); this.playing = Boolean.TRUE; } catch (MsControlException e) { logger.error("Play failed: " + e.getMessage()); final MediaGroupResponse<String> response = new MediaGroupResponse<String>(e); notifyObservers(response, self); } } } private void onCollect(Collect message, ActorRef self, ActorRef sender) { if (is(active)) { try { Parameters optargs = this.mediaGroup.createParameters(); // Add patterns to the detector List<Parameter> patterns = new ArrayList<Parameter>(2); if (message.hasEndInputKey()) { optargs.put(SignalDetector.PATTERN[0], message.endInputKey()); patterns.add(SignalDetector.PATTERN[0]); } if (message.hasPattern()) { optargs.put(SignalDetector.PATTERN[1], message.pattern()); patterns.add(SignalDetector.PATTERN[1]); } Parameter[] patternArray = null; if (!patterns.isEmpty()) { patternArray = patterns.toArray(new Parameter[patterns.size()]); } // Setup enabled events EventType[] enabledEvents = { SignalDetectorEvent.RECEIVE_SIGNALS_COMPLETED }; optargs.put(SignalDetector.ENABLED_EVENTS, enabledEvents); // Setup prompts if (message.hasPrompts()) { List<URI> prompts = message.prompts(); optargs.put(SignalDetector.PROMPT, prompts.toArray(new URI[prompts.size()])); } // Setup time out interval int timeout = message.timeout(); optargs.put(SignalDetector.INITIAL_TIMEOUT, timeout); optargs.put(SignalDetector.INTER_SIG_TIMEOUT, timeout); // Disable buffering for performance gain optargs.put(SignalDetector.BUFFERING, false); this.dtmfListener.setRemote(sender); this.mediaGroup.getSignalDetector().flushBuffer(); this.mediaGroup.getSignalDetector().receiveSignals(message.numberOfDigits(), patternArray, RTC.NO_RTC, optargs); this.collecting = Boolean.TRUE; } catch (MsControlException e) { logger.error("DTMF recognition failed: " + e.getMessage()); final MediaGroupResponse<String> response = new MediaGroupResponse<String>(e); notifyObservers(response, self); } } } private void onRecord(Record message, ActorRef self, ActorRef sender) { if (is(active)) { try { Parameters params = this.mediaGroup.createParameters(); // Add prompts if (message.hasPrompts()) { List<URI> prompts = message.prompts(); // TODO JSR-309 connector still does not support multiple prompts // params.put(Recorder.PROMPT, prompts.toArray(new URI[prompts.size()])); params.put(Recorder.PROMPT, prompts.get(0)); } // Finish on key RTC[] rtcs; if (message.hasEndInputKey()) { params.put(SignalDetector.PATTERN[0], message.endInputKey()); params.put(SignalDetector.INTER_SIG_TIMEOUT, new Integer(10000)); rtcs = new RTC[] { MediaGroup.SIGDET_STOPPLAY }; } else { rtcs = RTC.NO_RTC; } // Recording length params.put(Recorder.MAX_DURATION, message.length() * 1000); // Recording timeout int timeout = message.timeout(); params.put(SpeechDetectorConstants.INITIAL_TIMEOUT, timeout); params.put(SpeechDetectorConstants.FINAL_TIMEOUT, timeout); // Other parameters params.put(Recorder.APPEND, Boolean.FALSE); // TODO set as definitive media group parameter - handled by RestComm params.put(Recorder.START_BEEP, Boolean.FALSE); // Video parameters if (MediaAttributes.MediaType.AUDIO_VIDEO.equals(message.media()) || MediaAttributes.MediaType.VIDEO_ONLY.equals(message.media())) { params.put(Recorder.VIDEO_CODEC, CodecConstants.H264); String sVideoFMTP = "profile=" + "66"; sVideoFMTP += ";level=" + "3.1"; sVideoFMTP += ";width=" + "1280"; sVideoFMTP += ";height=" + "720"; sVideoFMTP += ";framerate=" + "15"; params.put(Recorder.VIDEO_FMTP, sVideoFMTP); params.put(Recorder.VIDEO_MAX_BITRATE, 2000); if (MediaAttributes.MediaType.AUDIO_VIDEO.equals(message.media())) { params.put(Recorder.AUDIO_CODEC, CodecConstants.AMR); } } this.recorderListener.setEndOnKey(message.endInputKey()); this.recorderListener.setRemote(sender); this.mediaGroup.getRecorder().record(message.destination(), rtcs, params); this.recordingMediaType = message.media(); this.recording = Boolean.TRUE; } catch (MsControlException e) { logger.error("Recording failed: " + e.getMessage()); final MediaGroupResponse<String> response = new MediaGroupResponse<String>(e); notifyObservers(response, self); } } } private void onJoinBridge(JoinBridge message, ActorRef self, ActorRef sender) throws Exception { if (is(active)) { try { // join call leg to bridge this.bridge = sender; this.mediaMixer = (MediaMixer) message.getEndpoint(); this.networkConnection.join(Direction.DUPLEX, mediaMixer); // alert call has joined successfully this.call.tell(new JoinComplete(), self); } catch (MsControlException e) { logger.error("Call bridging failed: " + e.getMessage()); fsm.transition(e, failed); } } } private void onJoinConference(JoinConference message, ActorRef self, ActorRef sender) throws Exception { if (is(active)) { try { // join call leg to bridge // overlay configuration MediaAttributes ma = message.mediaAttributes(); if (!StringUtils.isEmpty(ma.getVideoOverlay())) { mediaSession.setAttribute("CAPTION", ma.getVideoOverlay()); } this.bridge = sender; this.mediaMixer = (MediaMixer) message.getEndpoint(); this.networkConnection.join(Direction.DUPLEX, mediaMixer); // alert call has joined successfully this.call.tell(new JoinComplete(), self); } catch (MsControlException e) { logger.error("Call bridging failed: " + e.getMessage()); fsm.transition(e, failed); } } } private void onStop(Stop message, ActorRef self, ActorRef sender) { try { // XXX mediaGroup.stop() not implemented on Dialogic connector if (this.playing) { this.mediaGroup.getPlayer().stop(true); this.playing = Boolean.FALSE; } if (this.recording) { this.mediaGroup.getRecorder().stop(); this.recording = Boolean.FALSE; if (message.createRecord() && recordingUri != null) { 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, length: " + (new File(recordingUri).length())); } 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); builder.setUri(RestcommConnectServiceProvider.getInstance().recordingService() .prepareFileUrl(apiVersion, accountId.toString(), recordingSid.toString(), recordingMediaType)); URI s3Uri = RestcommConnectServiceProvider.getInstance().recordingService().storeRecording(recordingSid, recordingMediaType); 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"); } } } } if (this.collecting) { this.mediaGroup.getSignalDetector().stop(); this.collecting = Boolean.FALSE; } call.tell(new RecordStoped(), self); } catch (MsControlException e) { call.tell(new MediaServerControllerError(e), self); } } private void onLeave(Leave message, ActorRef self, ActorRef sender) throws Exception { if (is(active) && (this.mediaMixer != null)) { try { // Leave conference or bridge this.networkConnection.unjoin(this.mediaMixer); this.mediaMixer = null; this.bridge = null; // Restore link with Media Group this.networkConnection.join(Direction.DUPLEX, this.mediaGroup); // Warn call the operation is complete call.tell(new Left(), self); } catch (MsControlException e) { logger.error(e, "Call could not leave Bridge. Failing..."); fsm.transition(e, failed); } } } /* * ACTIONS */ private final class Initializing extends AbstractAction { public Initializing(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { try { CreateMediaSession msg = (CreateMediaSession) message; MediaAttributes mediaAttributes = msg.mediaAttributes(); // Create media session mediaSession = msControlFactory.createMediaSession(); // Create media group with full capabilities mediaGroup = mediaSession.createMediaGroup(MediaGroup.PLAYER_RECORDER_SIGNALDETECTOR); // Prepare the Media Group resources mediaGroup.getPlayer().addListener(playerListener); mediaGroup.getSignalDetector().addListener(dtmfListener); mediaGroup.getRecorder().addListener(recorderListener); // Create network connection networkConnection = mediaSession.createNetworkConnection(NetworkConnection.BASIC); // Distinguish between WebRTC and SIP calls Parameters sdpParameters = mediaSession.createParameters(); Map<String, String> configurationData = new HashMap<String, String>(); if (webrtc) { configurationData.put("webrtc", "yes"); // Enable DTLS, ICE Lite and RTCP feedback configurationData.put("Supported", "dlgc-encryption-dtls, dlgc-ice, dlgc-rtcp-feedback-audiovideo"); } else { configurationData.put("webrtc", "no"); } sdpParameters.put(SdpPortManager.SIP_HEADERS, configurationData); networkConnection.setParameters(sdpParameters); CodecPolicy codecPolicy = new CodecPolicy(); codecPolicy.setMediaTypeCapabilities(mediaAttributes.getMediaType().getCodecPolicy()); networkConnection.getSdpPortManager().setCodecPolicy(codecPolicy); networkConnection.getSdpPortManager().addListener(sdpListener); if (callOutbound) { networkConnection.getSdpPortManager().generateSdpOffer(); } else { networkConnection.getSdpPortManager().processSdpOffer(remoteSdp.getBytes()); } } catch (MsControlException e) { fsm.transition(e, failed); } } } private final class UpdatingMediaSession extends AbstractAction { public UpdatingMediaSession(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { try { networkConnection.getSdpPortManager().addListener(sdpListener); networkConnection.getSdpPortManager().processSdpAnswer(remoteSdp.getBytes()); } catch (MsControlException e) { fsm.transition(e, failed); } } } private final class Pending extends AbstractAction { public Pending(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Inform observers the state of the controller has changed final MediaSessionInfo info = new MediaSessionInfo(true, mediaServerInfo.getAddress(), localSdp, remoteSdp); call.tell(new MediaServerControllerStateChanged(MediaServerControllerState.PENDING, info), super.source); } } private final class Active extends AbstractAction { public Active(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Inform observers the state of the controller has changed final MediaSessionInfo info = new MediaSessionInfo(true, mediaServerInfo.getAddress(), localSdp, remoteSdp); call.tell(new MediaServerControllerStateChanged(MediaServerControllerState.ACTIVE, info), super.source); } } private abstract class FinalState extends AbstractAction { protected final MediaServerControllerState state; public FinalState(ActorRef source, MediaServerControllerState state) { super(source); this.state = state; } @Override public void execute(Object message) throws Exception { cleanMediaResources(); notifyObservers(new MediaServerControllerStateChanged(state), super.source); } private void cleanMediaResources() { mediaSession.release(); mediaSession = null; mediaGroup = null; mediaMixer = null; } } private final class Inactive extends FinalState { public Inactive(ActorRef source) { super(source, MediaServerControllerState.INACTIVE); } } private final class Failed extends FinalState { public Failed(ActorRef source) { super(source, MediaServerControllerState.FAILED); } } }
42,613
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NumberSelectorServiceTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/test/java/org/restcomm/connect/core/service/number/NumberSelectorServiceTest.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.core.service.number; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import static org.mockito.ArgumentMatchers.any; import org.mockito.InOrder; import org.mockito.Mockito; import static org.mockito.Mockito.*; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.number.NumberSelectorServiceImpl; import org.restcomm.connect.dao.IncomingPhoneNumbersDao; import org.restcomm.connect.dao.entities.IncomingPhoneNumber; import org.restcomm.connect.dao.entities.IncomingPhoneNumberFilter; public class NumberSelectorServiceTest { public NumberSelectorServiceTest() { } @Test public void testNoMatch() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = srcSid; String number = "1234"; List<IncomingPhoneNumber> emptyNumbers = new ArrayList(); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyNumbers, emptyNumbers, emptyNumbers); when(numDao.getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any())). thenReturn(emptyNumbers); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(0,0,0); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber(number, srcSid, destSid); Assert.assertNull(found); inOrder.verify(numDao, times(3)).getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any()); } @Test public void testPerfectMatch() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = Sid.generate(Sid.Type.ORGANIZATION); String number = "1234"; List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(number); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber(number, srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(number, found.getPhoneNumber()); inOrder.verify(numDao, times(1)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); verify(numDao, never()).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testUSMatch() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = Sid.generate(Sid.Type.ORGANIZATION); String number = "+1234"; List<IncomingPhoneNumber> emptyList = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(number); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyList, numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber("1234", srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(number, found.getPhoneNumber()); inOrder.verify(numDao, times(2)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); verify(numDao, never()).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testNoPlusMatch() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = Sid.generate(Sid.Type.ORGANIZATION); String number = "1234"; List<IncomingPhoneNumber> emptyList = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(number); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyList, numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber("+1234", srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(number, found.getPhoneNumber()); inOrder.verify(numDao, times(2)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); verify(numDao, never()).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testPerfectMatchNoOrg() { Sid srcSid = null; Sid destSid = null; String number = "1234"; List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(number); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber(number, srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(number, found.getPhoneNumber()); inOrder.verify(numDao, times(1)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); verify(numDao, never()).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testStarMatch() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = srcSid; String number = "1234"; String star = "*"; List<IncomingPhoneNumber> emptyList = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(star); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyList,emptyList, numbers); when(numDao.getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any())). thenReturn(emptyList); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber(number, srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(star, found.getPhoneNumber()); inOrder.verify(numDao, times(3)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); } @Test public void testRegexNoOrg() { Sid srcSid = null; Sid destSid = null; String regex = "12 when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())).\n" + " thenReturn(1,1,1);.*"; List<IncomingPhoneNumber> emptyNumbers = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(regex); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyNumbers, emptyNumbers); when(numDao.getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber("1234", srcSid, destSid); Assert.assertNull(found); inOrder.verify(numDao, times(2)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); inOrder.verify(numDao, never()).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testRegexMatch() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = srcSid; String regex = "12.*"; String longestRegex = "123.*"; List<IncomingPhoneNumber> emptyNumbers = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(regex); numbers.add(builder.build()); builder.setPhoneNumber(longestRegex); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyNumbers, emptyNumbers); when(numDao.getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber("1234", srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(longestRegex, found.getPhoneNumber()); inOrder.verify(numDao, times(2)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); inOrder.verify(numDao, times(1)).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testRegexMatch2() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = srcSid; String regex1 = "123456*"; String regex2 = "554433*"; String regex3 = "778899*"; String regex4 = "987456*"; String regex5 = "987456789*"; String regex6 = "12*"; String regex7 = "*"; List<IncomingPhoneNumber> emptyNumbers = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(regex1); numbers.add(builder.build()); builder.setPhoneNumber(regex2); numbers.add(builder.build()); builder.setPhoneNumber(regex3); numbers.add(builder.build()); builder.setPhoneNumber(regex4); numbers.add(builder.build()); builder.setPhoneNumber(regex5); numbers.add(builder.build()); builder.setPhoneNumber(regex6); numbers.add(builder.build()); builder.setPhoneNumber(regex7); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyNumbers, emptyNumbers); when(numDao.getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber("987456", srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(regex4, found.getPhoneNumber()); inOrder.verify(numDao, times(3)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); inOrder.verify(numDao, times(1)).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testRegexMatchFromNullSrcOrg() { Sid srcSid = null; Sid destSid = Sid.generate(Sid.Type.ORGANIZATION); String regex = "12.*"; String longestRegex = "123.*"; List<IncomingPhoneNumber> emptyNumbers = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(regex); numbers.add(builder.build()); builder.setPhoneNumber(longestRegex); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyNumbers, emptyNumbers); when(numDao.getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber("1234", srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(longestRegex, found.getPhoneNumber()); inOrder.verify(numDao, times(2)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); inOrder.verify(numDao, times(1)).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testRegexFailToMatchBecauseOfPhone() { Sid srcSid = null; Sid destSid = Sid.generate(Sid.Type.ORGANIZATION); String regex = "12.*"; String longestRegex = "123.*"; List<IncomingPhoneNumber> emptyNumbers = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(regex); numbers.add(builder.build()); builder.setPhoneNumber(longestRegex); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyNumbers, emptyNumbers); when(numDao.getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber("7788", srcSid, destSid); Assert.assertNull(found); inOrder.verify(numDao, times(4)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); inOrder.verify(numDao, never()).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testRegexFailToMatchBecauseDestOrgNull() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = null; String regex = "12.*"; String longestRegex = "123.*"; List<IncomingPhoneNumber> emptyNumbers = new ArrayList(); List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(regex); numbers.add(builder.build()); builder.setPhoneNumber(longestRegex); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1,1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(emptyNumbers, emptyNumbers); when(numDao.getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber("1234", srcSid, destSid); Assert.assertNull(found); inOrder.verify(numDao, times(2)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); inOrder.verify(numDao, never()).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } @Test public void testSamePhoneDiffOrg() { Sid srcSid = Sid.generate(Sid.Type.ORGANIZATION); Sid srcSid2 = Sid.generate(Sid.Type.ORGANIZATION); Sid destSid = Sid.generate(Sid.Type.ORGANIZATION); String number = "1234"; List<IncomingPhoneNumber> numbers = new ArrayList(); final IncomingPhoneNumber.Builder builder = IncomingPhoneNumber.builder(); builder.setPhoneNumber(number); builder.setOrganizationSid(srcSid); numbers.add(builder.build()); builder.setPhoneNumber(number); builder.setOrganizationSid(srcSid2); numbers.add(builder.build()); IncomingPhoneNumbersDao numDao = Mockito.mock(IncomingPhoneNumbersDao.class); when(numDao.getTotalIncomingPhoneNumbers((IncomingPhoneNumberFilter) any())). thenReturn(1); when(numDao.getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any())). thenReturn(numbers); InOrder inOrder = inOrder(numDao); NumberSelectorServiceImpl service = new NumberSelectorServiceImpl(numDao); IncomingPhoneNumber found = service.searchNumber(number, srcSid, destSid); Assert.assertNotNull(found); Assert.assertEquals(number, found.getPhoneNumber()); inOrder.verify(numDao, times(1)).getIncomingPhoneNumbersByFilter((IncomingPhoneNumberFilter) any()); verify(numDao, never()).getIncomingPhoneNumbersRegex((IncomingPhoneNumberFilter) any()); } }
20,665
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RecordingServiceTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/test/java/org/restcomm/connect/core/service/recording/RecordingServiceTest.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.core.service.recording; import akka.dispatch.ExecutionContexts; import akka.dispatch.ExecutorServiceFactory; import org.apache.http.client.methods.AbstractExecutionAwareRequest; import org.junit.Test; import org.restcomm.connect.commons.amazonS3.S3AccessTool; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.util.UriUtils; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.OrganizationsDao; import org.restcomm.connect.dao.RecordingsDao; import org.restcomm.connect.dao.entities.Recording; import scala.concurrent.ExecutionContextExecutor; import scala.concurrent.impl.ExecutionContextImpl; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static junit.framework.TestCase.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class RecordingServiceTest { DaoManager daoManager = mock(DaoManager.class); OrganizationsDao organizationsDao = mock(OrganizationsDao.class); RecordingsDao recordingsDao = mock(RecordingsDao.class); S3AccessTool s3AccessTool = mock(S3AccessTool.class); Sid recordingSid = Sid.generate(Sid.Type.RECORDING); URI s3Uri = URI.create("https://127.0.0.1:8099/s3/"+recordingSid.toString()); UriUtils uriUtils = new UriUtils(daoManager, null, false); @Test public void deleteRecordingS3Test() throws IOException { Recording recording = prepareRecording(recordingSid, true); when(recordingsDao.getRecording(recordingSid)).thenReturn(recording); ExecutorService es = Executors.newFixedThreadPool(1); RecordingsServiceImpl recordingsService = new RecordingsServiceImpl(recordingsDao, "file:///", s3AccessTool, ExecutionContexts.fromExecutor(es), uriUtils); recordingsService.removeRecording(recordingSid); verify(s3AccessTool).removeS3Uri(recordingSid.toString()); verify(recordingsDao).removeRecording(recordingSid); } @Test public void deleteRecordingLocalTest() throws IOException { Recording recording = prepareRecording(recordingSid, false); File recordingFile = prepareRecordingFile(recordingSid); assertTrue(recordingFile.exists()); assertTrue(recordingFile.isAbsolute()); when(recordingsDao.getRecording(recordingSid)).thenReturn(recording); ExecutorService es = Executors.newFixedThreadPool(1); RecordingsServiceImpl recordingsService = new RecordingsServiceImpl(recordingsDao, "file:///"+recordingFile.getParent(), s3AccessTool, ExecutionContexts.fromExecutor(es), uriUtils); recordingsService.removeRecording(recordingSid); verify(recordingsDao).removeRecording(recordingSid); assertTrue(!recordingFile.exists()); } private Recording prepareRecording(Sid recordingSid, boolean s3) { Recording.Builder builder = Recording.builder(); builder.setAccountSid(Sid.generate(Sid.Type.ACCOUNT)); builder.setSid(recordingSid); builder.setApiVersion("2012-04-24"); builder.setCallSid(new Sid("CA00000000000000000000000000000011")); builder.setDuration(20.00); builder.setFileUri(URI.create("http://127.0.0.1:8080/restcomm/"+recordingSid+".wav")); if (s3) builder.setS3Uri(s3Uri); return builder.build(); } private File prepareRecordingFile(Sid recordingSid) throws IOException { File recordingFile = new File(recordingSid+".wav"); recordingFile.createNewFile(); return recordingFile.getAbsoluteFile(); } }
4,605
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProfileServiceTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/test/java/org/restcomm/connect/core/service/profile/ProfileServiceTest.java
package org.restcomm.connect.core.service.profile; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.mockito.Mockito.when; import java.sql.SQLException; import javax.servlet.ServletContext; import org.junit.Test; import org.mockito.Mockito; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.api.ProfileService; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.OrganizationsDao; import org.restcomm.connect.dao.ProfileAssociationsDao; import org.restcomm.connect.dao.ProfilesDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.entities.Profile; import org.restcomm.connect.dao.entities.ProfileAssociation; public class ProfileServiceTest { /** * case 1: given: a profile is explicitly assigned to an account * calling retrieveExplicitlyAssociatedProfile by account sid will return that profile * @throws SQLException */ @Test public void retrieveExplicitlyAssociatedProfileCase1() throws SQLException { MockingService mocks = new MockingService(); Account account = returnValidAccount(mocks); Profile expectedProfile = returnProfile(mocks); returnProfileAssociation(new Sid(expectedProfile.getSid()), account.getSid(), mocks); Profile resultantProfile = mocks.profileService.retrieveExplicitlyAssociatedProfile(account.getSid()); assertEquals(expectedProfile.getSid(), resultantProfile.getSid()); } /** * case 2: given: a profile is explicitly assigned to an organization * calling retrieveExplicitlyAssociatedProfile by organization sid will return that profile * @throws SQLException */ @Test public void retrieveExplicitlyAssociatedProfileCase2() throws SQLException { MockingService mocks = new MockingService(); Organization organization = returnValidOrganization(mocks); Profile expectedProfile = returnProfile(mocks); returnProfileAssociation(new Sid(expectedProfile.getSid()), organization.getSid(), mocks); Profile resultantProfile = mocks.profileService.retrieveExplicitlyAssociatedProfile(organization.getSid()); assertEquals(expectedProfile.getSid(), resultantProfile.getSid()); } /** * case 3: given: a profile is not explicitly assigned to an account * calling retrieveExplicitlyAssociatedProfile by account sid will return NULL * @throws SQLException */ @Test public void retrieveExplicitlyAssociatedProfileCase3() throws SQLException { MockingService mocks = new MockingService(); Account account = returnValidAccount(mocks); Profile resultantProfile = mocks.profileService.retrieveExplicitlyAssociatedProfile(account.getSid()); assertNull(resultantProfile); } /** * case 4: given: a profile is not explicitly assigned to an organization * calling retrieveExplicitlyAssociatedProfile by organization sid will return NULL * @throws SQLException */ @Test public void retrieveExplicitlyAssociatedProfileCase4() throws SQLException { MockingService mocks = new MockingService(); Organization organization = returnValidOrganization(mocks); Profile resultantProfile = mocks.profileService.retrieveExplicitlyAssociatedProfile(organization.getSid()); assertNull(resultantProfile); } /** * case 1: given: a profile is explicitly assigned to an organization * calling retrieveEffectiveProfileByOrganizationSid by organization sid will return that profile * @throws SQLException */ @Test public void retrieveEffectiveProfileByOrganizationSidCase1() throws SQLException { MockingService mocks = new MockingService(); Organization organization = returnValidOrganization(mocks); Profile expectedProfile = returnProfile(mocks); returnProfileAssociation(new Sid(expectedProfile.getSid()), organization.getSid(), mocks); Profile resultantProfile = mocks.profileService.retrieveEffectiveProfileByOrganizationSid(organization.getSid()); assertEquals(expectedProfile.getSid(), resultantProfile.getSid()); } /** * case 2: given: a profile is NOT explicitly assigned to an organization * calling retrieveEffectiveProfileByOrganizationSid by organization sid will return DEFAULT profile * @throws SQLException */ @Test public void retrieveEffectiveProfileByOrganizationSidCase2() throws SQLException { MockingService mocks = new MockingService(); Organization organization = returnValidOrganization(mocks); returnDefaultProfile(mocks); Profile resultantProfile = mocks.profileService.retrieveEffectiveProfileByOrganizationSid(organization.getSid()); assertEquals(Profile.DEFAULT_PROFILE_SID, resultantProfile.getSid()); } /** * case 1: given: a profile is explicitly assigned to an account * calling retrieveEffectiveProfileByAccountSid by account sid will return that profile * @throws SQLException */ @Test public void retrieveEffectiveProfileByAccountSidCase1() throws SQLException { MockingService mocks = new MockingService(); Account account = returnValidAccount(mocks); Profile expectedProfile = returnProfile(mocks); returnProfileAssociation(new Sid(expectedProfile.getSid()), account.getSid(), mocks); Profile resultantProfile = mocks.profileService.retrieveEffectiveProfileByAccountSid(account.getSid()); assertEquals(expectedProfile.getSid(), resultantProfile.getSid()); } /** * case 2: given: a profile is NOT explicitly assigned to an account, but its associated to its parent * calling retrieveEffectiveProfileByAccountSid by account sid will return that profile * @throws SQLException */ @Test public void retrieveEffectiveProfileByAccountSidCase2() throws SQLException { MockingService mocks = new MockingService(); Profile expectedProfile = returnProfile(mocks); Account account = returnValidAccountWithOnlyParentAssignedProfile(new Sid(expectedProfile.getSid()), mocks); Profile resultantProfile = mocks.profileService.retrieveEffectiveProfileByAccountSid(account.getSid()); assertEquals(expectedProfile.getSid(), resultantProfile.getSid()); } /** * case 3: given: a profile is NOT explicitly assigned to an account nor to its parent, but its associated to its grand parent * calling retrieveEffectiveProfileByAccountSid by account sid will return that profile * @throws SQLException */ @Test public void retrieveEffectiveProfileByAccountSidCase3() throws SQLException { MockingService mocks = new MockingService(); Profile expectedProfile = returnProfile(mocks); Account account = returnValidAccountWithOnlyGrandParentAssignedProfile(new Sid(expectedProfile.getSid()), mocks); Profile resultantProfile = mocks.profileService.retrieveEffectiveProfileByAccountSid(account.getSid()); assertEquals(expectedProfile.getSid(), resultantProfile.getSid()); } /** * case 4: given: a profile is NOT explicitly assigned to an account nor to its parent or grand parent, but its associated to its organization * calling retrieveEffectiveProfileByAccountSid by account sid SHOULD return that profile * @throws SQLException */ @Test public void retrieveEffectiveProfileByAccountSidCase4() throws SQLException { MockingService mocks = new MockingService(); Profile expectedProfile = returnProfile(mocks); Account account = returnValidAccountWitOrganizationAssignedProfile(new Sid(expectedProfile.getSid()), mocks); Profile resultantProfile = mocks.profileService.retrieveEffectiveProfileByAccountSid(account.getSid()); assertEquals(expectedProfile.getSid(), resultantProfile.getSid()); } /** * case 5: given: a profile is NOT explicitly assigned to an account nor to its parent, grand parent or organization: * calling retrieveEffectiveProfileByAccountSid by account sid SHOULD return DEFAULT profile * @throws SQLException */ @Test public void retrieveEffectiveProfileByAccountSidCase5() throws SQLException { MockingService mocks = new MockingService(); Account account = returnValidAccount(mocks); returnDefaultProfile(mocks); Profile resultantProfile = mocks.profileService.retrieveEffectiveProfileByAccountSid(account.getSid()); assertEquals(Profile.DEFAULT_PROFILE_SID, resultantProfile.getSid()); } /** * case 6: * </p>given 1: an account X is child of account Y. * </p>given 2: X belongs to organization XO. * </p>given 3: Y belongs to organization YO. (parent organization is different than child organization) * </p>given 4: profile A is associated to organization XO * </p>given 5: profile B is associated to organization YO * </p>When retrieveEffectiveProfileByAccountSid (X) should return A. * </p>calling retrieveEffectiveProfileByAccountSid by account sid SHOULD return that profile * @throws SQLException */ @Test public void retrieveEffectiveProfileByAccountSidCase6() throws SQLException { MockingService mocks = new MockingService(); Profile expectedParentOrganizationProfile = returnProfile(mocks); Profile expectedChildOrganizationProfile = returnProfile(mocks); Sid parentOrganizationSid = Sid.generate(Sid.Type.ORGANIZATION); Sid childOrganizationSid = Sid.generate(Sid.Type.ORGANIZATION); Sid acctSidParent = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builderParent = Account.builder(); builderParent.setSid(acctSidParent); builderParent.setOrganizationSid(parentOrganizationSid); Account accountParent = builderParent.build(); Sid acctSid = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builder = Account.builder(); builder.setSid(acctSid); builder.setOrganizationSid(childOrganizationSid); builder.setParentSid(acctSidParent); Account account = builder.build(); when (mocks.mockedAccountsDao.getAccount(acctSidParent)).thenReturn(accountParent); when (mocks.mockedAccountsDao.getAccount(acctSid)).thenReturn(account); returnProfileAssociation(new Sid(expectedParentOrganizationProfile.getSid()), parentOrganizationSid, mocks); returnProfileAssociation(new Sid(expectedChildOrganizationProfile.getSid()), childOrganizationSid, mocks); Profile resultantProfile = mocks.profileService.retrieveEffectiveProfileByAccountSid(account.getSid()); assertEquals(expectedChildOrganizationProfile.getSid(), resultantProfile.getSid()); } private Account returnValidAccount(MockingService mocks ) { Sid organizationSid = Sid.generate(Sid.Type.ORGANIZATION); Sid acctSidGrandParent = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builderGParent = Account.builder(); builderGParent.setSid(acctSidGrandParent); builderGParent.setOrganizationSid(organizationSid); Account accountGrandParent = builderGParent.build(); Sid acctSidParent = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builderParent = Account.builder(); builderParent.setSid(acctSidParent); builderParent.setOrganizationSid(organizationSid); builderParent.setParentSid(acctSidGrandParent); Account accountParent = builderParent.build(); Sid acctSid = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builder = Account.builder(); builder.setSid(acctSid); builder.setOrganizationSid(organizationSid); builder.setParentSid(acctSidParent); Account account = builder.build(); when (mocks.mockedAccountsDao.getAccount(acctSidParent)).thenReturn(accountParent); when (mocks.mockedAccountsDao.getAccount(acctSidGrandParent)).thenReturn(accountGrandParent); when (mocks.mockedAccountsDao.getAccount(acctSid)).thenReturn(account); return account; } private Account returnValidAccountWitOrganizationAssignedProfile(Sid profileSid, MockingService mocks ) throws SQLException { Sid organizationSid = Sid.generate(Sid.Type.ORGANIZATION); Sid acctSidGrandParent = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builderGParent = Account.builder(); builderGParent.setSid(acctSidGrandParent); builderGParent.setOrganizationSid(organizationSid); Account accountGrandParent = builderGParent.build(); Sid acctSidParent = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builderParent = Account.builder(); builderParent.setSid(acctSidParent); builderParent.setOrganizationSid(organizationSid); builderParent.setParentSid(acctSidGrandParent); Account accountParent = builderParent.build(); Sid acctSid = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builder = Account.builder(); builder.setSid(acctSid); builder.setOrganizationSid(organizationSid); builder.setParentSid(acctSidParent); Account account = builder.build(); when (mocks.mockedAccountsDao.getAccount(acctSidGrandParent)).thenReturn(accountGrandParent); when (mocks.mockedAccountsDao.getAccount(acctSidParent)).thenReturn(accountParent); when (mocks.mockedAccountsDao.getAccount(acctSid)).thenReturn(account); returnProfileAssociation(profileSid, organizationSid, mocks); return account; } private Account returnValidAccountWithOnlyGrandParentAssignedProfile(Sid profileSid, MockingService mocks ) throws SQLException { Sid organizationSid = Sid.generate(Sid.Type.ORGANIZATION); Sid acctSidGrandParent = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builderGParent = Account.builder(); builderGParent.setSid(acctSidGrandParent); builderGParent.setOrganizationSid(organizationSid); Account accountGrandParent = builderGParent.build(); Sid acctSidParent = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builderParent = Account.builder(); builderParent.setSid(acctSidParent); builderParent.setOrganizationSid(organizationSid); builderParent.setParentSid(acctSidGrandParent); Account accountParent = builderParent.build(); Sid acctSid = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builder = Account.builder(); builder.setSid(acctSid); builder.setOrganizationSid(organizationSid); builder.setParentSid(acctSidParent); Account account = builder.build(); when (mocks.mockedAccountsDao.getAccount(acctSidParent)).thenReturn(accountParent); when (mocks.mockedAccountsDao.getAccount(acctSidGrandParent)).thenReturn(accountGrandParent); when (mocks.mockedAccountsDao.getAccount(acctSid)).thenReturn(account); returnProfileAssociation(profileSid, acctSidGrandParent, mocks); return account; } private Account returnValidAccountWithOnlyParentAssignedProfile(Sid profileSid, MockingService mocks ) throws SQLException { Sid organizationSid = Sid.generate(Sid.Type.ORGANIZATION); Sid acctSidParent = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builderParent = Account.builder(); builderParent.setSid(acctSidParent); builderParent.setOrganizationSid(organizationSid); Account accountParent = builderParent.build(); Sid acctSid = Sid.generate(Sid.Type.ACCOUNT); Account.Builder builder = Account.builder(); builder.setSid(acctSid); builder.setOrganizationSid(organizationSid); builder.setParentSid(acctSidParent); Account account = builder.build(); when (mocks.mockedAccountsDao.getAccount(acctSidParent)).thenReturn(accountParent); when (mocks.mockedAccountsDao.getAccount(acctSid)).thenReturn(account); returnProfileAssociation(profileSid, acctSidParent, mocks); return account; } private Organization returnValidOrganization(MockingService mocks ) { Sid organizationSid = Sid.generate(Sid.Type.ORGANIZATION); Organization.Builder builder = Organization.builder(); builder.setSid(organizationSid); builder.setDomainName("test"); Organization organization = builder.build(); return organization; } private ProfileAssociation returnProfileAssociation(Sid profileSid, Sid targetSid, MockingService mocks ) throws SQLException { ProfileAssociation assoc = new ProfileAssociation(profileSid, targetSid, null, null); when (mocks.mockedProfileAssociationsDao.getProfileAssociationByTargetSid(targetSid.toString())). thenReturn(assoc); return assoc; } private Profile returnDefaultProfile(MockingService mocks ) throws SQLException { Profile profile = new Profile(Profile.DEFAULT_PROFILE_SID, "{}", null, null); when (mocks.mockedProfilesDao.getProfile(profile.getSid())). thenReturn(profile); return profile; } private Profile returnProfile(MockingService mocks ) throws SQLException { Profile profile = new Profile(Sid.generate(Sid.Type.PROFILE).toString(), "{}", null, null); when (mocks.mockedProfilesDao.getProfile(profile.getSid())).thenReturn(profile); return profile; } class MockingService { ServletContext mockedServletContext = Mockito.mock(ServletContext.class); DaoManager mockedDaoManager = Mockito.mock(DaoManager.class); OrganizationsDao mockedOrganizationsDao = Mockito.mock(OrganizationsDao.class); AccountsDao mockedAccountsDao = Mockito.mock(AccountsDao.class); ProfilesDao mockedProfilesDao = Mockito.mock(ProfilesDao.class); ProfileAssociationsDao mockedProfileAssociationsDao = Mockito.mock(ProfileAssociationsDao.class); ProfileService profileService; public MockingService() { when(mockedServletContext.getAttribute(DaoManager.class.getName())). thenReturn(mockedDaoManager); when(mockedDaoManager.getProfileAssociationsDao()).thenReturn(mockedProfileAssociationsDao); when(mockedDaoManager.getProfilesDao()).thenReturn(mockedProfilesDao); when(mockedDaoManager.getAccountsDao()).thenReturn(mockedAccountsDao); when(mockedDaoManager.getAccountsDao()).thenReturn(mockedAccountsDao); profileService = new ProfileServiceImpl(mockedDaoManager); } } }
18,839
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UriUtilsTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/test/java/org/restcomm/connect/core/service/util/UriUtilsTest.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.core.service.util; import org.apache.commons.configuration.XMLConfiguration; import org.junit.Assert; import org.junit.Test; import org.restcomm.connect.commons.HttpConnector; import org.restcomm.connect.commons.HttpConnectorList; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.JBossConnectorDiscover; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.OrganizationsDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Organization; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MalformedObjectNameException; import javax.management.ReflectionException; import java.net.URI; import java.net.URL; import java.net.UnknownHostException; import java.util.Arrays; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class UriUtilsTest { DaoManager daoManager = mock(DaoManager.class); AccountsDao accountsDao = mock(AccountsDao.class); OrganizationsDao organizationsDao = mock(OrganizationsDao.class); Account account = mock(Account.class); Organization organization = mock(Organization.class); JBossConnectorDiscover jBossConnectorDiscover = mock(JBossConnectorDiscover.class); UriUtils uriUtils = new UriUtils(daoManager, jBossConnectorDiscover, false); Sid orgSid = new Sid("ORafbe225ad37541eba518a74248f0ac4c"); @Test public void testResolveWithBase() { URI relativeUri = URI.create("/restcomm/recording.wav"); URI baseUri = URI.create("http://127.0.0.1:8080"); Assert.assertEquals("http://127.0.0.1:8080/restcomm/recording.wav", uriUtils.resolveWithBase(baseUri, relativeUri).toString()); } @Test public void testResolveRelativeUrlWithAccount() throws MalformedObjectNameException, UnknownHostException, InstanceNotFoundException, AttributeNotFoundException, MBeanException, ReflectionException { String domainName = "amazing.restcomm.com"; HttpConnector httpConnector = new HttpConnector("http","127.0.0.1", 8080, false); HttpConnectorList httpConnectorList = new HttpConnectorList(Arrays.asList(new HttpConnector[]{httpConnector})); when(jBossConnectorDiscover.findConnectors()).thenReturn(httpConnectorList); when(daoManager.getAccountsDao()).thenReturn(accountsDao); when(daoManager.getOrganizationsDao()).thenReturn(organizationsDao); when(accountsDao.getAccount(any(Sid.class))).thenReturn(account); when(account.getOrganizationSid()).thenReturn(orgSid); when(organizationsDao.getOrganization(orgSid)).thenReturn(organization); when(organization.getDomainName()).thenReturn(domainName); URI relativeUri = URI.create("/restcomm/recording.wav"); Assert.assertEquals("http://amazing.restcomm.com:8080/restcomm/recording.wav", uriUtils.resolve(relativeUri, Sid.generate(Sid.Type.ACCOUNT)).toString()); } @Test public void testResolveRelativeUrl() throws Exception { URL url = this.getClass().getResource("/restcomm.xml"); XMLConfiguration xml = new XMLConfiguration(); xml.setDelimiterParsingDisabled(true); xml.setAttributeSplittingDisabled(true); xml.load(url); RestcommConfiguration conf = new RestcommConfiguration(xml); String domainName = "amazing.restcomm.com"; HttpConnector httpConnector = new HttpConnector("http","127.0.0.1", 8080, false); HttpConnectorList httpConnectorList = new HttpConnectorList(Arrays.asList(new HttpConnector[]{httpConnector})); when(jBossConnectorDiscover.findConnectors()).thenReturn(httpConnectorList); URI relativeUri = URI.create("/restcomm/recording.wav"); Assert.assertEquals("http://127.0.0.1:8080/restcomm/recording.wav", uriUtils.resolve(relativeUri).toString()); } }
5,052
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommConnectServiceProvider.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/RestcommConnectServiceProvider.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.core.service; import javax.servlet.ServletContext; import org.restcomm.connect.commons.amazonS3.S3AccessTool; import org.restcomm.connect.core.service.api.ClientPasswordHashingService; import org.restcomm.connect.core.service.api.NumberSelectorService; import org.restcomm.connect.core.service.api.ProfileService; import org.restcomm.connect.core.service.api.RecordingService; import org.restcomm.connect.core.service.client.ClientPasswordHashingServiceImpl; import org.restcomm.connect.core.service.number.NumberSelectorServiceImpl; import org.restcomm.connect.core.service.profile.ProfileServiceImpl; import org.restcomm.connect.core.service.recording.RecordingsServiceImpl; import org.restcomm.connect.core.service.util.UriUtils; import org.restcomm.connect.dao.DaoManager; import scala.concurrent.ExecutionContext; /** * @author [email protected] * @author Maria */ public class RestcommConnectServiceProvider { private static RestcommConnectServiceProvider instance = null; // core services private NumberSelectorService numberSelector; private ProfileService profileService; private ClientPasswordHashingService clientPasswordHashingService; private RecordingService recordingService; private UriUtils uriUtils; public static RestcommConnectServiceProvider getInstance() { if (instance == null) { instance = new RestcommConnectServiceProvider(); } return instance; } /** * @param ctx */ public void startServices(ServletContext ctx) { DaoManager daoManager = (DaoManager) ctx.getAttribute(DaoManager.class.getName()); // core services initialization this.numberSelector = new NumberSelectorServiceImpl(daoManager.getIncomingPhoneNumbersDao()); ctx.setAttribute(NumberSelectorService.class.getName(), numberSelector); this.profileService = new ProfileServiceImpl(daoManager); ctx.setAttribute(ProfileService.class.getName(), profileService); this.clientPasswordHashingService = new ClientPasswordHashingServiceImpl(daoManager); ctx.setAttribute(ClientPasswordHashingService.class.getName(), clientPasswordHashingService); S3AccessTool s3AccessTool = (S3AccessTool) ctx.getAttribute(S3AccessTool.class.getName()); ExecutionContext ec = (ExecutionContext) ctx.getAttribute(ExecutionContext.class.getName()); this.uriUtils = new UriUtils(daoManager); ctx.setAttribute(UriUtils.class.getName(), uriUtils); this.recordingService = new RecordingsServiceImpl(daoManager.getRecordingsDao(), s3AccessTool, ec, uriUtils); ctx.setAttribute(RecordingService.class.getName(), recordingService); } /** * @return */ public NumberSelectorService provideNumberSelectorService() { return numberSelector; } /** * @return */ public ProfileService provideProfileService() { return profileService; } /** * @return */ public ClientPasswordHashingService clientPasswordHashingService() { return clientPasswordHashingService; } /** * @return */ public RecordingService recordingService() { return recordingService; } /** * * @return */ public UriUtils uriUtils() { return uriUtils; } //Used for unit testing - not elegant way though public void setUriUtils(UriUtils uriUtils) { this.uriUtils = uriUtils; } }
4,314
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NumberSelectorServiceImpl.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/number/NumberSelectorServiceImpl.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.core.service.number; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.api.NumberSelectorService; import org.restcomm.connect.core.service.number.api.NumberSelectionResult; import org.restcomm.connect.core.service.number.api.ResultType; import org.restcomm.connect.core.service.number.api.SearchModifier; import org.restcomm.connect.dao.IncomingPhoneNumbersDao; import org.restcomm.connect.dao.entities.IncomingPhoneNumber; import org.restcomm.connect.dao.entities.IncomingPhoneNumberFilter; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; /** * This Service will be used in different protocol scenarios to find if some * application is associated to the incoming session/number. * * Different queries to IncomingPhoneNumbersDao will be performed to try * locating the proper application. * * * Is expected that protocol scenario will provide meaningful Organization * details for source and destination. If protocol doesnt support Organizations * yet, then null values are allowed, but Regexes will not be evaluated in these * cases. */ public class NumberSelectorServiceImpl implements NumberSelectorService { private static Logger logger = Logger.getLogger(NumberSelectorServiceImpl.class); private IncomingPhoneNumbersDao numbersDao; public NumberSelectorServiceImpl(IncomingPhoneNumbersDao numbersDao) { this.numbersDao = numbersDao; } /** * * @param phone the original incoming phone number * @return a list of strings to match number based on different formats */ private List<String> createPhoneQuery(String phone) { List<String> numberQueries = new ArrayList<String>(10); //add the phone itself like it is first numberQueries.add(phone); //try adding US format if number doesnt contain *# if (!(phone.contains("*") || phone.contains("#"))) { try { // Format the destination to an E.164 phone number. final PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance(); String usFormatNum = phoneNumberUtil.format(phoneNumberUtil.parse(phone, "US"), PhoneNumberUtil.PhoneNumberFormat.E164); if (!numberQueries.contains(usFormatNum)) { if (logger.isDebugEnabled()) { logger.debug("Adding US Format num to queries:" + usFormatNum); } numberQueries.add(usFormatNum); } } catch (NumberParseException e) { //logger.error("Exception when try to format : " + e); } } //here we deal with different + prefix scnearios. //different providers will trigger calls with different formats //basiaclly we try with a leading + if original number doesnt have it, //and remove it if it has it. if (phone.startsWith("+")) { //remove the (+) and check if exists String noPlusNum = phone.replaceFirst("\\+", ""); if (!numberQueries.contains(noPlusNum)) { if (logger.isDebugEnabled()) { logger.debug("Adding No Plus Num:" + noPlusNum); } numberQueries.add(noPlusNum); } } else { String plusNum = "+".concat(phone); if (!numberQueries.contains(plusNum)) { if (logger.isDebugEnabled()) { logger.debug("Adding Plus Num:" + plusNum); } numberQueries.add(plusNum); } } return numberQueries; } /** * Here we expect a perfect match in DB. * * Several rules regarding organization scoping will be applied in the DAO * filter to ensure only applicable numbers in DB are retrieved. * * @param number the number to match against IncomingPhoneNumbersDao * @param sourceOrganizationSid * @param destinationOrganizationSid * @return the matched number, null if not matched. */ private NumberSelectionResult findSingleNumber(String number, Sid sourceOrganizationSid, Sid destinationOrganizationSid, Set<SearchModifier> modifiers) { NumberSelectionResult matchedNumber = new NumberSelectionResult(null, false, null); IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); filterBuilder.byPhoneNumber(number); int unfilteredCount = numbersDao.getTotalIncomingPhoneNumbers(filterBuilder.build()); if (unfilteredCount > 0) { if (destinationOrganizationSid != null) { filterBuilder.byOrgSid(destinationOrganizationSid.toString()); } else if ((modifiers != null) && (modifiers.contains(SearchModifier.ORG_COMPLIANT))){ //restrict search to non SIP numbers logger.debug("Organizations are null, restrict PureSIP numbers."); filterBuilder.byPureSIP(Boolean.FALSE); } //this rule forbids using PureSIP numbers if organizations doesnt match //this means only external provider numbers will be evaluated in DB if (sourceOrganizationSid != null && !sourceOrganizationSid.equals(destinationOrganizationSid)) { filterBuilder.byPureSIP(Boolean.FALSE); } IncomingPhoneNumberFilter numFilter = filterBuilder.build(); if (logger.isDebugEnabled()) { logger.debug("Searching with filter:" + numFilter); } List<IncomingPhoneNumber> matchedNumbers = numbersDao.getIncomingPhoneNumbersByFilter(numFilter); if (logger.isDebugEnabled()) { logger.debug("Num of results:" + matchedNumbers.size() + ".unfilteredCount:" + unfilteredCount); } //we expect a perfect match, so first result taken if (matchedNumbers != null && matchedNumbers.size() > 0) { if (logger.isDebugEnabled()) { logger.debug("Matched number with filter:" + matchedNumbers.get(0).toString()); } matchedNumber = new NumberSelectionResult(matchedNumbers.get(0), Boolean.FALSE, ResultType.REGULAR); } else { //without organization fileter we had results,so this is //marked as filtered by organization matchedNumber.setOrganizationFiltered(Boolean.TRUE); } } return matchedNumber; } /** * Iterates over the list of given numbers, and returns the first matching. * * @param numberQueries the list of numbers to attempt * @param sourceOrganizationSid * @param destinationOrganizationSid * @return the matched number, null if not matched. */ private NumberSelectionResult findByNumber(List<String> numberQueries, Sid sourceOrganizationSid, Sid destinationOrganizationSid, Set<SearchModifier> modifiers) { Boolean orgFiltered = false; NumberSelectionResult matchedNumber = new NumberSelectionResult(null, orgFiltered, null); int i = 0; while (matchedNumber.getNumber() == null && i < numberQueries.size()) { matchedNumber = findSingleNumber(numberQueries.get(i), sourceOrganizationSid, destinationOrganizationSid, modifiers); //preserve the orgFiltered flag along the queries if (matchedNumber.getOrganizationFiltered()) { orgFiltered = true; } i = i + 1; } matchedNumber.setOrganizationFiltered(orgFiltered); return matchedNumber; } /** * @param phone * @param sourceOrganizationSid * @param destinationOrganizationSid * @return */ @Override public IncomingPhoneNumber searchNumber(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid) { return searchNumber(phone, sourceOrganizationSid, destinationOrganizationSid, new HashSet<>(Arrays.asList(SearchModifier.ORG_COMPLIANT))); } /** * @param phone * @param sourceOrganizationSid * @param destinationOrganizationSid * @param modifiers * @return */ @Override public IncomingPhoneNumber searchNumber(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid, Set<SearchModifier> modifiers) { NumberSelectionResult searchNumber = searchNumberWithResult(phone, sourceOrganizationSid, destinationOrganizationSid, modifiers); return searchNumber.getNumber(); } /** * * @param result whether the call should be rejected depending on results * found * @param srcOrg * @param destOrg * @return */ @Override public boolean isFailedCall(NumberSelectionResult result, Sid srcOrg, Sid destOrg) { boolean failCall = false; if (result.getNumber() == null) { if (!destOrg.equals(srcOrg) && result.getOrganizationFiltered()) { failCall = true; } } return failCall; } /** * The main logic is: -Find a perfect match in DB using different formats. * -If not matched, use available Regexes in the organization. -If not * matched, try with the special * match. * * @param phone * @param sourceOrganizationSid * @param destinationOrganizationSid * @return */ @Override public NumberSelectionResult searchNumberWithResult(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid){ return searchNumberWithResult(phone, sourceOrganizationSid, destinationOrganizationSid, new HashSet<>(Arrays.asList(SearchModifier.ORG_COMPLIANT))); } /** * The main logic is: -Find a perfect match in DB using different formats. * -If not matched, use available Regexes in the organization. -If not * matched, try with the special * match. * * @param phone * @param sourceOrganizationSid * @param destinationOrganizationSid * @param modifiers * @return */ @Override public NumberSelectionResult searchNumberWithResult(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid, Set<SearchModifier> modifiers) { if (logger.isDebugEnabled()) { logger.debug("getMostOptimalIncomingPhoneNumber: " + phone + ",srcOrg:" + sourceOrganizationSid + ",destOrg:" + destinationOrganizationSid); } List<String> numberQueries = createPhoneQuery(phone); NumberSelectionResult numberfound = findByNumber(numberQueries, sourceOrganizationSid, destinationOrganizationSid, modifiers); if (numberfound.getNumber() == null) { //only use regex if perfect match didnt worked if (destinationOrganizationSid != null && (sourceOrganizationSid == null || destinationOrganizationSid.equals(sourceOrganizationSid)) && phone.matches("[\\d,*,#,+]+")) { //check regex if source and dest orgs are the same //only use regex if org available //check if there is a Regex match only if parameter is a String aka phone Number NumberSelectionResult regexFound = findByRegex(numberQueries, sourceOrganizationSid, destinationOrganizationSid); if (regexFound.getNumber() != null) { numberfound = regexFound; } if (numberfound.getNumber() == null) { //if no regex match found, try with special star number in the end NumberSelectionResult starfound = findSingleNumber("*", sourceOrganizationSid, destinationOrganizationSid, modifiers); if (starfound.getNumber() != null) { numberfound = new NumberSelectionResult(starfound.getNumber(), false, ResultType.REGEX); } } } } if (numberfound.getNumber() == null) { if (logger.isDebugEnabled()) { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("NumberSelectionService didn't match a number because: "); if (destinationOrganizationSid == null) { stringBuffer.append(" - Destination Org is null - "); } else if (sourceOrganizationSid != null && !destinationOrganizationSid.equals(sourceOrganizationSid)) { stringBuffer.append(" - Source Org is NOT null and DOESN'T match the Destination Org - "); } else if (!phone.matches("[\\d,*,#,+]+")) { String msg = String.format(" - Phone %s doesn't match regex \"[\\\\d,*,#,+]+\" - ", phone); stringBuffer.append(msg); } else { String msg = String.format(" - Phone %s didn't match any of the Regex - ",phone); stringBuffer.append(msg); } logger.debug(stringBuffer.toString()); } } return numberfound; } /** * Used to order a collection by the size of PhoneNumber String */ class NumberLengthComparator implements Comparator<IncomingPhoneNumber> { @Override public int compare(IncomingPhoneNumber o1, IncomingPhoneNumber o2) { //put o2 first to make longest first in coll int comparison = Integer.compare(o2.getPhoneNumber().length(), o1.getPhoneNumber().length()); return comparison == 0 ? -1 : comparison; } } /** * This will take the regexes available in given organization, and evalute * them agsint the given list of numbers, returning the first match. * * The list of regexes will be ordered by length to ensure the longest * regexes matching any number in the list is returned first. * * In this case, organization details are required. * * @param numberQueries * @param sourceOrganizationSid * @param destOrg * @return the longest regex matching any number in the list, null if no * match */ private NumberSelectionResult findByRegex(List<String> numberQueries, Sid sourceOrganizationSid, Sid destOrg) { NumberSelectionResult numberFound = new NumberSelectionResult(null, false, null); IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); filterBuilder.byOrgSid(destOrg.toString()); filterBuilder.byPureSIP(Boolean.TRUE); List<IncomingPhoneNumber> regexList = numbersDao.getIncomingPhoneNumbersRegex(filterBuilder.build()); if (logger.isDebugEnabled()) { logger.debug(String.format("Found %d Regex IncomingPhone numbers.", regexList.size())); } //order by regex length Set<IncomingPhoneNumber> regexSet = new TreeSet<IncomingPhoneNumber>(new NumberLengthComparator()); regexSet.addAll(regexList); if (regexList != null && regexList.size() > 0) { NumberSelectionResult matchingRegex = findFirstMatchingRegex(numberQueries, regexSet); if (matchingRegex.getNumber() != null) { numberFound = matchingRegex; } } return numberFound; } /** * * @param numberQueries the list of numbers to be matched * @param regexSet The set of regexes to evaluate against given numbers * @return the first regex matching any number in list, null if no match */ private NumberSelectionResult findFirstMatchingRegex(List<String> numberQueries, Set<IncomingPhoneNumber> regexSet ) { NumberSelectionResult matchedRegex = new NumberSelectionResult(null, false, null); try { Iterator<IncomingPhoneNumber> iterator = regexSet.iterator(); while (matchedRegex.getNumber() == null && iterator.hasNext()) { IncomingPhoneNumber currentRegex = iterator.next(); String phoneRegexPattern = null; //here we perform string replacement to allow proper regex compilation if (currentRegex.getPhoneNumber().startsWith("+")) { //ensures leading + sign is interpreted as expected char phoneRegexPattern = currentRegex.getPhoneNumber().replace("+", "/+"); } else if (currentRegex.getPhoneNumber().startsWith("*")) { //ensures leading * sign is interpreted as expected char phoneRegexPattern = currentRegex.getPhoneNumber().replace("*", "/*"); } else { phoneRegexPattern = currentRegex.getPhoneNumber(); } Pattern p = Pattern.compile(phoneRegexPattern); int i = 0; //we evalute the current regex to the list of incoming numbers //we stop as soon as a match is found while (matchedRegex.getNumber() == null && i < numberQueries.size()) { Matcher m = p.matcher(numberQueries.get(i)); if (m.find()) { //match found, exit from loops and return matchedRegex = new NumberSelectionResult(currentRegex, false, ResultType.REGEX); } else if (logger.isInfoEnabled()) { String msg = String.format("Regex \"%s\" cannot be matched for phone number \"%s\"", phoneRegexPattern, numberQueries.get(i)); logger.info(msg); } i = i + 1; } } } catch (Exception e) { if (logger.isDebugEnabled()) { String msg = String.format("Exception while trying to match for a REGEX, exception: %s", e); logger.debug(msg); } } if (matchedRegex.getNumber() == null) { logger.info("No matching phone number found, make sure your Restcomm Regex phone number is correctly defined"); } return matchedRegex; } }
19,538
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SearchModifier.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/number/api/SearchModifier.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.core.service.number.api; /** * @author [email protected] (Maria Farooq) */ public enum SearchModifier { ORG_COMPLIANT }
982
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ResultType.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/number/api/ResultType.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.core.service.number.api; public enum ResultType { REGULAR, REGEX, STAR; }
922
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NumberSelectionResult.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/number/api/NumberSelectionResult.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.core.service.number.api; import org.restcomm.connect.dao.entities.IncomingPhoneNumber; public class NumberSelectionResult { IncomingPhoneNumber number; Boolean organizationFiltered = false; ResultType type; public NumberSelectionResult(IncomingPhoneNumber number, Boolean organizationFiltered, ResultType type) { this.number = number; this.organizationFiltered = organizationFiltered; this.type = type; } public IncomingPhoneNumber getNumber() { return number; } public Boolean getOrganizationFiltered() { return organizationFiltered; } public void setOrganizationFiltered(Boolean organizationFiltered) { this.organizationFiltered = organizationFiltered; } public ResultType getType() { return type; } public void setType(ResultType type) { this.type = type; } }
1,737
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientPasswordHashingServiceImpl.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/client/ClientPasswordHashingServiceImpl.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.core.service.client; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.core.service.api.ClientPasswordHashingService; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Client; import java.util.HashMap; import java.util.List; import java.util.Map; public class ClientPasswordHashingServiceImpl implements ClientPasswordHashingService { private final DaoManager daoManager; public ClientPasswordHashingServiceImpl (DaoManager daoManager) { this.daoManager = daoManager; } @Override public Map<String, String> hashClientPassword (List<Client> clients, String domainName) { Map<String, String> migratedClients = new HashMap<>(); for (Client client: clients) { String newPasswordAlgorithm = hashClientPassword(client, domainName); if (newPasswordAlgorithm != null) { migratedClients.put(client.getSid().toString(), newPasswordAlgorithm); } } return migratedClients; } @Override public String hashClientPassword (Client client, String domainName) { if (client.getPasswordAlgorithm().equalsIgnoreCase(RestcommConfiguration.getInstance().getMain().getClearTextPasswordAlgorithm())) { client = client.setPassword(client.getLogin(), client.getPassword(), domainName); daoManager.getClientsDao().updateClient(client); return client.getPasswordAlgorithm(); } return null; } }
2,395
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NumberSelectorService.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/api/NumberSelectorService.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.core.service.api; import java.util.Set; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.number.api.NumberSelectionResult; import org.restcomm.connect.core.service.number.api.SearchModifier; import org.restcomm.connect.dao.entities.IncomingPhoneNumber; public interface NumberSelectorService { /** * @param phone * @param sourceOrganizationSid * @param destinationOrganizationSid * @return */ IncomingPhoneNumber searchNumber(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid); /** * @param phone * @param sourceOrganizationSid * @param destinationOrganizationSid * @param modifiers * @return */ IncomingPhoneNumber searchNumber(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid, Set<SearchModifier> modifiers); /** * The main logic is: -Find a perfect match in DB using different formats. * -If not matched, use available Regexes in the organization. -If not * matched, try with the special * match. * * @param phone * @param sourceOrganizationSid * @param destinationOrganizationSid * @return */ NumberSelectionResult searchNumberWithResult(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid); /** * The main logic is: -Find a perfect match in DB using different formats. * -If not matched, use available Regexes in the organization. -If not * matched, try with the special * match. * * @param phone * @param sourceOrganizationSid * @param destinationOrganizationSid * @param modifiers * @return */ NumberSelectionResult searchNumberWithResult(String phone, Sid sourceOrganizationSid, Sid destinationOrganizationSid, Set<SearchModifier> modifiers); /** * * @param result whether the call should be rejected depending on results * found * @param srcOrg * @param destOrg * @return */ boolean isFailedCall(NumberSelectionResult result, Sid srcOrg, Sid destOrg); }
2,988
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProfileService.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/api/ProfileService.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.core.service.api; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.Profile; public interface ProfileService { /** * @param accountSid * @return will return associated profile of provided account sid */ Profile retrieveEffectiveProfileByAccountSid(Sid accountSid); /** * @param organizationSid * @return will return associated profile of provided organization sid */ Profile retrieveEffectiveProfileByOrganizationSid(Sid organizationSid); /** * @param targetSid * @return will return explicitly associated profile of provided target (account or * organization) will return null if no profile is explicitly assigned to the target resource. */ Profile retrieveExplicitlyAssociatedProfile(Sid targetSid); }
1,669
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RecordingService.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/api/RecordingService.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.core.service.api; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.MediaAttributes; import java.net.URI; public interface RecordingService { /** * Upload recording file to Amazon S3 * @param recordingSid * @param mediaType * @return */ URI storeRecording(Sid recordingSid, MediaAttributes.MediaType mediaType); /** * Prepare Recording URL to store in the Recording.fileUrl property. * This will be used later to access the recording file * @param apiVersion * @param accountSid * @param recordingSid * @param mediaType * @return */ URI prepareFileUrl (String apiVersion, String accountSid, String recordingSid, MediaAttributes.MediaType mediaType); /** *Remove recording file from Amazon S3 * @param recordingSid */ void removeRecording(Sid recordingSid); }
1,757
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientPasswordHashingService.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/api/ClientPasswordHashingService.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.core.service.api; import org.restcomm.connect.dao.entities.Client; import java.util.List; import java.util.Map; public interface ClientPasswordHashingService { /** * Will hash the password of all clients in the provided List of Clients * @param clients * @return will return the List of Clients with hashed password */ Map<String, String> hashClientPassword(List<Client> clients, String domainName); /** * Will hash the password of the provided client * @param client * @return will return the Client with hashed password */ String hashClientPassword(Client client, String domainName); }
1,500
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RecordingsServiceImpl.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/recording/RecordingsServiceImpl.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.core.service.recording; import akka.dispatch.Futures; import org.apache.log4j.Logger; import org.restcomm.connect.commons.amazonS3.S3AccessTool; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.api.RecordingService; import org.restcomm.connect.core.service.util.UriUtils; import org.restcomm.connect.dao.RecordingsDao; import org.restcomm.connect.dao.entities.MediaAttributes; import org.restcomm.connect.dao.entities.Recording; import scala.concurrent.ExecutionContext; import scala.concurrent.Future; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.Callable; public class RecordingsServiceImpl implements RecordingService { private static Logger logger = Logger.getLogger(RecordingsServiceImpl.class); private final RecordingsDao recordingsDao; private final S3AccessTool s3AccessTool; private String recordingsPath; private final ExecutionContext ec; private final UriUtils uriUtils; public RecordingsServiceImpl (RecordingsDao recordingsDao, S3AccessTool s3AccessTool, ExecutionContext ec, UriUtils uriUtils) { this.recordingsDao = recordingsDao; this.s3AccessTool = s3AccessTool; this.recordingsPath = RestcommConfiguration.getInstance().getMain().getRecordingPath(); this.ec = ec; this.uriUtils = uriUtils; } //Used for unit testing public RecordingsServiceImpl (RecordingsDao recordingsDao, String recordingsPath, S3AccessTool s3AccessTool, ExecutionContext ec, UriUtils uriUtils) { this.recordingsDao = recordingsDao; this.s3AccessTool = s3AccessTool; this.recordingsPath = recordingsPath; this.ec = ec; this.uriUtils = uriUtils; } @Override public URI storeRecording (final Sid recordingSid, MediaAttributes.MediaType mediaType) { URI s3Uri = null; final String fileExtension = mediaType.equals(MediaAttributes.MediaType.AUDIO_ONLY) ? ".wav" : ".mp4"; Recording recording = recordingsDao.getRecording(recordingSid); if (s3AccessTool != null && ec != null) { s3Uri = s3AccessTool.getS3Uri(recordingsPath+"/"+recordingSid+fileExtension); Future<Boolean> f = Futures.future(new Callable<Boolean>() { @Override public Boolean call () throws Exception { return s3AccessTool.uploadFile(recordingsPath+"/"+recordingSid+fileExtension); } }, ec); } return s3Uri; } @Override public URI prepareFileUrl(String apiVersion, String accountSid, String recordingSid, MediaAttributes.MediaType mediaType) { final String fileExtension = mediaType.equals(MediaAttributes.MediaType.AUDIO_ONLY) ? ".wav" : ".mp4"; String fileUrl = String.format("/restcomm/%s/Accounts/%s/Recordings/%s",apiVersion,accountSid,recordingSid); URI uriToResolve = null; try { //For local stored recordings, add .wav/.mp4 suffix to the URI uriToResolve = new URI(fileUrl+fileExtension); } catch (URISyntaxException e) { logger.error(e); } return uriUtils.resolve(uriToResolve, new Sid(accountSid)); } @Override public void removeRecording (Sid recordingSid) { Recording recording = recordingsDao.getRecording(recordingSid); boolean isStoredAtS3 = recording.getS3Uri() != null; if (isStoredAtS3) { if (s3AccessTool != null) { s3AccessTool.removeS3Uri(recordingSid.toString()); } } else { if (!recordingsPath.endsWith("/")) recordingsPath += "/"; URI recordingsUri = URI.create(recordingsPath+recordingSid+".wav"); File fileToDelete = new File(recordingsUri); if (fileToDelete.exists()) { fileToDelete.delete(); } } recordingsDao.removeRecording(recordingSid); } }
4,948
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProfileServiceImpl.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/profile/ProfileServiceImpl.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.core.service.profile; import java.sql.SQLException; import org.apache.log4j.Logger; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.core.service.api.ProfileService; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Profile; import org.restcomm.connect.dao.entities.ProfileAssociation; public class ProfileServiceImpl implements ProfileService { private static Logger logger = Logger.getLogger(ProfileServiceImpl.class); private static String DEFAULT_PROFILE_SID = Profile.DEFAULT_PROFILE_SID; private final DaoManager daoManager; public ProfileServiceImpl(DaoManager daoManager) { super(); this.daoManager = daoManager; } /** * @param accountSid * @return will return associated profile of provided accountSid */ @Override public Profile retrieveEffectiveProfileByAccountSid(Sid accountSid) { Profile profile = null; Sid orginalRequestedAccount = accountSid; Sid currentAccount = accountSid; Account lastAccount = null; // try to find profile in account hierarchy do { profile = retrieveExplicitlyAssociatedProfile(currentAccount); if (profile == null) { lastAccount = daoManager.getAccountsDao().getAccount(currentAccount); if (lastAccount != null) { currentAccount = lastAccount.getParentSid(); } else { throw new RuntimeException("account not found!!!"); } } } while (profile == null && currentAccount != null); // if profile is not found in account hierarchy,try org if (profile == null) { Sid organizationSid = daoManager.getAccountsDao().getAccount(orginalRequestedAccount).getOrganizationSid(); profile = retrieveExplicitlyAssociatedProfile(organizationSid); } // finally try with default profile if (profile == null) { try { profile = daoManager.getProfilesDao().getProfile(DEFAULT_PROFILE_SID); } catch (SQLException ex) { throw new RuntimeException(ex); } } if (logger.isDebugEnabled()) { logger.debug("Returning profile:" + profile); } return profile; } /** * @param organizationSid * @return will return associated profile of provided organization sid */ public Profile retrieveEffectiveProfileByOrganizationSid(Sid organizationSid) { Profile profile = null; profile = retrieveExplicitlyAssociatedProfile(organizationSid); // finally try with default profile if (profile == null) { try { profile = daoManager.getProfilesDao().getProfile(DEFAULT_PROFILE_SID); } catch (SQLException ex) { throw new RuntimeException(ex); } } if (logger.isDebugEnabled()) { logger.debug("Returning profile:" + profile); } return profile; } /** * @param targetSid * @return will return associated profile of provided target (account or * organization) */ @Override public Profile retrieveExplicitlyAssociatedProfile(Sid targetSid) { ProfileAssociation assoc = daoManager.getProfileAssociationsDao().getProfileAssociationByTargetSid(targetSid.toString()); Profile profile = null; if (assoc != null) { try { profile = daoManager.getProfilesDao().getProfile(assoc.getProfileSid().toString()); } catch (SQLException ex) { throw new RuntimeException("problem retrieving profile", ex); } } if (logger.isDebugEnabled()) { logger.debug("Returning profile:" + profile); } return profile; } }
4,829
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UriUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.core/src/main/java/org/restcomm/connect/core/service/util/UriUtils.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.core.service.util; import org.apache.log4j.Logger; import org.restcomm.connect.commons.HttpConnector; import org.restcomm.connect.commons.HttpConnectorList; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.DNSUtils; import org.restcomm.connect.commons.util.JBossConnectorDiscover; import org.restcomm.connect.commons.util.TomcatConnectorDiscover; import org.restcomm.connect.dao.DaoManager; import java.net.InetAddress; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.Iterator; import java.util.List; /** * Utility class to manipulate URI. * * @author Henrique Rosa */ @ThreadSafe public class UriUtils { private Logger logger = Logger.getLogger(UriUtils.class); private HttpConnector selectedConnector = null; private DaoManager daoManager; private JBossConnectorDiscover jBossConnectorDiscover; private boolean useHostnameToResolve; /** * Default constructor. */ public UriUtils(final DaoManager daoManager) { this.daoManager = daoManager; jBossConnectorDiscover = new JBossConnectorDiscover(); useHostnameToResolve = RestcommConfiguration.getInstance().getMain().isUseHostnameToResolveRelativeUrls(); } public UriUtils(final DaoManager daoManager, final JBossConnectorDiscover jBossConnectorDiscover, boolean useHostnameToResolve) { this.daoManager = daoManager; this.jBossConnectorDiscover = jBossConnectorDiscover; this.useHostnameToResolve = useHostnameToResolve; } /** * Resolves a relative URI. * * @param base The base of the URI * @param uri The relative URI. * @return The absolute URI */ public URI resolveWithBase (final URI base, final URI uri) { if (base.equals(uri)) { return uri; } else if (!uri.isAbsolute()) { return base.resolve(uri); } else { return uri; } } /** * Will query different JMX MBeans for a list of runtime connectors. * * JBoss discovery will be used first, then Tomcat. * * * @return the list of connectors found */ private HttpConnectorList getHttpConnectors() throws Exception { logger.info("Searching HTTP connectors."); HttpConnectorList httpConnectorList = null; //find Jboss first as is typical setup httpConnectorList = jBossConnectorDiscover.findConnectors(); if (httpConnectorList == null || httpConnectorList.getConnectors().isEmpty()) { //if not found try tomcat httpConnectorList = new TomcatConnectorDiscover().findConnectors(); } return httpConnectorList; } /** * * Use to resolve a relative URI * using the instance hostname as base * * @param uri * @return */ public URI resolve(final URI uri) { return resolve(uri, null); } /** * Use to resolve a relative URI * using the domain name of the Organization * that the provided AccountSid belongs * * @param uri The relative URI * @param accountSid The accountSid to get the Org domain * @return The absolute URI */ public URI resolve(final URI uri, final Sid accountSid) { getHttpConnector(); String restcommAddress = null; if (accountSid != null && daoManager != null) { Sid organizationSid = daoManager.getAccountsDao().getAccount(accountSid).getOrganizationSid(); restcommAddress = daoManager.getOrganizationsDao().getOrganization(organizationSid).getDomainName(); } if (restcommAddress == null || restcommAddress.isEmpty()) { if (useHostnameToResolve) { restcommAddress = RestcommConfiguration.getInstance().getMain().getHostname(); if (restcommAddress == null || restcommAddress.isEmpty()) { try { InetAddress addr = DNSUtils.getByName(selectedConnector.getAddress()); restcommAddress = addr.getCanonicalHostName(); } catch (UnknownHostException e) { logger.error("Unable to resolveWithBase: " + selectedConnector + " to hostname: " + e); restcommAddress = selectedConnector.getAddress(); } } } else { restcommAddress = selectedConnector.getAddress(); } } String base = selectedConnector.getScheme() + "://" + restcommAddress + ":" + selectedConnector.getPort(); try { return resolveWithBase(new URI(base), uri); } catch (URISyntaxException e) { throw new IllegalArgumentException("Badly formed URI: " + base, e); } } /** * For historical reasons this method never returns null, and instead * throws a RuntimeException. * * TODO review all clients of this method to check for null instead of * throwing RuntimeException * * @return The selected connector with Secure preference. * @throws RuntimeException if no connector is found for some reason */ public HttpConnector getHttpConnector() throws RuntimeException { if (selectedConnector == null) { try { HttpConnectorList httpConnectorList = getHttpConnectors(); if (httpConnectorList != null && !httpConnectorList.getConnectors().isEmpty()) { List<HttpConnector> connectors = httpConnectorList.getConnectors(); Iterator<HttpConnector> iterator = connectors.iterator(); while (iterator.hasNext()) { HttpConnector connector = iterator.next(); //take secure conns with preference if (connector.isSecure()) { selectedConnector = connector; } } if (selectedConnector == null) { //if not secure,take the first one selectedConnector = connectors.get(0); } } if (selectedConnector == null) { //pervent logic to go further throw new RuntimeException("No HttpConnector found"); } } catch (Exception e) { throw new RuntimeException("Exception during HTTP Connectors discovery: ", e); } } return selectedConnector; } }
7,652
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AWSPollySpeechSyntetizerTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.awspolly/src/test/java/org/restcomm/connect/tts/awspolly/AWSPollySpeechSyntetizerTest.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.awspolly; 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.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; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * @author [email protected] (Ricardo Limonta) */ public final class AWSPollySpeechSyntetizerTest { private ActorSystem system; private ActorRef tts; private ActorRef cache; private String tempSystemDirectory; public AWSPollySpeechSyntetizerTest() throws ConfigurationException { super(); } @Before public void before() throws Exception { system = ActorSystem.create(); final URL input = getClass().getResource("/awspolly.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("ja")); assertTrue(languages.contains("tr-tr")); assertTrue(languages.contains("ru")); assertTrue(languages.contains("ro")); assertTrue(languages.contains("bp")); assertTrue(languages.contains("pt")); assertTrue(languages.contains("pl")); assertTrue(languages.contains("nl")); assertTrue(languages.contains("nb")); assertTrue(languages.contains("it")); assertTrue(languages.contains("is")); assertTrue(languages.contains("fr")); assertTrue(languages.contains("fr-ca")); assertTrue(languages.contains("es-mx")); assertTrue(languages.contains("es")); assertTrue(languages.contains("en-gb")); assertTrue(languages.contains("cy-gb")); assertTrue(languages.contains("en")); assertTrue(languages.contains("en-in")); assertTrue(languages.contains("en-gb")); assertTrue(languages.contains("en-au")); assertTrue(languages.contains("de")); assertTrue(languages.contains("da")); } }; } @SuppressWarnings("unchecked") @Test public void testSynthesisMan() { new JavaTestKit(system) { { final ActorRef observer = getRef(); String gender = "man"; String woman = "woman"; String language = "bp"; String message = "Bem vindo à plataforma Restcomm Connect!"; 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 testSynthesisWoman() { new JavaTestKit(system) { { final ActorRef observer = getRef(); String gender = "woman"; String language = "bp"; String message = "Bem vindo à plataforma Restcomm Connect!"; 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())); } }; } }
9,118
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AWSPollySpeechSyntetizer.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.awspolly/src/main/java/org/restcomm/connect/tts/awspolly/AWSPollySpeechSyntetizer.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.awspolly; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.services.polly.AmazonPollyClient; import com.amazonaws.services.polly.AmazonPollyClientBuilder; import com.amazonaws.services.polly.model.OutputFormat; import com.amazonaws.services.polly.model.SynthesizeSpeechRequest; import com.amazonaws.services.polly.model.SynthesizeSpeechResult; import com.amazonaws.services.polly.model.VoiceId; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.cache.HashGenerator; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.util.PcmToWavConverterUtils; 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.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.HashMap; import java.util.Map; /** * @author [email protected] (Ricardo Limonta) */ public class AWSPollySpeechSyntetizer extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private final AmazonPollyClient pollyClient; private final Map<String, String> men, women; public AWSPollySpeechSyntetizer(final Configuration configuration) { super(); // retrieve polly api credentials final String awsAccessKey = configuration.getString("aws-access-key"); final String awsSecretKey = configuration.getString("aws-secret-key"); final String awsRegion = configuration.getString("aws-region"); // Initialize the Amazon Cognito credentials provider. AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey); // Default region String region = "eu-west-1"; //AWS Specific Region if ((awsRegion != null) && (!"".equals(awsRegion))) { region = awsRegion; } // Create a client that supports generation of presigned URLs. this.pollyClient = (AmazonPollyClient) AmazonPollyClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withRegion(region) .build(); //initialize voice´s list men = new HashMap<>(); women = new HashMap<>(); load(configuration); } private void load(final Configuration configuration) throws RuntimeException { // Initialize female voices. women.put("ja", configuration.getString("speakers.ja-JP.female")); women.put("tr-tr", configuration.getString("speakers.tr-TR.female")); women.put("ru", configuration.getString("speakers.ru-RU.female")); women.put("ro", configuration.getString("speakers.ro-RO.female")); women.put("pt", configuration.getString("speakers.pt-PT.female")); women.put("bp", configuration.getString("speakers.pt-BR.female")); women.put("pl", configuration.getString("speakers.pl-PL.female")); women.put("nl", configuration.getString("speakers.nl-NL.female")); women.put("nb", configuration.getString("speakers.nb-NO.female")); women.put("it", configuration.getString("speakers.it-IT.female")); women.put("is", configuration.getString("speakers.is-IS.female")); women.put("fr", configuration.getString("speakers.fr-FR.female")); women.put("fr-ca", configuration.getString("speakers.fr-CA.female")); women.put("es-mx", configuration.getString("speakers.es-US.female")); women.put("es", configuration.getString("speakers.es-ES.female")); women.put("en-gb", configuration.getString("speakers.en-GB-WLS.female")); women.put("cy-gb", configuration.getString("speakers.cy-GB.female")); women.put("en", configuration.getString("speakers.en-US.female")); women.put("en-in", configuration.getString("speakers.en-IN.female")); women.put("en-gb", configuration.getString("speakers.en-GB.female")); women.put("en-ca", configuration.getString("speakers.en-GB.female")); women.put("en-au", configuration.getString("speakers.en-AU.female")); women.put("de", configuration.getString("speakers.de-DE.female")); women.put("da", configuration.getString("speakers.da-DK.female")); // Initialize male voices. men.put("ja", configuration.getString("speakers.ja-JP.male")); men.put("tr-tr", configuration.getString("speakers.tr-TR.male")); men.put("ru", configuration.getString("speakers.ru-RU.male")); men.put("ro", configuration.getString("speakers.ro-RO.male")); men.put("pt", configuration.getString("speakers.pt-PT.male")); men.put("bp", configuration.getString("speakers.pt-BR.male")); men.put("pl", configuration.getString("speakers.pl-PL.male")); men.put("nl", configuration.getString("speakers.nl-NL.male")); men.put("nb", configuration.getString("speakers.nb-NO.male")); men.put("it", configuration.getString("speakers.it-IT.male")); men.put("is", configuration.getString("speakers.is-IS.male")); men.put("fr", configuration.getString("speakers.fr-FR.male")); men.put("fr-ca", configuration.getString("speakers.fr-CA.male")); men.put("es-mx", configuration.getString("speakers.es-US.male")); men.put("es", configuration.getString("speakers.es-ES.male")); men.put("en-gb", configuration.getString("speakers.en-GB-WLS.male")); men.put("cy-gb", configuration.getString("speakers.cy-GB.male")); men.put("en", configuration.getString("speakers.en-US.male")); men.put("en-in", configuration.getString("speakers.en-IN.male")); men.put("en-gb", configuration.getString("speakers.en-GB.male")); men.put("en-ca", configuration.getString("speakers.en-GB.male")); men.put("en-au", configuration.getString("speakers.en-AU.male")); men.put("de", configuration.getString("speakers.de-DE.male")); men.put("da", configuration.getString("speakers.da-DK.male")); } @Override public void onReceive(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), self); } } catch (final IOException | SpeechSynthesizerException 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<>(new SpeechSynthesizerInfo(men.keySet())), self); } } private URI synthesize(final Object message) throws IOException, SpeechSynthesizerException { //retrieve resquest message final org.restcomm.connect.tts.api.SpeechSynthesizerRequest request = (org.restcomm.connect.tts.api.SpeechSynthesizerRequest) message; //retrieve gender, language and text message final String gender = request.gender(); final String language = request.language(); final String text = request.text(); //generate file hash name final String hash = HashGenerator.hashMessage(gender, language, 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()); } // Create speech synthesis request. SynthesizeSpeechRequest pollyRequest = new SynthesizeSpeechRequest().withText(text) .withVoiceId(VoiceId.valueOf(this.retrieveSpeaker(gender, language))) .withOutputFormat(OutputFormat.Pcm) .withSampleRate("8000"); //retrieve audio result SynthesizeSpeechResult result = pollyClient.synthesizeSpeech(pollyRequest); //create a temporary file File srcFile = new File(System.getProperty("java.io.tmpdir") + File.separator + hash + ".pcm"); File dstFile = new File(System.getProperty("java.io.tmpdir") + File.separator + hash + ".wav"); //save temporary pcm file Files.copy(result.getAudioStream(), srcFile.toPath(), StandardCopyOption.REPLACE_EXISTING); //convert pcm file to wav new PcmToWavConverterUtils().rawToWave(srcFile, dstFile); //return file URI return dstFile.toURI(); } private String retrieveSpeaker(final String gender, final String language) { String speaker = null; if ("woman".equalsIgnoreCase(gender)) { speaker = women.get(language); if (speaker == null || speaker.isEmpty()) { speaker = men.get(language); } } else { speaker = men.get(language); if (speaker == null || speaker.isEmpty()) { speaker = women.get(language); } } //if speaker not found, set default speaker to en-US woman if (speaker == null) { speaker = "Joanna"; } return speaker; } }
11,295
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoxbonePhoneNumberProvisioningManager.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.provisioning.number.voxbone/src/main/java/org/restcomm/connect/provisioning/number/voxbone/VoxbonePhoneNumberProvisioningManager.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.provisioning.number.voxbone; 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.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 com.google.gson.JsonArray; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.ClientResponse.Status; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; /** * @author [email protected] */ public class VoxbonePhoneNumberProvisioningManager implements PhoneNumberProvisioningManager { private static final Logger logger = Logger.getLogger(VoxbonePhoneNumberProvisioningManager.class); private static final String COUNTRY_CODE_PARAM = "countryCodeA3"; private static final String PAGE_SIZE = "pageSize"; private static final String PAGE_NUMBER = "pageNumber"; private static final String CONTENT_TYPE = "application/json"; protected Boolean telestaxProxyEnabled; protected String uri, username, password; protected String searchURI, createCartURI, voiceURI, updateURI, cancelURI, countriesURI, listDidsURI; protected String voiceUriId; protected Configuration activeConfiguration; protected ContainerConfiguration containerConfiguration; public VoxbonePhoneNumberProvisioningManager() {} /* * (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("username"); password = telestaxProxyConfiguration.getString("password"); activeConfiguration = telestaxProxyConfiguration; } else { Configuration voxboneConfiguration = phoneNumberProvisioningConfiguration.subset("voxbone"); uri = voxboneConfiguration.getString("uri"); username = voxboneConfiguration.getString("username"); password = voxboneConfiguration.getString("password"); activeConfiguration = voxboneConfiguration; } searchURI = uri + "/inventory/didgroup"; createCartURI = uri + "/ordering/cart"; voiceURI = uri + "/configuration/voiceuri"; updateURI = uri + "/configuration/configuration"; cancelURI = uri + "/ordering/cancel"; countriesURI = uri + "/inventory/country"; listDidsURI = uri + "/inventory/did"; Configuration callbackUrlsConfiguration = phoneNumberProvisioningConfiguration.subset("callback-urls"); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource webResource = jerseyClient.resource(voiceURI); String body = "{\"voiceUri\":{\"voiceUriProtocol\":\"SIP\",\"uri\":\"" + callbackUrlsConfiguration.getString("voice[@url]") + "\"}}"; ClientResponse clientResponse = webResource.accept(CONTENT_TYPE).type(CONTENT_TYPE).put(ClientResponse.class,body); String voiceURIResponse = clientResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("response " + voiceURIResponse); JsonParser parser = new JsonParser(); JsonObject jsonVoiceURIResponse = parser.parse(voiceURIResponse).getAsJsonObject(); if (clientResponse.getClientResponseStatus() == Status.OK) { JsonObject voxVoiceURI = jsonVoiceURIResponse.get("voiceUri").getAsJsonObject(); voiceUriId = voxVoiceURI.get("voiceUriId").getAsString(); } else if (clientResponse.getClientResponseStatus() == Status.UNAUTHORIZED) { JsonObject error = jsonVoiceURIResponse.get("errors").getAsJsonArray().get(0).getAsJsonObject(); throw new IllegalArgumentException(error.get("apiErrorMessage").getAsString()); } else { webResource = jerseyClient.resource(voiceURI); clientResponse = webResource.queryParam(PAGE_NUMBER,"0").queryParam(PAGE_SIZE,"300").accept(CONTENT_TYPE).type(CONTENT_TYPE).get(ClientResponse.class); String listVoiceURIResponse = clientResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("response " + listVoiceURIResponse ); JsonObject jsonListVoiceURIResponse = parser.parse(listVoiceURIResponse).getAsJsonObject(); // TODO go through the list of voiceURI id and check which one is matching JsonObject voxVoiceURI = jsonListVoiceURIResponse.get("voiceUris").getAsJsonArray().get(0).getAsJsonObject(); voiceUriId = voxVoiceURI.get("voiceUriId").getAsString(); } } 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(); if(Integer.parseInt(number.get("stock").toString()) > 0) { //we only return the number if there is any stock for it String countryCode = number.get(COUNTRY_CODE_PARAM).getAsString(); String features = null; if(number.get("features") != null) { features = number.get("features").toString(); } boolean isVoiceCapable = true; boolean isFaxCapable = false; boolean isSmsCapable = false; if(features.contains("VoxSMS")) { isSmsCapable = true; } if(features.contains("VoxFax")) { isFaxCapable = true; } String friendlyName = number.get("countryCodeA3").getAsString(); if(number.get("cityName") != null && !(number.get("cityName") instanceof JsonNull)) { friendlyName = friendlyName + "-" + number.get("cityName").getAsString(); } if(number.get("areaCode") != null && !(number.get("areaCode") instanceof JsonNull)) { friendlyName = friendlyName + "-" + number.get("areaCode").getAsString(); } final PhoneNumber phoneNumber = new PhoneNumber( friendlyName, number.get("didGroupId").getAsString(), null, null, null, null, null, null, countryCode, null, isVoiceCapable, isSmsCapable, null, isFaxCapable, 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) { Locale locale = new Locale("en",country); String iso3Country = locale.getISO3Country(); if(logger.isDebugEnabled()) { logger.debug("searchPattern " + listFilters.getFilterPattern()); } Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource webResource = jerseyClient.resource(searchURI); // https://developers.voxbone.com/docs/v3/inventory#path__didgroup.html webResource = webResource.queryParam(COUNTRY_CODE_PARAM,iso3Country); // Pattern filterPattern = listFilters.getFilterPattern(); // if(filterPattern != null) { // webResource = webResource.queryParam("cityNamePattern" , filterPattern.toString()); // } if(listFilters.getAreaCode() != null) { webResource = webResource.queryParam("areaCode", listFilters.getAreaCode()); } if(listFilters.getInRateCenter() != null) { webResource = webResource.queryParam("rateCenter", listFilters.getInRateCenter()); } if(listFilters.getSmsEnabled() != null) { webResource = webResource.queryParam("featureIds", "6"); } if(listFilters.getFaxEnabled() != null) { webResource = webResource.queryParam("featureIds", "25"); } if(listFilters.getRangeIndex() != -1) { webResource = webResource.queryParam(PAGE_NUMBER, "" + listFilters.getRangeIndex()); } else { webResource = webResource.queryParam(PAGE_NUMBER, "0"); } if(listFilters.getRangeSize() != -1) { webResource = webResource.queryParam(PAGE_SIZE, "" + listFilters.getRangeSize()); } else { webResource = webResource.queryParam(PAGE_SIZE, "50"); } ClientResponse clientResponse = webResource.accept(CONTENT_TYPE).type(CONTENT_TYPE) .get(ClientResponse.class); String response = clientResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("response " + response); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); // long count = jsonResponse.getAsJsonPrimitive("count").getAsLong(); // if(logger.isDebugEnabled()) { // logger.debug("Number of numbers found : "+count); // } JsonArray voxboneNumbers = jsonResponse.getAsJsonArray("didGroups"); final List<PhoneNumber> numbers = toAvailablePhoneNumbers(voxboneNumbers, listFilters); return numbers; // } else { // logger.warn("Couldn't reach uri for getting Phone Numbers. Response status was: "+response.getStatusLine().getStatusCode()); // } // // return new ArrayList<PhoneNumber>(); } @Override public boolean buyNumber(PhoneNumber phoneNumberObject, PhoneNumberParameters phoneNumberParameters) { String phoneNumber = phoneNumberObject.getPhoneNumber(); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource webResource = jerseyClient.resource(createCartURI); ClientResponse clientResponse = webResource.accept(CONTENT_TYPE).type(CONTENT_TYPE).put(ClientResponse.class,"{}"); String createCartResponse = clientResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("createCartResponse " + createCartResponse); JsonParser parser = new JsonParser(); JsonObject jsonCreateCartResponse = parser.parse(createCartResponse).getAsJsonObject(); JsonObject voxCart = jsonCreateCartResponse.get("cart").getAsJsonObject(); String cartIdentifier = voxCart.get("cartIdentifier").getAsString(); try { Client addToCartJerseyClient = Client.create(); addToCartJerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource addToCartWebResource = addToCartJerseyClient.resource(createCartURI + "/" + cartIdentifier + "/product"); String addToCartBody = "{\"didCartItem\":{\"didGroupId\":\"" + phoneNumber + "\",\"quantity\":\"1\"}}"; ClientResponse addToCartResponse = addToCartWebResource.accept(CONTENT_TYPE).type(CONTENT_TYPE).post(ClientResponse.class,addToCartBody); if (addToCartResponse.getClientResponseStatus() == Status.OK) { String addToCartResponseString = addToCartResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("addToCartResponse " + addToCartResponseString); JsonObject jsonAddToCartResponse = parser.parse(addToCartResponseString).getAsJsonObject(); if(jsonAddToCartResponse.get("status").getAsString().equalsIgnoreCase("SUCCESS")) { Client checkoutCartJerseyClient = Client.create(); checkoutCartJerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource checkoutCartWebResource = checkoutCartJerseyClient.resource(createCartURI + "/" + cartIdentifier + "/checkout"); ClientResponse checkoutCartResponse = checkoutCartWebResource.queryParam("cartIdentifier", cartIdentifier).accept(CONTENT_TYPE).type(CONTENT_TYPE).get(ClientResponse.class); if (checkoutCartResponse.getClientResponseStatus() == Status.OK) { String checkoutCartResponseString = checkoutCartResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("checkoutCartResponse " + checkoutCartResponseString); JsonObject jsonCheckoutCartResponse = parser.parse(checkoutCartResponseString).getAsJsonObject(); if(jsonCheckoutCartResponse.get("status").getAsString().equalsIgnoreCase("SUCCESS")) { String orderReference = jsonCheckoutCartResponse.get("productCheckoutList").getAsJsonArray().get(0).getAsJsonObject().get("orderReference").getAsString(); Client listDidsJerseyClient = Client.create(); listDidsJerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource listDidsWebResource = listDidsJerseyClient.resource(listDidsURI); ClientResponse listDidsResponse = listDidsWebResource. queryParam("orderReference", orderReference). queryParam(PAGE_NUMBER, "0"). queryParam(PAGE_SIZE, "50"). accept(CONTENT_TYPE). type(CONTENT_TYPE). get(ClientResponse.class); if (listDidsResponse.getClientResponseStatus() == Status.OK) { String listDidsResponseString = listDidsResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("listDidsResponse " + listDidsResponseString); JsonObject jsonListDidsResponse = parser.parse(listDidsResponseString).getAsJsonObject(); JsonObject dids = jsonListDidsResponse.get("dids").getAsJsonArray().get(0).getAsJsonObject(); String didId = dids.get("didId").getAsString(); String e164 = dids.get("e164").getAsString(); phoneNumberObject.setFriendlyName(didId); phoneNumberObject.setPhoneNumber(e164); updateNumber(phoneNumberObject, phoneNumberParameters); } else { return false; } } else { // Handle not enough credit on the account return false; } } else { return false; } // we always return true as the phone number was bought return true; } else { return false; } } else { if(logger.isDebugEnabled()) logger.debug("Couldn't buy Phone Number " + phoneNumber + ". Response status was: "+ addToCartResponse.getClientResponseStatus()); } } 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.getFriendlyName(); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource webResource = jerseyClient.resource(updateURI); String body = "{\"didIds\":[\"" + phoneNumber + "\"],\"voiceUriId\":\"" + voiceUriId + "\"}"; ClientResponse clientResponse = webResource.accept(CONTENT_TYPE).type(CONTENT_TYPE).post(ClientResponse.class,body); String voiceURIResponse = clientResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("response " + voiceURIResponse); // JsonParser parser = new JsonParser(); // JsonObject jsonCreateCartResponse = parser.parse(voiceURIResponse).getAsJsonObject(); if (clientResponse.getClientResponseStatus() == Status.OK) { return true; } else { return false; } } @Override public boolean cancelNumber(PhoneNumber phoneNumberObj) { String phoneNumber = phoneNumberObj.getFriendlyName(); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource webResource = jerseyClient.resource(cancelURI); String body = "{\"didIds\":[\"" + phoneNumber + "\"]}"; ClientResponse clientResponse = webResource.accept(CONTENT_TYPE).type(CONTENT_TYPE).post(ClientResponse.class,body); String response = clientResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("response " + response); // JsonParser parser = new JsonParser(); // JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); if (clientResponse.getClientResponseStatus() == Status.OK) { return true; } else { return false; } } @Override public List<String> getAvailableCountries() { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, password)); WebResource webResource = jerseyClient.resource(countriesURI); // http://www.voxbone.com/apidoc/resource_InventoryServiceRest.html#path__country.html ClientResponse clientResponse = webResource.queryParam(PAGE_NUMBER,"0").queryParam(PAGE_SIZE,"300").accept(CONTENT_TYPE).type(CONTENT_TYPE) .get(ClientResponse.class); String response = clientResponse.getEntity(String.class); if(logger.isDebugEnabled()) logger.debug("response " + response); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); JsonArray voxCountries = jsonResponse.get("countries").getAsJsonArray(); List<String> countries = new ArrayList<String>(); for (int i = 0; i < voxCountries.size(); i++) { JsonObject country = voxCountries.get(i).getAsJsonObject(); String countryCode = country.get(COUNTRY_CODE_PARAM).getAsString(); countries.add(countryCode); } return countries; } }
21,093
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConferenceMediaResourceControllerStateChanged.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb.api/src/main/java/org/restcomm/connect/mrb/api/ConferenceMediaResourceControllerStateChanged.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.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author Maria * */ @Immutable public class ConferenceMediaResourceControllerStateChanged { public enum MediaServerControllerState { INITIALIZED, ACTIVE, FAILED, INACTIVE; } private final MediaServerControllerState state; private final String conferenceState; private final boolean destroyEndpoint; private final boolean moderatorPresent; public ConferenceMediaResourceControllerStateChanged(MediaServerControllerState state, final String conferenceState, final boolean destroyEndpoint, final boolean moderatorPresent) { this.state = state; this.conferenceState = conferenceState; this.destroyEndpoint = destroyEndpoint; this.moderatorPresent = moderatorPresent; } public ConferenceMediaResourceControllerStateChanged(MediaServerControllerState state, final String conferenceState) { this(state, conferenceState, false, false); } public ConferenceMediaResourceControllerStateChanged(MediaServerControllerState state, final String conferenceState, final boolean moderatorPresent) { this(state, conferenceState, false, moderatorPresent); } public ConferenceMediaResourceControllerStateChanged(MediaServerControllerState state, final boolean destroyEndpoint) { this(state, null, destroyEndpoint, false); } public ConferenceMediaResourceControllerStateChanged(MediaServerControllerState state) { this(state, null, false, false); } public MediaServerControllerState state() { return state; } public String conferenceState() { return conferenceState; } public boolean destroyEndpoint (){ return destroyEndpoint; } public boolean moderatorPresent (){ return moderatorPresent; } }
2,822
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StopConferenceMediaResourceController.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb.api/src/main/java/org/restcomm/connect/mrb/api/StopConferenceMediaResourceController.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.mrb.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Maria Farooq) */ @Immutable public final class StopConferenceMediaResourceController { public StopConferenceMediaResourceController() { super(); } }
1,131
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StartMediaResourceBroker.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb.api/src/main/java/org/restcomm/connect/mrb/api/StartMediaResourceBroker.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.mrb.api; import akka.actor.ActorRef; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.dao.DaoManager; /** * @author [email protected] (Maria Farooq) */ @Immutable public final class StartMediaResourceBroker { private final Configuration configuration; private final DaoManager storage; private final ClassLoader loader; private final ActorRef monitoringService; public StartMediaResourceBroker(final Configuration configuration, final DaoManager storage, final ClassLoader loader, final ActorRef monitoringService) { super(); this.configuration = configuration; this.storage = storage; this.loader = loader; this.monitoringService = monitoringService; } public Configuration configuration(){ return this.configuration; } public DaoManager storage(){ return this.storage; } public ClassLoader loader(){ return this.loader; } public ActorRef getMonitoringService () { return monitoringService; } }
1,986
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MediaGatewayForConference.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb.api/src/main/java/org/restcomm/connect/mrb/api/MediaGatewayForConference.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.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.dao.Sid; import akka.actor.ActorRef; /** * @author Maria Farooq ([email protected]) */ @Immutable public final class MediaGatewayForConference { private final Sid conferenceSid; private final ActorRef mediaGateway; private final String masterConfernceEndpointIdName; private final boolean isThisMaster; public MediaGatewayForConference(final Sid conferenceSid, final ActorRef mediaGateway, final String masterConfernceEndpointIdName, final boolean isThisMaster) { super(); this.conferenceSid = conferenceSid; this.mediaGateway = mediaGateway; this.masterConfernceEndpointIdName = masterConfernceEndpointIdName; this.isThisMaster = isThisMaster; } public Sid conferenceSid() { return conferenceSid; } public ActorRef mediaGateway() { return mediaGateway; } public String masterConfernceEndpointIdName() { return masterConfernceEndpointIdName; } public boolean isThisMaster() { return isThisMaster; } @Override public String toString() { return "MediaGatewayForConference [conferenceSid=" + conferenceSid + ", mediaGateway=" + mediaGateway + ", masterConfernceEndpointIdName=" + masterConfernceEndpointIdName + ", isThisMaster=" + isThisMaster + "]"; } }
2,416
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StartConferenceMediaResourceController.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb.api/src/main/java/org/restcomm/connect/mrb/api/StartConferenceMediaResourceController.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.mrb.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.dao.Sid; import akka.actor.ActorRef; /** * @author [email protected] (Maria Farooq) */ @Immutable public final class StartConferenceMediaResourceController { private final ActorRef cnfEndpoint; private final Sid conferenceSid; public StartConferenceMediaResourceController(final ActorRef cnfEndpoint, final Sid conferenceSid) { super(); this.cnfEndpoint = cnfEndpoint; this.conferenceSid = conferenceSid; } public ActorRef cnfEndpoint() { return cnfEndpoint; } public Sid conferenceSid() { return conferenceSid; } }
1,561
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GetMediaGateway.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb.api/src/main/java/org/restcomm/connect/mrb/api/GetMediaGateway.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.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.dao.Sid; /** * @author Maria Farooq ([email protected]) */ @Immutable public final class GetMediaGateway { private final Sid callSid; private final String conferenceName; private final String msId; public GetMediaGateway(final Sid callSid, final String conferenceName, final String msId) { super(); this.callSid = callSid; this.conferenceName = conferenceName; this.msId = msId; } public GetMediaGateway(final Sid callSid){ this(callSid, null, null); } public GetMediaGateway(final String msId) { this(null, null, msId); } public Sid callSid() { return callSid; } public String conferenceName() { return conferenceName; } public String msId(){ return msId; } }
1,876
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GetConferenceMediaResourceController.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mrb.api/src/main/java/org/restcomm/connect/mrb/api/GetConferenceMediaResourceController.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.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author Maria Farooq ([email protected]) */ @Immutable public final class GetConferenceMediaResourceController { private final String conferenceName; public GetConferenceMediaResourceController(final String conferenceName) { super(); this.conferenceName = conferenceName; } public String getConferenceName() { return conferenceName; } }
1,430
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
InterfaxServiceTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.fax/src/test/java/org/restcomm/connect/fax/InterfaxServiceTest.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.fax; 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 akka.testkit.JavaTestKit; import java.io.File; 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.Ignore; import org.junit.Test; import scala.concurrent.duration.FiniteDuration; /** * @author [email protected] (Thomas Quintana) */ public final class InterfaxServiceTest { private ActorSystem system; private ActorRef interfax; public InterfaxServiceTest() { super(); } @Before public void before() throws Exception { system = ActorSystem.create(); final URL input = getClass().getResource("/interfax.xml"); final XMLConfiguration configuration = new XMLConfiguration(input); interfax = interfax(configuration); } @After public void after() throws Exception { system.shutdown(); } private ActorRef interfax(final Configuration configuration) { return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new InterfaxService(configuration); } })); } @Test @Ignore public void testSendFax() { new JavaTestKit(system) { { final ActorRef observer = getRef(); final File file = new File(getClass().getResource("/fax.pdf").getPath()); // This is the fax number for http://faxtoy.net/ final FaxRequest request = new FaxRequest("+18888771655", file); // This will fax "Welcome to RestComm!" to http://faxtoy.net/ interfax.tell(request, observer); final FaxResponse response = expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS), FaxResponse.class); assertTrue(response.succeeded()); System.out.println(response.get().toString()); } }; } }
3,199
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
FaxRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.fax/src/main/java/org/restcomm/connect/fax/FaxRequest.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.fax; import java.io.File; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class FaxRequest { private final String to; private final File file; public FaxRequest(final String to, final File file) { super(); this.to = to; this.file = file; } public String to() { return to; } public File file() { return file; } }
1,340
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
FaxResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.fax/src/main/java/org/restcomm/connect/fax/FaxResponse.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.fax; import java.net.URI; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class FaxResponse extends StandardResponse<URI> { public FaxResponse(final URI object) { super(object); } public FaxResponse(final Throwable cause) { super(cause); } public FaxResponse(final Throwable cause, final String message) { super(cause, message); } }
1,399
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
FaxServiceException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.fax/src/main/java/org/restcomm/connect/fax/FaxServiceException.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.fax; /** * @author [email protected] (Thomas Quintana) */ public final class FaxServiceException extends Exception { private static final long serialVersionUID = 1L; public FaxServiceException() { super(); } public FaxServiceException(final String message) { super(message); } public FaxServiceException(final Throwable cause) { super(cause); } public FaxServiceException(final String message, final Throwable cause) { super(message, cause); } }
1,369
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
InterfaxService.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.fax/src/main/java/org/restcomm/connect/fax/InterfaxService.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.fax; import akka.actor.ActorRef; import org.apache.commons.configuration.Configuration; import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.FileEntity; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import java.io.File; import java.net.URI; import java.net.URLConnection; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; /** * @author [email protected] (Thomas Quintana) */ public final class InterfaxService extends RestcommUntypedActor { private static final String url = "https://rest.interfax.net/outbound/faxes?faxNumber="; private final TrustStrategy strategy; private final String user; private final String password; public InterfaxService(final Configuration configuration) { super(); user = configuration.getString("user"); password = configuration.getString("password"); strategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }; } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (FaxRequest.class.equals(klass)) { try { sender.tell(new FaxResponse(send(message)), self); } catch (final Exception exception) { sender.tell(new FaxResponse(exception), self); } } } private URI send(final Object message) throws Exception { final FaxRequest request = (FaxRequest) message; final String to = request.to(); final File file = request.file(); // Prepare the request. final DefaultHttpClient client = new DefaultHttpClient(); final HttpContext context = new BasicHttpContext(); final SSLSocketFactory sockets = new SSLSocketFactory(strategy); final Scheme scheme = new Scheme("https", 443, sockets); client.getConnectionManager().getSchemeRegistry().register(scheme); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password); final HttpPost post = new HttpPost(url + to); final String mime = URLConnection.guessContentTypeFromName(file.getName()); final FileEntity entity = new FileEntity(file, mime); post.addHeader(new BasicScheme().authenticate(credentials, post, context)); post.setEntity(entity); // Handle the response. final HttpResponse response = client.execute(post, context); final StatusLine status = response.getStatusLine(); final int code = status.getStatusCode(); if (HttpStatus.SC_CREATED == code) { EntityUtils.consume(response.getEntity()); final Header[] headers = response.getHeaders(HttpHeaders.LOCATION); final Header location = headers[0]; final String resource = location.getValue(); return URI.create(resource); } else { final StringBuilder buffer = new StringBuilder(); buffer.append(code).append(" ").append(status.getReasonPhrase()); throw new FaxServiceException(buffer.toString()); } } }
4,881
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Ping.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/Ping.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.application; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import javax.servlet.ServletContext; import javax.servlet.sip.SipServlet; 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.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.apache.log4j.Logger; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.common.http.CustomHttpClientBuilder; import org.restcomm.connect.provisioning.number.api.ProvisionProvider; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ @Deprecated public class Ping { private Logger logger = Logger.getLogger(Ping.class); private Configuration configuration; private ServletContext context; private Timer timer; private Timer subsequentTimer; private boolean subsequentTimerIsSet = false; private PingTask ping; private final String provider; Ping(Configuration configuration, ServletContext context){ this.configuration = configuration; this.context = context; this.provider = configuration.getString("phone-number-provisioning[@class]"); } public void sendPing(){ boolean daemon = true; timer = new Timer(daemon); ping = new PingTask(configuration); timer.schedule(ping, 0, 60000); } private class PingTask extends TimerTask { private Configuration configuration; public PingTask(Configuration configuration) { this.configuration = configuration; } @Override public void run() { Configuration proxyConf = configuration.subset("runtime-settings").subset("telestax-proxy"); Boolean proxyEnabled = proxyConf.getBoolean("enabled"); Configuration mediaConf = configuration.subset("media-server-manager").subset("mgcp-server"); String publicIpAddress = mediaConf.getString("external-address"); if (proxyEnabled) { String proxyUri = proxyConf.getString("uri"); String username = proxyConf.getString("login"); String password = proxyConf.getString("password"); String endpoint = proxyConf.getString("endpoint"); final StringBuilder buffer = new StringBuilder(); buffer.append("<request id=\""+generateId()+"\">"); buffer.append(header(username, password)); buffer.append("<body>"); buffer.append("<requesttype>").append("ping").append("</requesttype>"); buffer.append("<item>"); buffer.append("<endpointgroup>").append(endpoint).append("</endpointgroup>"); // buffer.append("<provider>").append(provider).append("</provider>"); buffer.append("</item>"); buffer.append("</body>"); buffer.append("</request>"); final String body = buffer.toString(); final HttpPost post = new HttpPost(proxyUri); try { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("apidata", body)); post.setEntity(new UrlEncodedFormEntity(parameters)); final HttpClient client = CustomHttpClientBuilder.build(RestcommConfiguration.getInstance().getMain()); //This will work as a flag for LB that this request will need to be modified and proxied to VI post.addHeader("TelestaxProxy", String.valueOf(proxyEnabled)); //Adds the Provision provider class name post.addHeader("Provider", provider); //This will tell LB that this request is a getAvailablePhoneNumberByAreaCode request post.addHeader("RequestType", ProvisionProvider.REQUEST_TYPE.PING.name()); //This will let LB match the DID to a node based on the node host+port List<SipURI> uris = outboundInterface(); for (SipURI uri: uris) { post.addHeader("OutboundIntf", uri.getHost()+":"+uri.getPort()+":"+uri.getTransportParam()); } if (publicIpAddress != null || !publicIpAddress.equalsIgnoreCase("")) { post.addHeader("PublicIpAddress",publicIpAddress); } final HttpResponse response = client.execute(post); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { logger.info("Ping to Telestax Proxy was successfully sent"); timer.cancel(); // if (!subsequentTimerIsSet) { // logger.info("Will set subsequent timer"); // boolean daemon = true; // subsequentTimer = new Timer(daemon); // subsequentTimer.schedule(ping, 1800000, 1800000); // subsequentTimerIsSet = true; // } return; } else { logger.error("Ping to Telestax Proxy was sent, but there was a problem. Response status line: "+response.getStatusLine()); return; } } catch (final Exception e){ logger.error("Ping to Telestax Proxy was sent, but there was a problem. Exception: "+e); return; } } else { timer.cancel(); return; } } @SuppressWarnings("unchecked") private List<SipURI> outboundInterface() { final List<SipURI> uris = (List<SipURI>) context.getAttribute(SipServlet.OUTBOUND_INTERFACES); return uris; } private String generateId() { return UUID.randomUUID().toString().replace("-", ""); } 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(); } } }
7,701
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RvdProjectsMigrationException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/RvdProjectsMigrationException.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.application; /** * @author [email protected] */ public class RvdProjectsMigrationException extends Exception { private String message; private int errorCode; public RvdProjectsMigrationException(String message, int errorCode) { super(); this.message = message; this.errorCode = errorCode; } public RvdProjectsMigrationException(String message) { super(); this.message = message; } public RvdProjectsMigrationException() { } @Override public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getErrorCode() { return errorCode; } public void setErrorCode(int errorCode) { this.errorCode = errorCode; } }
1,783
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Bootstrapper.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/Bootstrapper.java
package org.restcomm.connect.application; import static org.restcomm.connect.dao.entities.Profile.DEFAULT_PROFILE_SID; import java.io.IOException; import java.net.UnknownHostException; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Properties; import javax.media.mscontrol.MsControlException; import javax.media.mscontrol.MsControlFactory; import javax.media.mscontrol.spi.Driver; import javax.media.mscontrol.spi.DriverManager; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.sip.SipServlet; import javax.servlet.sip.SipServletContextEvent; import javax.servlet.sip.SipServletListener; import javax.servlet.sip.SipURI; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.configuration.interpol.ConfigurationInterpolator; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.mobicents.servlet.sip.SipConnector; import org.restcomm.connect.application.config.ConfigurationStringLookup; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.amazonS3.S3AccessTool; import org.restcomm.connect.commons.common.http.CustomHttpClientBuilder; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.loader.ObjectFactory; import org.restcomm.connect.commons.loader.ObjectInstantiationException; import org.restcomm.connect.commons.util.DNSUtils; import org.restcomm.connect.core.service.RestcommConnectServiceProvider; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.InstanceId; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.entities.Profile; import org.restcomm.connect.dao.entities.shiro.ShiroResources; import org.restcomm.connect.extension.controller.ExtensionBootstrapper; import org.restcomm.connect.identity.IdentityContext; import org.restcomm.connect.monitoringservice.MonitoringService; import org.restcomm.connect.mrb.api.StartMediaResourceBroker; import org.restcomm.connect.mscontrol.api.MediaServerControllerFactory; import org.restcomm.connect.mscontrol.api.MediaServerInfo; import org.restcomm.connect.mscontrol.jsr309.Jsr309ControllerFactory; import org.restcomm.connect.mscontrol.mms.MmsControllerFactory; import org.restcomm.connect.sdr.api.StartSdrService; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; 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 scala.concurrent.ExecutionContext; /** * @author <a href="mailto:[email protected]">gvagenas</a> * @author [email protected] (Maria Farooq) */ public final class Bootstrapper extends SipServlet implements SipServletListener { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(Bootstrapper.class); private ActorSystem system; private ExecutionContext ec; public Bootstrapper() { super(); } @Override public void destroy() { CustomHttpClientBuilder.stopDefaultClient(); system.shutdown(); system.awaitTermination(); } private MediaServerControllerFactory mediaServerControllerFactory(final Configuration configuration, ClassLoader loader, DaoManager storage, ActorRef monitoring) throws ServletException { Configuration settings; String compatibility = configuration.subset("mscontrol").getString("compatibility", "rms"); MediaServerControllerFactory factory; switch (compatibility) { case "rms": try { settings = configuration.subset("media-server-manager"); ActorRef mrb = mediaResourceBroker(settings, storage, loader, monitoring); factory = new MmsControllerFactory(mrb); } catch (UnknownHostException e) { throw new ServletException(e); } break; case "xms": try { settings = configuration.subset("mscontrol"); // Load JSR 309 driver final String driverName = settings.getString("media-server[@class]"); Driver driver = DriverManager.getDriver(driverName); DriverManager.registerDriver(driver); // Configure properties Properties properties = getDialogicXmsProperties(settings); // Create JSR 309 factory MsControlFactory msControlFactory = driver.getFactory(properties); MediaServerInfo mediaServerInfo = mediaServerInfo(settings); factory = new Jsr309ControllerFactory(mediaServerInfo, msControlFactory); } catch (UnknownHostException | MsControlException e) { throw new ServletException(e); } break; default: throw new IllegalArgumentException("MSControl unknown compatibility mode: " + compatibility); } return factory; } private MediaServerInfo mediaServerInfo(final Configuration configuration) throws UnknownHostException { final String name = configuration.getString("media-server[@name]"); final String address = configuration.getString("media-server.address"); final int port = configuration.getInt("media-server.port"); final int timeout = configuration.getInt("media-server.timeout", 5); return new MediaServerInfo(name, DNSUtils.getByName(address), port, timeout); } private Properties getDialogicXmsProperties(final Configuration configuration) { // New set of properties that will be used to configure the connector Properties properties = new Properties(); // Tell the driver we are configuring it programmatically // properties.setProperty("connector.dynamic.configuration", "yes"); // Configure the transport to be used by the connector final String mediaTransport = configuration.getString("media-server.transport", "udp"); if (logger.isInfoEnabled()) { logger.info("JSR 309 - media-server.transport: udp"); } properties.setProperty("connector.sip.transport", mediaTransport); // Configure SIP connector using RestComm binding address SipURI sipURI = outboundInterface(getServletContext(), mediaTransport); properties.setProperty("connector.sip.address", sipURI.getHost()); if (logger.isInfoEnabled()) { logger.info("JSR 309 - connector.sip.address: " + sipURI.getHost()); } properties.setProperty("connector.sip.port", String.valueOf(sipURI.getPort())); if (logger.isInfoEnabled()) { logger.info("JSR 309 - connector.sip.port: " + String.valueOf(sipURI.getPort())); } // Configure Media Server address based on restcomm configuration file final String mediaAddress = configuration.getString("media-server.address", "127.0.0.1"); properties.setProperty("mediaserver.sip.ipaddress", mediaAddress); if (logger.isInfoEnabled()) { logger.info("JSR 309 - mediaserver.sip.ipaddress: " + mediaAddress); } final String mediaPort = configuration.getString("media-server.port", "5060"); properties.setProperty("mediaserver.sip.port", mediaPort); if (logger.isInfoEnabled()) { logger.info("JSR 309 - mediaserver.sip.port: " + mediaPort); } // Let RestComm control call legs properties.setProperty("connector.conferenceControlLeg", "no"); return properties; } @SuppressWarnings("unchecked") private SipURI outboundInterface(ServletContext context, String transport) { SipURI result = null; final List<SipURI> uris = (List<SipURI>) context.getAttribute(OUTBOUND_INTERFACES); if (uris != null && uris.size() > 0) { for (final SipURI uri : uris) { final String interfaceTransport = uri.getTransportParam(); if (transport.equalsIgnoreCase(interfaceTransport)) { result = uri; } } if (logger.isInfoEnabled()) { if (result == null) { logger.info("Outbound interface is NULL! Looks like there was no " + transport + " in the list of connectors"); } else { logger.info("Outbound interface found: " + result.toString()); } } } else { if (logger.isInfoEnabled()) { logger.info("ServletContext return null or empty list of connectors"); } } return result; } private ActorRef mediaResourceBroker(final Configuration configuration, final DaoManager storage, final ClassLoader loader, final ActorRef monitoring) throws UnknownHostException { final Props props = 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); } }); ActorRef mrb = system.actorOf(props); mrb.tell(new StartMediaResourceBroker(configuration, storage, loader, monitoring), null); return mrb; } private String home(final ServletContext context) { final String path = context.getRealPath("/"); if (path.endsWith("/")) { return path.substring(0, path.length() - 1); } else { return path; } } private DaoManager storage(final Configuration configuration, Configuration daoManagerConfiguration, final ClassLoader loader) throws ObjectInstantiationException { final String classpath = daoManagerConfiguration.getString("dao-manager[@class]"); final DaoManager daoManager = (DaoManager) new ObjectFactory(loader).getObjectInstance(classpath); daoManager.configure(configuration, daoManagerConfiguration); daoManager.start(); return daoManager; } 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); } private ActorRef sdrService(final Configuration configuration, final ClassLoader loader) throws Exception { final String className = configuration.subset("runtime-settings").getString("sdr-service[@class]"); if (className != null) { final Props props = new Props(new UntypedActorFactory() { @Override public Actor create() throws Exception { return (Actor) new ObjectFactory(loader).getObjectInstance(className); } }); ActorRef sdr = system.actorOf(props); sdr.tell(new StartSdrService(configuration), null); return sdr; } return null; } private String uri(final ServletContext context) { return context.getContextPath(); } /** * generateDefaultDomainName based on RC hostname * https://github.com/RestComm/Restcomm-Connect/issues/2085 * * @param configuration * @param storage * @param sipUriHostAsFallbackDomain - if hostname is not provided in restcomm.xml then provided sipuri host will be used as domain. */ private boolean generateDefaultDomainName(final Configuration configuration, final DaoManager storage, final SipURI sipUriHostAsFallbackDomain) { try { final Sid defaultOrganization = new Sid("ORafbe225ad37541eba518a74248f0ac4c"); String hostname = configuration.getString("hostname"); if (hostname != null && !hostname.trim().equals("")) { if (logger.isInfoEnabled()) logger.info("Generate Default Domain Name based on RC hostname: " + hostname); } else { if (sipUriHostAsFallbackDomain != null) { logger.warn("Hostname property is null in restcomm.xml, will assign this host as domain: " + sipUriHostAsFallbackDomain.getHost()); hostname = sipUriHostAsFallbackDomain.getHost(); } else { logger.error("Hostname property is null in restcomm.xml, As well restcomm outbound sipuri is NULL."); return false; } } Organization organization = storage.getOrganizationsDao().getOrganization(defaultOrganization); if (organization == null) { storage.getOrganizationsDao().addOrganization(new Organization(defaultOrganization, hostname, DateTime.now(), DateTime.now(), Organization.Status.ACTIVE)); } else { organization = organization.setDomainName(hostname); storage.getOrganizationsDao().updateOrganization(organization); } } catch (Exception e) { logger.error("Unable to generateDefaultDomainName {}", e); return false; } return true; } /** * generateDefaultProfile if does not already exists * @throws SQLException * @throws IOException */ private void generateDefaultProfile(final DaoManager storage, final String profileSourcePath) throws SQLException, IOException{ Profile profile = storage.getProfilesDao().getProfile(DEFAULT_PROFILE_SID); if (profile == null) { if(logger.isDebugEnabled()) { logger.debug("default profile does not exist, will create one from default Plan"); } JsonNode jsonNode = JsonLoader.fromPath(profileSourcePath); profile = new Profile(DEFAULT_PROFILE_SID, jsonNode.toString(), new Date(), new Date()); storage.getProfilesDao().addProfile(profile); } else { if(logger.isDebugEnabled()){ logger.debug("default profile already exists, will not override it."); } } } private S3AccessTool prepareS3AccessTool(Configuration configuration) { Configuration amazonS3Configuration = configuration.subset("amazon-s3"); if (!amazonS3Configuration.isEmpty()) { // Do not fail with NPE is amazonS3Configuration is not present for older install boolean amazonS3Enabled = amazonS3Configuration.getBoolean("enabled"); if (amazonS3Enabled) { final String accessKey = amazonS3Configuration.getString("access-key"); final String securityKey = amazonS3Configuration.getString("security-key"); final String bucketName = amazonS3Configuration.getString("bucket-name"); final String folder = amazonS3Configuration.getString("folder"); final boolean reducedRedundancy = amazonS3Configuration.getBoolean("reduced-redundancy"); final int minutesToRetainPublicUrl = amazonS3Configuration.getInt("minutes-to-retain-public-url", 10); final boolean removeOriginalFile = amazonS3Configuration.getBoolean("remove-original-file"); final String bucketRegion = amazonS3Configuration.getString("bucket-region"); final boolean testing = amazonS3Configuration.getBoolean("testing", false); final String testingUrl = amazonS3Configuration.getString("testing-url", null); return new S3AccessTool(accessKey, securityKey, bucketName, folder, reducedRedundancy, minutesToRetainPublicUrl, removeOriginalFile, bucketRegion, testing, testingUrl); } } return null; } @Override public void servletInitialized(SipServletContextEvent event) { if (event.getSipServlet().getClass().equals(Bootstrapper.class)) { final ServletContext context = event.getServletContext(); final String path = context.getRealPath("WEB-INF/conf/restcomm.xml"); final String extensionConfigurationPath = context.getRealPath("WEB-INF/conf/extensions.xml"); final String daoManagerConfigurationPath = context.getRealPath("WEB-INF/conf/dao-manager.xml"); // Initialize the configuration interpolator. final ConfigurationStringLookup strings = new ConfigurationStringLookup(); strings.addProperty("home", home(context)); strings.addProperty("uri", uri(context)); ConfigurationInterpolator.registerGlobalLookup("restcomm", strings); // Load the RestComm configuration file. Configuration xml = null; XMLConfiguration extensionConf = null; XMLConfiguration daoManagerConf = null; try { XMLConfiguration xmlConfiguration = new XMLConfiguration(); xmlConfiguration.setDelimiterParsingDisabled(true); xmlConfiguration.setAttributeSplittingDisabled(true); xmlConfiguration.load(path); xml = xmlConfiguration; extensionConf = new XMLConfiguration(); extensionConf.setDelimiterParsingDisabled(true); extensionConf.setAttributeSplittingDisabled(true); extensionConf.load(extensionConfigurationPath); daoManagerConf = new XMLConfiguration(); daoManagerConf.setDelimiterParsingDisabled(true); daoManagerConf.setAttributeSplittingDisabled(true); daoManagerConf.load(daoManagerConfigurationPath); } catch (final ConfigurationException exception) { logger.error(exception); } xml.setProperty("runtime-settings.home-directory", home(context)); xml.setProperty("runtime-settings.root-uri", uri(context)); // initialize DnsUtilImpl ClassName DNSUtils.initializeDnsUtilImplClassName(xml); // Create high-level restcomm configuration RestcommConfiguration.createOnce(xml); context.setAttribute(Configuration.class.getName(), xml); context.setAttribute("ExtensionConfiguration", extensionConf); // Initialize global dependencies. final ClassLoader loader = getClass().getClassLoader(); // Create the actor system. final Config settings = ConfigFactory.load(); system = ActorSystem.create("RestComm", settings, loader); // Share the actor system with other servlets. context.setAttribute(ActorSystem.class.getName(), system); ec = system.dispatchers().lookup("restcomm-blocking-dispatcher"); context.setAttribute(ExecutionContext.class.getName(), ec); S3AccessTool s3AccessTool = prepareS3AccessTool(xml); context.setAttribute(S3AccessTool.class.getName(), s3AccessTool); // Create the storage system. DaoManager storage = null; try { storage = storage(xml, daoManagerConf, loader); } catch (final ObjectInstantiationException exception) { logger.error("ObjectInstantiationException during initialization: ", exception); } context.setAttribute(DaoManager.class.getName(), storage); //ShiroResources.getInstance().set(DaoManager.class, storage); ShiroResources.getInstance().set(Configuration.class, xml.subset("runtime-settings")); // Initialize identityContext IdentityContext identityContext = new IdentityContext(xml); context.setAttribute(IdentityContext.class.getName(), identityContext); // Initialize CoreServices RestcommConnectServiceProvider.getInstance().startServices(context); // Create the media gateway. //Initialize Monitoring Service ActorRef monitoring = monitoringService(xml, storage, loader); if (monitoring != null) { context.setAttribute(MonitoringService.class.getName(), monitoring); if (logger.isInfoEnabled()) { logger.info("Monitoring Service created and stored in the context"); } } else { logger.error("Monitoring Service is null"); } //Initialize Sdr Service try { sdrService(xml, loader); } catch (Exception e) { logger.error("Exception during Sdr Service initialization: " + e.getStackTrace()); } CloseableHttpClient buildDefaultClient = CustomHttpClientBuilder.buildDefaultClient(RestcommConfiguration.getInstance().getMain()); context.setAttribute(CustomHttpClientBuilder.class.getName(), buildDefaultClient); //Initialize Extensions Configuration extensionConfiguration = null; try { extensionConfiguration = new XMLConfiguration(extensionConfigurationPath); } catch (final ConfigurationException exception) { // logger.error(exception); } ExtensionBootstrapper extensionBootstrapper = new ExtensionBootstrapper(context, extensionConfiguration); try { extensionBootstrapper.start(); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { logger.error("Exception during extension scanner start: " + e.getStackTrace()); } try { generateDefaultProfile(storage, context.getRealPath("WEB-INF/conf/defaultPlan.json")); } catch (SQLException | IOException e1) { logger.error("Exception during generateDefaultProfile: ", e1); } // Create the media server controller factory MediaServerControllerFactory mscontrollerFactory = null; try { mscontrollerFactory = mediaServerControllerFactory(xml, loader, storage, monitoring); } catch (ServletException exception) { logger.error("ServletException during initialization: ", exception); } context.setAttribute(MediaServerControllerFactory.class.getName(), mscontrollerFactory); Boolean rvdMigrationEnabled = new Boolean(xml.subset("runtime-settings").getString("rvd-workspace-migration-enabled", "false")); if (rvdMigrationEnabled) { //Replicate RVD Projects as database entities try { RvdProjectsMigrator rvdProjectMigrator = new RvdProjectsMigrator(context, xml); rvdProjectMigrator.executeMigration(); } catch (Exception exception) { logger.error("RVD Porjects migration failed during initialization: ", exception); } } //Last, print Version and send PING if needed Version.printVersion(); GenerateInstanceId generateInstanceId = null; InstanceId instanceId = null; SipURI sipURI = null; try { sipURI = outboundInterface(context, "udp"); if (sipURI != null) { generateInstanceId = new GenerateInstanceId(context, sipURI); } else { if (logger.isInfoEnabled()) { logger.info("SipURI is NULL!!! Cannot proceed to generate InstanceId"); } } instanceId = generateInstanceId.instanceId(); } catch (UnknownHostException e) { logger.error("UnknownHostException during the generation of InstanceId: " + e); } context.setAttribute(InstanceId.class.getName(), instanceId); monitoring.tell(instanceId, null); RestcommConfiguration.getInstance().getMain().setInstanceId(instanceId.getId().toString()); if (!generateDefaultDomainName(xml.subset("http-client"), storage, sipURI)) { logger.error("Unable to generate DefaultDomainName, Restcomm Akka system will exit now..."); system.shutdown(); system.awaitTermination(); } // https://github.com/RestComm/Restcomm-Connect/issues/1285 Pass InstanceId to the Load Balancer for LCM stickiness SipConnector[] connectors = (SipConnector[]) context.getAttribute("org.mobicents.servlet.sip.SIP_CONNECTORS"); Properties loadBalancerCustomInfo = new Properties(); loadBalancerCustomInfo.setProperty("Restcomm-Instance-Id", instanceId.getId().toString()); for (SipConnector sipConnector : connectors) { if (logger.isDebugEnabled()) { logger.debug("Passing InstanceId " + instanceId.getId().toString() + " to connector " + sipConnector); } sipConnector.setLoadBalancerCustomInformation(loadBalancerCustomInfo); } //Depreciated // Ping ping = new Ping(xml, context); // ping.sendPing(); } } }
26,184
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RvdProjectsMigrationHelper.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/RvdProjectsMigrationHelper.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.application; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActorFactory; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.thoughtworks.xstream.XStream; import org.apache.commons.configuration.Configuration; import org.apache.commons.io.FileUtils; import org.apache.ibatis.exceptions.TooManyResultsException; import org.joda.time.DateTime; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.util.StringUtils; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.ApplicationsDao; import org.restcomm.connect.dao.ClientsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.IncomingPhoneNumbersDao; import org.restcomm.connect.dao.NotificationsDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Application; 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.email.EmailService; import org.restcomm.connect.email.api.EmailRequest; import org.restcomm.connect.email.api.Mail; import javax.servlet.ServletContext; import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.restcomm.connect.dao.entities.IncomingPhoneNumberFilter; /** * This class was designed to be used with exclusivity by {@link RvdProjectsMigrator}, once that * Restcomm should not interact with RVD's workspace as a typical operation given that the migration process forms a very * specific scenario. * * @author [email protected] */ public class RvdProjectsMigrationHelper { private static final String CONTEXT_NAME_RVD = "visual-designer.war"; private static final String WORKSPACE_DIRECTORY_NAME = "workspace"; private static final String PROTO_DIRECTORY_PREFIX = "_proto"; private static final String USERS_DIRECTORY_NAME = "@users"; private static final Pattern RVD_PROJECT_URL = Pattern.compile("^\\/visual-designer.*\\/(.*)\\/controller$"); private static final String ACCOUNT_NOTIFICATIONS_SID = "ACae6e420f425248d6a26948c17a9e2acf"; private static final String EMBEDDED_DIRECTORY_NAME = "workspace-migration"; private boolean embeddedMigration = false; // If visual-designer context is not found, search for internal structure private Configuration configuration; private String workspacePath; private String workspaceBackupPath; private StateHeader currentStateHeader; private Application currentApplication; private final ApplicationsDao applicationDao; private final AccountsDao accountsDao; private final IncomingPhoneNumbersDao didsDao; private final ClientsDao clientsDao; private final NotificationsDao notificationsDao; private List<IncomingPhoneNumber> dids; private List<Client> clients; private ActorRef emailService; private ActorSystem system; public RvdProjectsMigrationHelper(ServletContext servletContext, Configuration configuration) throws Exception { defineWorkspacePath(servletContext); this.configuration = configuration; final DaoManager storage = (DaoManager) servletContext.getAttribute(DaoManager.class.getName()); this.applicationDao = storage.getApplicationsDao(); this.accountsDao = storage.getAccountsDao(); this.didsDao = storage.getIncomingPhoneNumbersDao(); this.clientsDao = storage.getClientsDao(); this.notificationsDao = storage.getNotificationsDao(); system = (ActorSystem) servletContext.getAttribute(ActorSystem.class.getName()); } private void defineWorkspacePath(ServletContext servletContext) throws Exception { // Obtain RVD context root path String contextRootPath = servletContext.getRealPath("/"); String contextPathRvd = contextRootPath + "../" + CONTEXT_NAME_RVD + "/"; // Check RVD context to try embedded mode if necessary File rvd = new File(contextPathRvd); if (rvd.exists()) { // Load RVD configuration and check workspace path FileInputStream input = new FileInputStream(contextPathRvd + "WEB-INF/rvd.xml"); XStream xstream = new XStream(); xstream.alias("rvd", RvdConfig.class); RvdConfig rvdConfig = (RvdConfig) xstream.fromXML(input); // Define workspace location String workspaceBasePath = contextPathRvd + WORKSPACE_DIRECTORY_NAME; if (rvdConfig.getWorkspaceLocation() != null && !"".equals(rvdConfig.getWorkspaceLocation())) { if (rvdConfig.getWorkspaceLocation().startsWith("/")) workspaceBasePath = rvdConfig.getWorkspaceLocation(); // this is an absolute path else workspaceBasePath = contextPathRvd + rvdConfig.getWorkspaceLocation(); // this is a relative path hooked // under RVD context } this.workspacePath = workspaceBasePath; // Define workspace backup location String workspaceBackupBasePath = contextPathRvd; if (rvdConfig.getWorkspaceBackupLocation() != null && !"".equals(rvdConfig.getWorkspaceBackupLocation())) { if (rvdConfig.getWorkspaceBackupLocation().startsWith("/")) workspaceBackupBasePath = rvdConfig.getWorkspaceBackupLocation(); // this is an absolute path else workspaceBackupBasePath = contextPathRvd + rvdConfig.getWorkspaceBackupLocation(); // this is a relative // path hooked under RVD // context } this.workspaceBackupPath = workspaceBackupBasePath; } else { // Try to set embedded migration. For testing only String dir = contextRootPath + EMBEDDED_DIRECTORY_NAME + File.separator + WORKSPACE_DIRECTORY_NAME + File.separator; File embedded = new File(dir); if (embedded.exists()) { this.workspacePath = dir; this.workspaceBackupPath = contextRootPath; this.embeddedMigration = true; } else { throw new Exception("Error while searching for the workspace location. Aborting migration."); } } } public void backupWorkspace() throws RvdProjectsMigrationException { try { File workspace = new File(this.workspacePath); File workspaceBackup = new File(this.workspaceBackupPath + File.separator + "workspaceBackup-" + DateTime.now().getMillis()); FileUtils.copyDirectoryToDirectory(workspace, workspaceBackup); } catch (IOException e) { throw new RvdProjectsMigrationException("[ERROR-CODE:13] Error while creating backup for RVD workspace", 13); } } public List<String> listProjects() throws RvdProjectsMigrationException { List<String> items = new ArrayList<String>(); File workspaceDir = new File(workspacePath); if (workspaceDir.exists()) { File[] entries = workspaceDir.listFiles(new FileFilter() { @Override public boolean accept(File anyfile) { if (anyfile.isDirectory() && !anyfile.getName().startsWith(PROTO_DIRECTORY_PREFIX) && !anyfile.getName().equals(USERS_DIRECTORY_NAME)) return true; return false; } }); Arrays.sort(entries, new Comparator<File>() { @Override public int compare(File f1, File f2) { File statefile1 = new File(f1.getAbsolutePath() + File.separator + "state"); File statefile2 = new File(f2.getAbsolutePath() + File.separator + "state"); if (statefile1.exists() && statefile2.exists()) return Long.valueOf(statefile2.lastModified()).compareTo(statefile1.lastModified()); else return Long.valueOf(f2.lastModified()).compareTo(f1.lastModified()); } }); for (File entry : entries) { items.add(entry.getName()); } } else { throw new RvdProjectsMigrationException("[ERROR-CODE:1] Error while loading the list of projects from workspace", 1); } return items; } public String searchApplicationSid(String projectName) throws RvdProjectsMigrationException { try { currentApplication = null; String applicationSid = null; currentApplication = applicationDao.getApplication(projectName); if (currentApplication != null) { applicationSid = currentApplication.getSid().toString(); } else if (Sid.pattern.matcher(projectName).matches()) { Sid sid = new Sid(projectName); currentApplication = applicationDao.getApplication(sid); if (currentApplication != null) { applicationSid = currentApplication.getSid().toString(); } } return applicationSid; } catch ( TooManyResultsException e) { /* This happens when a non-upgraded project whose friendly-name exists in several applications is upgraded. The old bahaviour was a broken upgrade attempt for the whole workspace. Now, the failure should be limited to this project */ throw new RvdProjectsMigrationException("[ERROR-CODE:14] Error while upgrading project '" + projectName + "'. Several applications with such a FriendlyName were found. You have to manually restore this project.", 14); } } public void renameProjectUsingNewConvention(String projectName, String applicationSid) throws RvdProjectsMigrationException { try { renameProject(projectName, applicationSid); } catch (IOException e) { throw new RvdProjectsMigrationException("[ERROR-CODE:5] Error while renaming the project '" + projectName + "' to '" + applicationSid + "'" + e.getMessage(), 5); } } public void renameProject(String source, String dest) throws IOException { File sourceDir = new File(workspacePath + File.separator + source); File destDir = new File(workspacePath + File.separator + dest); FileUtils.moveDirectory(sourceDir, destDir); } public void loadProjectState(String projectName) throws RvdProjectsMigrationException { try { String pathName = workspacePath + File.separator + projectName + File.separator + "state"; File file = new File(pathName); if (!file.exists()) { throw new RvdProjectsMigrationException("File " + file.getPath() + "does not exist"); } String data = FileUtils.readFileToString(file, Charset.forName("UTF-8")); JsonParser parser = new JsonParser(); JsonElement headerElement = parser.parse(data).getAsJsonObject().get("header"); if (headerElement == null) { throw new RvdProjectsMigrationException(); } Gson gson = new Gson(); currentStateHeader = gson.fromJson(headerElement, StateHeader.class); } catch (IOException e) { throw new RvdProjectsMigrationException("[ERROR-CODE:6] Error loading state file from project '" + projectName + "' " + e.getMessage(), 6); } } public boolean projectUsesNewNamingConvention(String projectName) { return Sid.pattern.matcher(projectName).matches(); } public String createOrUpdateApplicationEntity(String applicationSid, String projectName) throws RvdProjectsMigrationException { try { if(applicationSid != null) { // Update application currentApplication = currentApplication.setRcmlUrl(URI.create("/visual-designer/services/apps/" + applicationSid + "/controller")); applicationDao.updateApplication(currentApplication); return applicationSid; } else { // Create new application Account account = accountsDao.getAccount(currentStateHeader.getOwner()); if (account == null) { throw new RvdProjectsMigrationException("Error locating the owner account for project \"" + projectName + "\""); } final Application.Builder builder = Application.builder(); final Sid sid = Sid.generate(Sid.Type.APPLICATION); builder.setSid(sid); builder.setFriendlyName(projectName); builder.setAccountSid(account.getSid()); builder.setApiVersion(configuration.subset("runtime-settings").getString("api-version")); builder.setHasVoiceCallerIdLookup(false); String rootUri = configuration.subset("runtime-settings").getString("root-uri"); rootUri = StringUtils.addSuffixIfNotPresent(rootUri, "/"); final StringBuilder buffer = new StringBuilder(); buffer.append(rootUri).append(configuration.subset("runtime-settings").getString("api-version")) .append("/Accounts/").append(account.getSid().toString()).append("/Applications/").append(sid.toString()); builder.setUri(URI.create(buffer.toString())); builder.setRcmlUrl(URI.create("/visual-designer/services/apps/" + sid.toString() + "/controller")); builder.setKind(Application.Kind.getValueOf(currentStateHeader.getProjectKind())); currentApplication = builder.build(); applicationDao.addApplication(currentApplication); return sid.toString(); } } catch (RvdProjectsMigrationException e) { String suffix = currentApplication != null ? "with the application '" + currentApplication.getSid().toString() + "' " : ""; throw new RvdProjectsMigrationException("[ERROR-CODE:7] Error while synchronizing the project '" + projectName + "' " + suffix + e.getMessage(), 7); } } public int updateIncomingPhoneNumbers(String applicationSid, String projectName) throws RvdProjectsMigrationException { try { if (dids == null) { IncomingPhoneNumberFilter.Builder filterBuilder = IncomingPhoneNumberFilter.Builder.builder(); dids = didsDao.getIncomingPhoneNumbersByFilter(filterBuilder.build()); } } catch (Exception e) { throw new RvdProjectsMigrationException( "[ERROR-CODE:8] Error while loading IncomingPhoneNumbers list for updates with project '" + applicationSid + "' " + e.getMessage(), 8); } Application.Kind kind = Application.Kind.getValueOf(currentStateHeader.getProjectKind()); IncomingPhoneNumber did = null; int amountUpdated = 0; try { switch (kind) { case SMS: for (int i = 0; i < dids.size(); i++) { did = dids.get(i); if (hasUrlReference(did.getSmsUrl(), currentApplication.getFriendlyName())) { Sid smsApplicationSid = new Sid(applicationSid); IncomingPhoneNumber updateSmsDid = new IncomingPhoneNumber(did.getSid(), did.getDateCreated(), did.getDateUpdated(), did.getFriendlyName(), did.getAccountSid(), did.getPhoneNumber(), did.getCost(), did.getApiVersion(), did.hasVoiceCallerIdLookup(), did.getVoiceUrl(), did.getVoiceMethod(), did.getVoiceFallbackUrl(), did.getVoiceFallbackMethod(), did.getStatusCallback(), did.getStatusCallbackMethod(), did.getVoiceApplicationSid(), null, did.getSmsMethod(), did.getSmsFallbackUrl(), did.getSmsFallbackMethod(), smsApplicationSid, did.getUri(), did.getUssdUrl(), did.getUssdMethod(), did.getUssdFallbackUrl(), did.getUssdFallbackMethod(), did.getUssdApplicationSid(), did.getReferUrl(), did.getReferMethod(), did.getReferApplicationSid(), did.isVoiceCapable(), did.isSmsCapable(), did.isMmsCapable(), did.isFaxCapable(), did.isPureSip(), did.getOrganizationSid()); didsDao.updateIncomingPhoneNumber(updateSmsDid); dids.set(i, updateSmsDid); amountUpdated++; } } break; case USSD: for (int i = 0; i < dids.size(); i++) { did = dids.get(i); if (hasUrlReference(did.getUssdUrl(), currentApplication.getFriendlyName())) { Sid ussdApplicationSid = new Sid(applicationSid); IncomingPhoneNumber updateUssdDid = new IncomingPhoneNumber(did.getSid(), did.getDateCreated(), did.getDateUpdated(), did.getFriendlyName(), did.getAccountSid(), did.getPhoneNumber(), did.getCost(), did.getApiVersion(), did.hasVoiceCallerIdLookup(), did.getVoiceUrl(), did.getVoiceMethod(), did.getVoiceFallbackUrl(), did.getVoiceFallbackMethod(), did.getStatusCallback(), did.getStatusCallbackMethod(), did.getVoiceApplicationSid(), did.getSmsUrl(), did.getSmsMethod(), did.getSmsFallbackUrl(), did.getSmsFallbackMethod(), did.getSmsApplicationSid(), did.getUri(), null, did.getUssdMethod(), did.getUssdFallbackUrl(), did.getUssdFallbackMethod(), ussdApplicationSid, did.getReferUrl(), did.getReferMethod(), did.getReferApplicationSid(), did.isVoiceCapable(), did.isSmsCapable(), did.isMmsCapable(), did.isFaxCapable(), did.isPureSip(), did.getOrganizationSid()); didsDao.updateIncomingPhoneNumber(updateUssdDid); dids.set(i, updateUssdDid); amountUpdated++; } } break; case VOICE: for (int i = 0; i < dids.size(); i++) { did = dids.get(i); if (hasUrlReference(did.getVoiceUrl(), currentApplication.getFriendlyName())) { Sid voiceApplicationSid = new Sid(applicationSid); IncomingPhoneNumber updateVoiceDid = new IncomingPhoneNumber(did.getSid(), did.getDateCreated(), did.getDateUpdated(), did.getFriendlyName(), did.getAccountSid(), did.getPhoneNumber(), did.getCost(), did.getApiVersion(), did.hasVoiceCallerIdLookup(), null, did.getVoiceMethod(), did.getVoiceFallbackUrl(), did.getVoiceFallbackMethod(), did.getStatusCallback(), did.getStatusCallbackMethod(), voiceApplicationSid, did.getSmsUrl(), did.getSmsMethod(), did.getSmsFallbackUrl(), did.getSmsFallbackMethod(), did.getSmsApplicationSid(), did.getUri(), did.getUssdUrl(), did.getUssdMethod(), did.getUssdFallbackUrl(), did.getUssdFallbackMethod(), did.getUssdApplicationSid(), did.getReferUrl(), did.getReferMethod(), did.getReferApplicationSid(), did.isVoiceCapable(), did.isSmsCapable(), did.isMmsCapable(), did.isFaxCapable(), did.isPureSip(), did.getOrganizationSid()); didsDao.updateIncomingPhoneNumber(updateVoiceDid); dids.set(i, updateVoiceDid); amountUpdated++; } } break; default: break; } } catch (UnsupportedEncodingException e) { throw new RvdProjectsMigrationException("[ERROR-CODE:9] Error while updating IncomingPhoneNumber '" + did.getSid().toString() + "' with the Application '" + applicationSid + "' " + e.getMessage(), 9); } return amountUpdated; } private boolean hasUrlReference(URI url, String projectName) throws UnsupportedEncodingException { if (url != null && !url.toString().isEmpty()) { Matcher m = RVD_PROJECT_URL.matcher(url.toString()); if (m.find()) { String result = m.group(1); result = URLDecoder.decode(result, "UTF-8"); return projectName.equals(result); } } return false; } public int updateClients(String applicationSid, String projectName) throws RvdProjectsMigrationException { try { if (clients == null) { clients = clientsDao.getAllClients(); } } catch (Exception e) { throw new RvdProjectsMigrationException( "[ERROR-CODE:10] Error while loading the Clients list for updates with project '" + applicationSid + "'. " + e.getMessage(), 10); } Application.Kind kind = Application.Kind.getValueOf(currentStateHeader.getProjectKind()); Client client = null; int amountUpdated = 0; try { if (kind == Application.Kind.VOICE) { for (int i = 0; i < clients.size(); i++) { client = clients.get(i); if (hasUrlReference(client.getVoiceUrl(), currentApplication.getFriendlyName())) { Sid voiceApplicationSid = new Sid(applicationSid); client = client.setVoiceApplicationSid(voiceApplicationSid); client = client.setVoiceUrl(null); clientsDao.updateClient(client); clients.set(i, client); amountUpdated++; } } } } catch (Exception e) { throw new RvdProjectsMigrationException("[ERROR-CODE:11] Error while updating Client '" + client.getSid().toString() + "' with the Application '" + applicationSid + "' " + e.getMessage(), 11); } return amountUpdated; } public void storeWorkspaceStatus(boolean migrationSucceeded) throws RvdProjectsMigrationException { String pathName = workspacePath + File.separator + ".version"; File file = new File(pathName); Gson gson = new Gson(); String version = org.restcomm.connect.commons.Version.getVersion(); Version ws = new Version(migrationSucceeded, version); String data = gson.toJson(ws); try { FileUtils.writeStringToFile(file, data, "UTF-8"); } catch (IOException e) { throw new RvdProjectsMigrationException("[ERROR-CODE:12] Error creating file in storage: " + file + e.getMessage(), 12); } } public boolean isMigrationExecuted() { String pathName = workspacePath + File.separator + ".version"; File file = new File(pathName); if (!file.exists()) { return false; } String data; try { data = FileUtils.readFileToString(file, Charset.forName("UTF-8")); } catch (IOException e) { return false; } JsonParser parser = new JsonParser(); JsonElement element = parser.parse(data).getAsJsonObject(); if (element != null) { Gson gson = new Gson(); Version workspaceVersion = gson.fromJson(element, Version.class); String restcommVersion = org.restcomm.connect.commons.Version.getVersion(); if (!workspaceVersion.getVersion().equals(restcommVersion) && !workspaceVersion.getStatus()) { return false; } else { return true; } } return false; } public void addNotification(String message, boolean error, Integer errorCode) throws URISyntaxException { Notification.Builder builder = Notification.builder(); Sid sid = Sid.generate(Sid.Type.NOTIFICATION); builder.setSid(sid); builder.setAccountSid(new Sid(ACCOUNT_NOTIFICATIONS_SID)); builder.setApiVersion(configuration.subset("runtime-settings").getString("api-version")); builder.setLog(error ? new Integer(1) : new Integer(0)); builder.setErrorCode(errorCode); builder.setMoreInfo(new URI("http://docs.telestax.com/rvd-workspace-upgrade")); builder.setMessageText(message); builder.setMessageDate(DateTime.now()); builder.setRequestUrl(new URI("")); builder.setRequestMethod(""); builder.setRequestVariables(""); StringBuilder buffer = new StringBuilder(); buffer.append("/").append(configuration.subset("runtime-settings").getString("api-version")).append("/Accounts/"); buffer.append(ACCOUNT_NOTIFICATIONS_SID).append("/Notifications/"); buffer.append(sid.toString()); final URI uri = URI.create(buffer.toString()); builder.setUri(uri); Notification notification = builder.build(); notificationsDao.addNotification(notification); } public boolean isMigrationEnabled() { Boolean value = new Boolean(configuration.subset("runtime-settings").getString("rvd-workspace-migration-enabled", "true")); return value; } public void sendEmailNotification(String message, boolean migrationSucceeded) throws RvdProjectsMigrationException { String host = configuration.subset("smtp-notify").getString("host"); String username = configuration.subset("smtp-notify").getString("user"); String password = configuration.subset("smtp-notify").getString("password"); String defaultEmailAddress = configuration.subset("smtp-notify").getString("default-email-address"); if (host == null || username == null || password == null || defaultEmailAddress == null || host.isEmpty() || username.isEmpty() || password.isEmpty() || defaultEmailAddress.isEmpty()) { throw new RvdProjectsMigrationException("Skipping email notification due to invalid configuration"); } if (emailService == null) { emailService = emailService(configuration.subset("smtp-notify")); } String subject = "Restcomm - RVD Projects migration"; String body = message; if (!migrationSucceeded) { body += ". Please, visit http://docs.telestax.com/rvd-workspace-upgrade for more information on how to troubleshoot workspace migration issues."; } final Mail emailMsg = new Mail(username + "@" + host, defaultEmailAddress, subject, body); emailService.tell(new EmailRequest(emailMsg), emailService); } private ActorRef emailService(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 system.actorOf(props); } public boolean isEmbeddedMigration() { return this.embeddedMigration; } private class Version { boolean status; String version; public Version() { } public Version(boolean namingMigrationSucceeded, String versionLastRun) { super(); this.status = namingMigrationSucceeded; this.version = versionLastRun; } public boolean getStatus() { return status; } public String getVersion() { return version; } } private class RvdConfig { private String workspaceLocation; private String workspaceBackupLocation; private String sslMode; private String restcommBaseUrl; public RvdConfig() { } public RvdConfig(String workspaceLocation, String workspaceBackupLocation, String restcommPublicIp, String sslMode) { super(); this.workspaceLocation = workspaceLocation; this.workspaceBackupLocation = workspaceBackupLocation; this.sslMode = sslMode; } public String getWorkspaceLocation() { return workspaceLocation; } public String getWorkspaceBackupLocation() { return workspaceBackupLocation; } public String getSslMode() { return sslMode; } public String getRestcommBaseUrl() { return restcommBaseUrl; } } private class StateHeader { // application logging settings for this project. If not null logging is enabled. // We are using an object instead of a boolean to easily add properties in the future public class Logging { } String projectKind; String startNodeName; String version; String owner; // the Restcomm user id that owns the project or null if it has no owner at all. Added in 7.1.6 release // Logging logging; - moved to the separate 'settings' file public StateHeader() { } public StateHeader(String projectKind, String startNodeName, String version) { super(); this.projectKind = projectKind; this.startNodeName = startNodeName; this.version = version; } public StateHeader(String projectKind, String startNodeName, String version, String owner) { super(); this.projectKind = projectKind; this.startNodeName = startNodeName; this.version = version; this.owner = owner; } public String getProjectKind() { return projectKind; } public String getStartNodeName() { return startNodeName; } public String getVersion() { return version; } public String getOwner() { return owner; } public void setOwner(String owner2) { this.owner = owner2; } public void setVersion(String version) { this.version = version; } } }
33,231
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GenerateInstanceId.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/GenerateInstanceId.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.application; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.InstanceIdDao; import org.restcomm.connect.dao.entities.InstanceId; import org.restcomm.connect.commons.dao.Sid; import javax.servlet.ServletContext; import javax.servlet.sip.SipURI; import java.net.UnknownHostException; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public class GenerateInstanceId { private final Logger logger = Logger.getLogger(GenerateInstanceId.class); // private final Configuration configuration; private final ServletContext servletContext; private final InstanceIdDao instanceIdDao; private final String host; public GenerateInstanceId(ServletContext servletContext, final SipURI sipURI) throws UnknownHostException { this.servletContext = servletContext; host = sipURI.getHost()+":"+sipURI.getPort(); logger.info("Host for InstanceId: "+host); instanceIdDao = ((DaoManager) servletContext.getAttribute(DaoManager.class.getName())).getInstanceIdDao(); } public InstanceId instanceId() { InstanceId instanceId = instanceIdDao.getInstanceIdByHost(host); if (instanceId != null) { if(logger.isInfoEnabled()) { logger.info("Restcomm Instance ID: "+instanceId.toString()); } } else { instanceId = new InstanceId(Sid.generate(Sid.Type.INSTANCE), host, DateTime.now(), DateTime.now()); instanceIdDao.addInstancecId(instanceId); if(logger.isInfoEnabled()) { logger.info("Restcomm Instance ID created: "+instanceId.toString()); } } servletContext.setAttribute(InstanceId.class.getName(), instanceId); return instanceId; } }
2,792
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RvdProjectsMigrator.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/RvdProjectsMigrator.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.application; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.joda.time.DateTimeZone; import org.joda.time.LocalDateTime; import javax.servlet.ServletContext; import java.io.File; import java.io.FileWriter; import java.net.URISyntaxException; import java.sql.Timestamp; import java.util.List; /** * The goal of this class is to generate an Application entity inside the database for each RVD project located inside its * workspace. Also, apply the new naming convention on project directories inside the workspace, based on a new * {@link Sid.Type.PROJECT} generated to each entry. * * @author [email protected] */ public class RvdProjectsMigrator { private static final Logger logger = Logger.getLogger(RvdProjectsMigrator.class); private static final String separator = "--------------------------------------"; private RvdProjectsMigrationHelper migrationHelper; private List<String> projectNames; private boolean migrationSucceeded; private Integer errorCode; private String logPath; private int projectsProcessed; private int projectsSuccess; private int projectsError; private int updatedDids; private int updatedClients; public RvdProjectsMigrator(ServletContext servletContext, Configuration configuration) throws Exception { this.migrationHelper = new RvdProjectsMigrationHelper(servletContext, configuration); this.migrationSucceeded = true; this.logPath = servletContext.getRealPath("/") + "../../../"; // Equivalent to RESTCOMM_HOME this.errorCode = 0; this.projectsProcessed = 0; this.projectsSuccess = 0; this.projectsError = 0; this.updatedDids = 0; this.updatedClients = 0; } public void executeMigration() throws Exception { String beginning = getTimeStamp(); // Ensure the migration needs to be executed if (!migrationHelper.isMigrationEnabled() || migrationHelper.isMigrationExecuted()) { storeNewMessage("Workspace migration skipped in " + beginning, true, true, true, false); storeNewMessage(separator, false, true, false, false); return; } storeNewMessage("Starting workspace migration at " + beginning, true, true, true, false); storeNewMessage(separator, false, true, false, false); try { if (!migrationHelper.isEmbeddedMigration()) { backupWorkspace(); } loadProjectsList(); } catch (RvdProjectsMigrationException e) { migrationSucceeded = false; errorCode = e.getErrorCode(); storeNewMessage(e.getMessage(), true, true, false, true); try { storeMigrationStatus(); } catch (Exception x) { storeNewMessage("[ERROR-CODE:2] Error while storing workspace status" + x.getMessage(), true, true, false, true); } throw e; } for (String projectName : projectNames) { try { // Load Project State Header migrationHelper.loadProjectState(projectName); // Check if this project is already synchronized with a application String applicationSid = searchApplicationSid(projectName); // Synchronize with application entity if needed applicationSid = synchronizeApplicationEntity(applicationSid, projectName); // Rename Project migrateNamingConvention(projectName, applicationSid); // Update IncomingPhoneNumbers updateIncomingPhoneNumbers(applicationSid, projectName); // Update Clients updateClients(applicationSid, projectName); projectsSuccess++; } catch (RvdProjectsMigrationException e) { migrationSucceeded = false; if (errorCode == 0) { // Keep the first error only errorCode = e.getErrorCode(); } projectsError++; storeNewMessage("Error while migrating project '" + projectName + "' " + e.getMessage(), false, true, false, true); } projectsProcessed++; storeNewMessage(separator, false, true, false, false); } try { storeMigrationStatus(); } catch (Exception e) { storeNewMessage("[ERROR-CODE:2] Error while storing workspace status " + e, true, true, false, true); throw e; } } private void loadProjectsList() throws Exception { this.projectNames = migrationHelper.listProjects(); } private String searchApplicationSid(String projectName) throws RvdProjectsMigrationException { return migrationHelper.searchApplicationSid(projectName); } private String synchronizeApplicationEntity(String applicationSid, String projectName) throws RvdProjectsMigrationException, URISyntaxException { if (!projectName.equals(applicationSid)) { applicationSid = migrationHelper.createOrUpdateApplicationEntity(applicationSid, projectName); storeNewMessage("Project '" + projectName + "' synchronized with Application '" + applicationSid + "'", false, true, false, false); } else { storeNewMessage("Project '" + projectName + "' previously synchronized with Application '" + applicationSid + "'. Skipped", false, true, false, false); } return applicationSid; } private void migrateNamingConvention(String projectName, String applicationSid) throws RvdProjectsMigrationException, URISyntaxException { if (!projectName.equals(applicationSid)) { migrationHelper.renameProjectUsingNewConvention(projectName, applicationSid); storeNewMessage("Project '" + projectName + "' renamed to '" + applicationSid + "'", false, true, false, false); } else { storeNewMessage("Project " + projectName + " already using new naming convention. Skipped", false, true, false, false); } } private void updateIncomingPhoneNumbers(String applicationSid, String projectName) throws RvdProjectsMigrationException, URISyntaxException { int amountUpdated = migrationHelper.updateIncomingPhoneNumbers(applicationSid, projectName); if (amountUpdated > 0) { storeNewMessage("Updated " + amountUpdated + " IncomingPhoneNumbers with Application '" + applicationSid + "'", false, true, false, false); updatedDids += amountUpdated; } else { storeNewMessage("No IncomingPhoneNumbers found to update with Application '" + applicationSid + "'. Skipped", false, true, false, false); } } private void updateClients(String applicationSid, String projectName) throws RvdProjectsMigrationException, URISyntaxException { int amountUpdated = migrationHelper.updateClients(applicationSid, projectName); if (amountUpdated > 0) { storeNewMessage("Updated " + amountUpdated + " Clients with Application '" + applicationSid + "'", false, true, false, false); updatedClients += amountUpdated; } else { storeNewMessage("No Clients found to update with Application '" + applicationSid + "'. Skipped", false, true, false, false); } } private void storeMigrationStatus() throws RvdProjectsMigrationException, URISyntaxException { migrationHelper.storeWorkspaceStatus(migrationSucceeded); String end = getTimeStamp(); if (!migrationSucceeded) { String message = "Workspace migration finished with errors at " + end; message += ". Status: " + projectsProcessed + " Projects processed ("; message += projectsSuccess + " with success and " + projectsError + " with error), "; message += updatedDids + " IncomingPhoneNumbers and " + updatedClients + " Clients updated"; storeNewMessage(message, true, true, true, true); storeNewMessage(separator, false, true, false, false); sendEmailNotification(message); } else { String message = "Workspace migration finished with success at " + end; message += ". Status: " + projectsProcessed + " Projects processed ("; message += projectsSuccess + " with success and " + projectsError + " with error), "; message += updatedDids + " IncomingPhoneNumbers and " + updatedClients + " Clients updated"; storeNewMessage(message, true, true, true, false); storeNewMessage(separator, false, true, false, false); sendEmailNotification(message); } } private void storeNewMessage(String message, boolean asServerLog, boolean asMigrationLog, boolean asNotification, boolean error) throws RvdProjectsMigrationException, URISyntaxException { // Write to server log if (asServerLog) { if (error) { logger.error(message); } else if(logger.isInfoEnabled()) { logger.info(message); } } // Write to migration log, but use server log if embedded migration if (asMigrationLog) { if (!migrationHelper.isEmbeddedMigration()) { storeLogMessage(message); } else if (!asServerLog) { // Prevent duplicated messages if (error) { logger.error(message); } else if(logger.isInfoEnabled()) { logger.info(message); } } } // Create new notification if (asNotification) { storeNewNotification(message); } } private void storeLogMessage(String message) throws RvdProjectsMigrationException, URISyntaxException { try { String pathName = logPath + "workspace-migration.log"; File file = new File(pathName); if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file, true); fw.write(message + "\n"); fw.close(); } catch (Exception e) { storeNewMessage("[ERROR-CODE:3] Error while writing to file RESTCOMM_HOME/workspace-migration.log", true, false, false, true); } } private String getTimeStamp() { LocalDateTime date = LocalDateTime.now(); DateTimeZone tz = DateTimeZone.getDefault(); return new Timestamp(date.toDateTime(tz).toDateTime(DateTimeZone.UTC).getMillis()).toString(); } private void storeNewNotification(String message) throws URISyntaxException { migrationHelper.addNotification(message, migrationSucceeded, new Integer(errorCode)); } private void sendEmailNotification(String message) throws RvdProjectsMigrationException, URISyntaxException { try { migrationHelper.sendEmailNotification(message, migrationSucceeded); } catch (RvdProjectsMigrationException e) { storeNewMessage("[ERROR-CODE:4] Workspace migration email notification skipped due to invalid configuration", true, true, false, true); storeNewMessage(separator, false, true, false, false); } } private void backupWorkspace() throws RvdProjectsMigrationException { migrationHelper.backupWorkspace(); } }
12,736
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConfigurationStringLookup.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.application/src/main/java/org/restcomm/connect/application/config/ConfigurationStringLookup.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.application.config; import java.util.HashMap; import java.util.Map; import org.apache.commons.lang.text.StrLookup; /** * @author [email protected] (Thomas Quintana) */ public class ConfigurationStringLookup extends StrLookup { private final Map<String, String> dictionary; public ConfigurationStringLookup() { super(); dictionary = new HashMap<String, String>(); } public void addProperty(final String name, final String value) { dictionary.put(name, value); } @Override public String lookup(final String key) { final String result = dictionary.get(key); if (result != null) { return result; } else { return key; } } }
1,587
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Mail.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.email.api/src/main/java/org/restcomm/connect/email/api/Mail.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.api; import org.joda.time.DateTime; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Lefteris Banos) */ @Immutable public final class Mail { private final String from; private final String to; private final String cc; private final String bcc; private final String subject; private final String body; private final DateTime dateSent; private final String accountSid; private final String contentType; public Mail(final String from, final String to, final String subject, final String body) { this(from, to, subject, body, "", "", DateTime.now(), "", "text/plain"); } public Mail(final String from, final String to, final String subject, final String body, final String cc, final String bcc) { this(from, to, subject, body, cc, bcc, DateTime.now(), "", "text/plain"); } public Mail(final String from, final String to, final String subject, final String body, final String cc, final String bcc, final DateTime dateSent, final String accountSid) { this(from, to, subject, body, cc, bcc, dateSent, accountSid, "text/plain"); } public Mail(final String from, final String to, final String subject, final String body, final String cc, final String bcc, final DateTime dateSent, final String accountSid, final String contentType) { this.from = from; this.to = to; this.cc = cc; this.bcc = bcc; this.subject = subject; this.body = body; this.dateSent = dateSent; this.accountSid = accountSid; this.contentType = contentType; } public String from() { return from; } public String to() { return to; } public String cc() { return cc; } public String bcc() { return bcc; } public String subject() { return subject; } public String body() { return body; } public String contentType() { return contentType; } public String accountSid() { return accountSid; } public DateTime dateSent() { return dateSent; } }
3,022
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EmailResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.email.api/src/main/java/org/restcomm/connect/email/api/EmailResponse.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.api; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author [email protected] (Lefteris Banos) */ public class EmailResponse<T> extends StandardResponse <T> { public EmailResponse(final T object) { super(object); } public EmailResponse(final Throwable cause) { super(cause); } public EmailResponse(final Throwable cause, final String message) { super(cause, message); } }
1,296
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
EmailRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.email.api/src/main/java/org/restcomm/connect/email/api/EmailRequest.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.api; /** * @author [email protected] (Lefteris Banos) */ public class EmailRequest { private final Mail emailmsg; public EmailRequest(Mail object){ super(); this.emailmsg=object; } public Mail getObject(){ return this.emailmsg; } }
1,130
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DownloaderTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/test/java/org/restcomm/connect/http/client/DownloaderTest.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.http.client; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import com.github.tomakehurst.wiremock.junit.WireMockRule; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.concurrent.TimeUnit; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.XMLConfiguration; import org.apache.http.conn.ConnectionPoolTimeoutException; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import scala.concurrent.duration.FiniteDuration; /** * @author [email protected] (Thomas Quintana) */ public final class DownloaderTest { private ActorSystem system; private ActorRef downloader; private static int MOCK_PORT = 8099; //use localhost instead of 127.0.0.1 to match the route rule private static String PATH = "http://localhost:" + MOCK_PORT + "/"; @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().bindAddress("127.0.0.1").port(MOCK_PORT)); public DownloaderTest() { super(); } @Before public void before() throws Exception { URL url = this.getClass().getResource("/restcomm_downloader.xml"); Configuration xml = new XMLConfiguration(url); RestcommConfiguration.createOnce(xml); system = ActorSystem.create(); downloader = system.actorOf(new Props(Downloader.class)); } @After public void after() throws Exception { system.shutdown(); wireMockRule.resetRequests(); } @Test public void testGet() throws URISyntaxException, IOException { stubFor(get(urlMatching("/testGet")).willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("expectedBody"))); new JavaTestKit(system) { { final ActorRef observer = getRef(); final URI uri = URI.create(PATH + "testGet"); final String method = "GET"; final HttpRequestDescriptor request = new HttpRequestDescriptor(uri, method); downloader.tell(request, observer); final FiniteDuration timeout = FiniteDuration.create(30, TimeUnit.SECONDS); final DownloaderResponse response = expectMsgClass(timeout, DownloaderResponse.class); assertTrue(response.succeeded()); final HttpResponseDescriptor descriptor = response.get(); System.out.println("Result: " + descriptor.getContentAsString()); assertTrue(descriptor.getContentAsString().contains("expectedBody")); } }; } @Test @Ignore public void testPost() throws URISyntaxException, IOException { stubFor(post(urlMatching("/testPost")).willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("expectedBody"))); new JavaTestKit(system) { { final ActorRef observer = getRef(); final URI uri = URI.create(PATH + "testPost"); final String method = "POST"; final HttpRequestDescriptor request = new HttpRequestDescriptor(uri, method); downloader.tell(request, observer); final FiniteDuration timeout = FiniteDuration.create(30, TimeUnit.SECONDS); final DownloaderResponse response = expectMsgClass(timeout, DownloaderResponse.class); assertTrue(response.succeeded()); final HttpResponseDescriptor descriptor = response.get(); assertTrue(descriptor.getContentAsString().contains("expectedBody")); } }; } @Test public void testNotFound() throws URISyntaxException, IOException { stubFor(get(urlMatching("/testNotFound")).willReturn(aResponse() .withStatus(404) .withHeader("Content-Type", "application/json") .withBody("{}"))); new JavaTestKit(system) { { final ActorRef observer = getRef(); final URI uri = URI.create(PATH + "testNotFound"); final String method = "GET"; final HttpRequestDescriptor request = new HttpRequestDescriptor(uri, method); downloader.tell(request, observer); final FiniteDuration timeout = FiniteDuration.create(30, TimeUnit.SECONDS); final DownloaderResponse response = expectMsgClass(timeout, DownloaderResponse.class); assertTrue(response.succeeded()); final HttpResponseDescriptor descriptor = response.get(); assertEquals(404, descriptor.getStatusCode()); } }; } /** * configuration comes from restcomm.xml file * * @throws Exception */ @Test() public void testDownloaderWithRouteconfiguration() throws Exception { stubFor(get(urlMatching("/testDownloaderWithRouteconfiguration")).willReturn(aResponse() .withFixedDelay(5000 * 2)//delay will cause read timeout to happen .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{}"))); new JavaTestKit(system) { { int connsPerRoute = 5; final URI uri = URI.create(PATH + "testDownloaderWithRouteconfiguration"); final String method = "GET"; final HttpRequestDescriptor request = new HttpRequestDescriptor(uri, method); final ActorRef observer = getRef(); for (int i =0; i < connsPerRoute; i ++) { downloader = system.actorOf(new Props(Downloader.class)); downloader.tell(request, observer); } Thread.sleep(1000); downloader = system.actorOf(new Props(Downloader.class)); downloader.tell(request, observer); final FiniteDuration timeout = FiniteDuration.create(30, TimeUnit.SECONDS); final DownloaderResponse response = expectMsgClass(timeout, DownloaderResponse.class); assertFalse(response.succeeded()); //JavaTestKit dont allow to throw exception and use "expected" assertEquals(ConnectionPoolTimeoutException.class, response.cause().getClass()); } }; } }
8,089
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApiClientTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/test/java/org/restcomm/connect/http/client/api/ApiClientTests.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.http.client.api; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; 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 org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.CallDetailRecordsDao; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.http.client.CallApiResponse; import org.restcomm.connect.telephony.api.Hangup; import com.github.tomakehurst.wiremock.junit.WireMockRule; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import akka.testkit.JavaTestKit; import scala.concurrent.duration.FiniteDuration; /** * @author maria.farooq */ public final class ApiClientTests { private ActorSystem system; private static int MOCK_PORT = 8099; 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"; @Rule public WireMockRule wireMockRule = new WireMockRule(wireMockConfig().bindAddress("127.0.0.1").port(MOCK_PORT)); public ApiClientTests() { super(); } @Before public void before() throws Exception { URL url = this.getClass().getResource("/restcomm.xml"); Configuration xml = new XMLConfiguration(url); RestcommConfiguration.createOnce(xml); system = ActorSystem.create(); } @After public void after() throws Exception { system.shutdown(); wireMockRule.resetRequests(); } private Props CallApiClientProps(final DaoManager storage){ final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new CallApiClient(null, storage); } }); return props; } @Test public void testCallApiTimeoutTermination() throws URISyntaxException, IOException, InterruptedException { stubFor(get(urlMatching("/testGet")).willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("expectedBody"))); new JavaTestKit(system) { { final ActorRef observer = getRef(); DaoManager daoManager = mock(DaoManager.class); CallDetailRecord.Builder cdrBuilder = CallDetailRecord.builder(); cdrBuilder.setSid(TEST_CALL_SID); cdrBuilder.setUri(new URI(TEST_CALL_URI)); CallDetailRecord cdr = cdrBuilder.build(); CallDetailRecordsDao cdrDao = mock(CallDetailRecordsDao.class); when(daoManager.getCallDetailRecordsDao()).thenReturn(cdrDao); when(cdrDao.getCallDetailRecord(any(Sid.class))).thenReturn(cdr); ActorRef callApiClient = system.actorOf(CallApiClientProps(daoManager)); callApiClient.tell(new ReceiveTimeout() {}, observer); final FiniteDuration timeout = FiniteDuration.create(15, TimeUnit.SECONDS); final CallApiResponse response = expectMsgClass(timeout, CallApiResponse.class); assertFalse(response.succeeded()); Thread.sleep(1000); assertTrue(callApiClient.isTerminated()); } }; } @Test public void testCallApiClientFailedResponse() throws URISyntaxException, IOException, InterruptedException { stubFor(get(urlMatching("/testGet")).willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("expectedBody"))); new JavaTestKit(system) { { final ActorRef observer = getRef(); DaoManager daoManager = mock(DaoManager.class); CallDetailRecord.Builder cdrBuilder = CallDetailRecord.builder(); cdrBuilder.setSid(TEST_CALL_SID); cdrBuilder.setUri(new URI(TEST_CALL_URI)); CallDetailRecord cdr = cdrBuilder.build(); CallDetailRecordsDao cdrDao = mock(CallDetailRecordsDao.class); when(daoManager.getCallDetailRecordsDao()).thenReturn(cdrDao); when(cdrDao.getCallDetailRecord(any(Sid.class))).thenReturn(cdr); ActorRef callApiClient = system.actorOf(CallApiClientProps(daoManager)); callApiClient.tell(new Hangup("test", new Sid("ACae6e420f425248d6a26948c17a9e2acf"), null), observer); final FiniteDuration timeout = FiniteDuration.create(15, TimeUnit.SECONDS); final CallApiResponse response = expectMsgClass(timeout, CallApiResponse.class); assertFalse(response.succeeded()); } }; } }
6,969
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RcmlserverResolverTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/test/java/org/restcomm/connect/http/client/rcmlserver/resolver/RcmlserverResolverTest.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.http.client.rcmlserver.resolver; import junit.framework.Assert; import org.junit.Test; import java.net.URI; import java.net.URISyntaxException; /** * @author [email protected] - Orestis Tsakiridis */ public class RcmlserverResolverTest { @Test public void testResolving() throws URISyntaxException { RcmlserverResolver resolver = RcmlserverResolver.getInstance("http://rvdserver.org","/visual-designer/services/", true); URI uri = resolver.resolveRelative(new URI("/visual-designer/services/apps/AP5f58b0baf6e14001b6eec02295fab05a/controller")); // relative urls to actual RVD applications should get prefixed Assert.assertEquals("http://rvdserver.org/visual-designer/services/apps/AP5f58b0baf6e14001b6eec02295fab05a/controller", uri.toString()); // absolute urls should not be touched uri = resolver.resolveRelative(new URI("http://externalserver/AP5f58b0baf6e14001b6eec02295fab05a/controller")); Assert.assertEquals("http://externalserver/AP5f58b0baf6e14001b6eec02295fab05a/controller", uri.toString()); // relative urls pointing to other (non-rvd) apps uri = resolver.resolveRelative(new URI("/restcomm/demos/hellp-play.xml")); Assert.assertEquals("/restcomm/demos/hellp-play.xml", uri.toString()); // make sure that RVD path can vary. Assume it's '/new-rvd' now resolver = RcmlserverResolver.getInstance("http://rvdserver.org","/new-rvd/services/", true); uri = resolver.resolveRelative(new URI("/new-rvd/myapp.xml")); Assert.assertEquals("http://rvdserver.org/new-rvd/myapp.xml", uri.toString()); // if rcmlserver.baseUrl is null, no resolving should occur resolver = RcmlserverResolver.getInstance(null,"/visual-designer/services", true); uri = resolver.resolveRelative(new URI("/visual-designer/services/apps/xxxx")); Assert.assertEquals("/visual-designer/services/apps/xxxx", uri.toString()); // if rcmlserver.apiPath is null or empty, no resolving should occur resolver = RcmlserverResolver.getInstance("http://rvdotsakir.org","", true); uri = resolver.resolveRelative(new URI("/visual-designer/services/apps/xxxx")); Assert.assertEquals("/visual-designer/services/apps/xxxx", uri.toString()); // all nulls resolver = RcmlserverResolver.getInstance(null,null, true); uri = resolver.resolveRelative(new URI("/visual-designer/services/apps/xxxx")); Assert.assertEquals("/visual-designer/services/apps/xxxx", uri.toString()); } }
3,403
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GatherSpeechTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/test/java/org/restcomm/connect/interpreter/GatherSpeechTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.net.URI; 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.http.NameValuePair; import org.joda.time.DateTime; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; import org.mockito.internal.stubbing.answers.ClonesArguments; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.restcomm.connect.commons.cache.DiskCacheRequest; import org.restcomm.connect.commons.cache.DiskCacheResponse; import org.restcomm.connect.commons.configuration.RestcommConfiguration; 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.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.http.client.DownloaderResponse; import org.restcomm.connect.http.client.HttpRequestDescriptor; import org.restcomm.connect.http.client.HttpResponseDescriptor; import org.restcomm.connect.interpreter.rcml.MockedActor; import org.restcomm.connect.interpreter.rcml.domain.GatherAttributes; import org.restcomm.connect.mscontrol.api.messages.Collect; import org.restcomm.connect.mscontrol.api.messages.CollectedResult; import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.Play; 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.Hangup; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; 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 akka.testkit.TestActorRef; import org.junit.Assert; import org.restcomm.connect.dao.entities.MediaAttributes; /** * Created by gdubina on 6/24/17. */ public class GatherSpeechTest { private static UriUtils uriUtils; private static ActorSystem system; private Configuration configuration; private URI requestUri = URI.create("http://127.0.0.1/gather.xml"); private URI playUri = URI.create("http://127.0.0.1/play.wav"); private URI actionCallbackUri = URI.create("http://127.0.0.1/gather-action.xml"); private URI partialCallbackUri = URI.create("http://127.0.0.1/gather-partial.xml"); private String endRcml = "<Response><Hangup/></Response>"; private String playRcml = "<Response><Play>" + playUri + "</Play></Response>"; private String gatherRcmlPartial = "<Response><Gather " + GatherAttributes.ATTRIBUTE_INPUT + "=\"speech\" " + GatherAttributes.ATTRIBUTE_ACTION + "=\"" + actionCallbackUri + "\" " + GatherAttributes.ATTRIBUTE_PARTIAL_RESULT_CALLBACK + "=\"" + partialCallbackUri + "\" " + GatherAttributes.ATTRIBUTE_NUM_DIGITS + "=\"1\" " + GatherAttributes.ATTRIBUTE_TIME_OUT + "=\"60\">" + "</Gather></Response>"; private String gatherRcmlNoPartial = "<Response><Gather " + GatherAttributes.ATTRIBUTE_INPUT + "=\"speech\" " + GatherAttributes.ATTRIBUTE_ACTION + "=\"" + actionCallbackUri + "\" " + GatherAttributes.ATTRIBUTE_NUM_DIGITS + "=\"1\" " + GatherAttributes.ATTRIBUTE_TIME_OUT + "=\"60\">" + "</Gather></Response>"; private String gatherEmpty = "<Response><Gather " + GatherAttributes.ATTRIBUTE_PARTIAL_RESULT_CALLBACK + "=\"" + partialCallbackUri + "\">" + "</Gather></Response>"; private String gatherRcmlWithHints = "<Response><Gather " + GatherAttributes.ATTRIBUTE_INPUT + "=\"speech\" " + GatherAttributes.ATTRIBUTE_ACTION + "=\"" + actionCallbackUri + "\" " + GatherAttributes.ATTRIBUTE_NUM_DIGITS + "=\"1\" " + GatherAttributes.ATTRIBUTE_TIME_OUT + "=\"60\" " + GatherAttributes.ATTRIBUTE_HINTS + "=\"" + "Telestax’s RestcommONE platform is changing the way real-time communications are developed and delivered. " + "It is fast becoming the platform of choice for rapidly building enterprise class real-time messaging, voice and video applications. " + "Our platform is scalable, highly available and the only WebRTC platform that supports cloud, on premise and hybrid deployment configurations.\">" + "</Gather></Response>"; public GatherSpeechTest() { super(); } @BeforeClass public static void before() throws Exception { uriUtils = Mockito.mock(UriUtils.class); RestcommConnectServiceProvider.getInstance().setUriUtils(uriUtils); Mockito.when(uriUtils.resolveWithBase(Mockito.any(URI.class), Mockito.any(URI.class))).thenAnswer(new Answer() { public Object answer (InvocationOnMock invocation) { return invocation.getArguments()[1]; }}); Mockito.when(uriUtils.resolve(Mockito.any(URI.class), Mockito.any(Sid.class))).thenAnswer(new Answer() { public Object answer (InvocationOnMock invocation) { return invocation.getArguments()[0]; }}); system = ActorSystem.create(); } @AfterClass public static void after() throws Exception { system.shutdown(); } @Before public void init() { String restcommXmlPath = this.getClass().getResource("/restcomm.xml").getFile(); try { configuration = getConfiguration(restcommXmlPath); RestcommConfiguration.createOnce(configuration); } catch (ConfigurationException e) { throw new RuntimeException(); } } private Configuration getConfiguration(String path) throws ConfigurationException { XMLConfiguration xmlConfiguration = new XMLConfiguration(); xmlConfiguration.setDelimiterParsingDisabled(true); xmlConfiguration.setAttributeSplittingDisabled(true); xmlConfiguration.load(path); return xmlConfiguration; } private HttpResponseDescriptor getOk(URI uri) { HttpResponseDescriptor.Builder builder = HttpResponseDescriptor.builder(); builder.setURI(uri); builder.setStatusCode(200); builder.setStatusDescription("OK"); builder.setContentLength(0); return builder.build(); } private HttpResponseDescriptor getOkRcml(URI uri, String rcml) { HttpResponseDescriptor.Builder builder = HttpResponseDescriptor.builder(); builder.setURI(uri); builder.setStatusCode(200); builder.setStatusDescription("OK"); builder.setContent(rcml); builder.setContentLength(rcml.length()); builder.setContentType("text/xml"); return builder.build(); } private TestActorRef<VoiceInterpreter> createVoiceInterpreter(final ActorRef observer) { //dao final CallDetailRecordsDao recordsDao = mock(CallDetailRecordsDao.class); when(recordsDao.getCallDetailRecord(any(Sid.class))).thenReturn(null); final DaoManager storage = mock(DaoManager.class); when(storage.getCallDetailRecordsDao()).thenReturn(recordsDao); //actors final ActorRef downloader = new MockedActor("downloader") .add(DiskCacheRequest.class, new DiskCacheRequestProperty(playUri), new DiskCacheResponse(playUri)) .asRef(system); final ActorRef callManager = new MockedActor("callManager").asRef(system); final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder(); builder.setConfiguration(configuration); builder.setStorage(storage); builder.setCallManager(callManager); builder.setAccount(new Sid("ACae6e420f425248d6a26948c17a9e2acf")); builder.setVersion("2012-04-24"); builder.setUrl(requestUri); builder.setMethod("GET"); builder.setAsImsUa(false); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new VoiceInterpreter(builder.build()) { @Override protected ActorRef downloader() { return observer; } @Override protected ActorRef httpAsycClientHelper(){ return observer; } @Override protected ActorRef cache(String path, String uri) { return downloader; } @Override public ActorRef getCache() { return downloader; } }; } }); return TestActorRef.create(system, props, "VoiceInterpreter" + System.currentTimeMillis());//system.actorOf(props); } @Test @SuppressWarnings("unchecked") public void testPartialHangupScenario() throws Exception { new JavaTestKit(system) { { final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); //wait for rcml downloading HttpRequestDescriptor callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), requestUri); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, gatherRcmlPartial)), observer); expectMsgClass(Collect.class); //generate partial response1 interpreter.tell(new MediaGroupResponse(new CollectedResult("1", true, true)), observer); callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), partialCallbackUri); assertEquals(findParam(callback.getParameters(), "UnstableSpeechResult").getValue(), "1"); interpreter.tell(new DownloaderResponse(getOkRcml(partialCallbackUri, "")), observer); //generate partial response2 interpreter.tell(new MediaGroupResponse(new CollectedResult("12", true, true)), observer); callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), partialCallbackUri); assertEquals(findParam(callback.getParameters(), "UnstableSpeechResult").getValue(), "12"); //generate final response interpreter.tell(new MediaGroupResponse(new CollectedResult("Hello. World.", true, false)), observer); callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(actionCallbackUri, callback.getUri()); assertEquals(findParam(callback.getParameters(), "SpeechResult").getValue(), "Hello. World."); interpreter.tell(new DownloaderResponse(getOkRcml(actionCallbackUri, endRcml)), observer); expectMsgClass(Hangup.class); } }; } @Test @SuppressWarnings("unchecked") public void testFinalResultAndHangupScenario() throws Exception { new JavaTestKit(system) { { final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); //wait for rcml downloading HttpRequestDescriptor callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), requestUri); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, gatherRcmlNoPartial)), observer); expectMsgClass(Collect.class); //generate final response interpreter.tell(new MediaGroupResponse(new CollectedResult("Hello. World.", true, false)), observer); callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), actionCallbackUri); assertEquals(findParam(callback.getParameters(), "SpeechResult").getValue(), "Hello. World."); interpreter.tell(new DownloaderResponse(getOkRcml(actionCallbackUri, endRcml)), observer); expectMsgClass(Hangup.class); } }; } @Test @SuppressWarnings("unchecked") public void testPartialAndPlayScenario() throws Exception { new JavaTestKit(system) { { final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); //wait for rcml downloading HttpRequestDescriptor callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), requestUri); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, gatherRcmlPartial)), observer); expectMsgClass(Collect.class); //generate partial response1 interpreter.tell(new MediaGroupResponse(new CollectedResult("1", true, true)), observer); callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), partialCallbackUri); assertEquals(findParam(callback.getParameters(), "UnstableSpeechResult").getValue(), "1"); interpreter.tell(new DownloaderResponse(getOk(partialCallbackUri)), observer); //generate partial response2 interpreter.tell(new MediaGroupResponse(new CollectedResult("12", true, true)), observer); callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), partialCallbackUri); assertEquals(findParam(callback.getParameters(), "UnstableSpeechResult").getValue(), "12"); //generate final response interpreter.tell(new MediaGroupResponse(new CollectedResult("Hello. World.", true, false)), observer); callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), actionCallbackUri); assertEquals(findParam(callback.getParameters(), "SpeechResult").getValue(), "Hello. World."); interpreter.tell(new DownloaderResponse(getOkRcml(actionCallbackUri, playRcml)), observer); //wait for new tag: Play DiskCacheRequest diskCacheRequest = expectMsgClass(DiskCacheRequest.class); interpreter.tell(new DiskCacheResponse(diskCacheRequest.uri()), observer); expectMsgClass(Play.class); //simulate play is finished interpreter.tell(new MediaGroupResponse(new CollectedResult("", false, false)), observer); expectMsgClass(Hangup.class); } }; } @Test @SuppressWarnings("unchecked") public void testFinalResultAndPlayScenario() throws Exception { new JavaTestKit(system) { { final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); //wait for rcml downloading HttpRequestDescriptor callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), requestUri); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, gatherRcmlNoPartial)), observer); expectMsgClass(Collect.class); //generate final response interpreter.tell(new MediaGroupResponse(new CollectedResult("Hello. World.", true, false)), observer); callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), actionCallbackUri); assertEquals(findParam(callback.getParameters(), "SpeechResult").getValue(), "Hello. World."); interpreter.tell(new DownloaderResponse(getOkRcml(actionCallbackUri, playRcml)), observer); //wait for new tag: Play DiskCacheRequest diskCacheRequest = expectMsgClass(DiskCacheRequest.class); interpreter.tell(new DiskCacheResponse(diskCacheRequest.uri()), observer); expectMsgClass(Play.class); //simulate play is finished interpreter.tell(new MediaGroupResponse(new CollectedResult("", false, false)), observer); expectMsgClass(Hangup.class); } }; } @Test @SuppressWarnings("unchecked") public void testValidateDefaultAttributeValues() throws Exception { new JavaTestKit(system) { { final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); //wait for rcml downloading HttpRequestDescriptor callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), requestUri); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, gatherEmpty)), observer); Collect collect = expectMsgClass(Collect.class); assertEquals(Collect.Type.DTMF, collect.type()); assertEquals("en-US", collect.lang()); assertEquals("#", collect.endInputKey()); assertSame(5, collect.timeout()); assertEquals("google", collect.getDriver()); } }; } @Test @SuppressWarnings("unchecked") public void testOnMediaGroupResponseEmptyCollectedResult() throws Exception { new JavaTestKit(system) { { final ActorRef observer = getRef(); final TestActorRef<VoiceInterpreter> interpreterRef = createVoiceInterpreter(observer); VoiceInterpreter interpreter = interpreterRef.underlyingActor(); interpreter.fsm = spy(new FiniteStateMachine(interpreter.gathering, interpreter.transitions)); doNothing().when(interpreter.fsm).transition(any(), eq(interpreter.finishGathering)); interpreter.collectedDigits = new StringBuffer(); interpreterRef.tell(new MediaGroupResponse(new CollectedResult("", false, false)), observer); assertSame(0, interpreter.collectedDigits.length()); } }; } @Test @SuppressWarnings("unchecked") public void testIgnoreRcmlFromPartialCallback() throws Exception { new JavaTestKit(system) { { final ActorRef observer = getRef(); final TestActorRef<VoiceInterpreter> interpreterRef = createVoiceInterpreter(observer); VoiceInterpreter interpreter = interpreterRef.underlyingActor(); interpreter.fsm = spy(new FiniteStateMachine(interpreter.gathering, interpreter.transitions)); interpreterRef.tell(new DownloaderResponse(getOk(partialCallbackUri)), observer); verify(interpreter.fsm, never()).transition(any(), any(State.class)); } }; } @Test @SuppressWarnings("unchecked") public void testDtmfFromMediaServer() throws Exception { new JavaTestKit(system) { { final ActorRef observer = getRef(); final TestActorRef<VoiceInterpreter> interpreterRef = createVoiceInterpreter(observer); VoiceInterpreter interpreter = interpreterRef.underlyingActor(); interpreter.fsm = spy(new FiniteStateMachine(interpreter.gathering, interpreter.transitions)); doNothing().when(interpreter.fsm).transition(any(), eq(interpreter.finishGathering)); interpreter.collectedDigits = new StringBuffer(); interpreter.finishOnKey="#"; interpreterRef.tell(new MediaGroupResponse(new CollectedResult("5", false, false)), observer); assertEquals("5", interpreter.collectedDigits.toString()); } }; } @Test public void testHintsLimits() { new JavaTestKit(system) { { final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); //wait for rcml downloading HttpRequestDescriptor callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), requestUri); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, gatherRcmlWithHints)), observer); expectMsgClass(Hangup.class); } }; } @Test public void testStartInputKeys() { final String inputKeys = "1234"; final String GATHER_WITH_START_INPUT = "<Response><Gather " + GatherAttributes.ATTRIBUTE_PARTIAL_RESULT_CALLBACK + "=\"" + partialCallbackUri + "\" " + GatherAttributes.ATTRIBUTE_TIME_OUT + "=\"60\" " + GatherAttributes.ATTRIBUTE_START_INPUT_KEY + "=\"" + inputKeys + "\" " + ">" + "</Gather></Response>"; new JavaTestKit(system) { { final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); //wait for rcml downloading HttpRequestDescriptor callback = expectMsgClass(HttpRequestDescriptor.class); assertEquals(callback.getUri(), requestUri); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, GATHER_WITH_START_INPUT)), observer); Collect collectCmd = expectMsgClass(Collect.class); Assert.assertTrue( collectCmd.hasStartInputKey()); assertEquals(inputKeys, collectCmd.startInputKey()); } }; } private NameValuePair findParam(final List<NameValuePair> params, final String key) { return Iterables.find(params, new Predicate<NameValuePair>() { public boolean apply(NameValuePair p) { return key.equals(p.getName()); } }); } public static class DiskCacheRequestProperty extends MockedActor.SimplePropertyPredicate<DiskCacheRequest, URI> { static Function<DiskCacheRequest, URI> extractor = new Function<DiskCacheRequest, URI>() { @Override public URI apply(DiskCacheRequest diskCacheRequest) { return diskCacheRequest.uri(); } }; public DiskCacheRequestProperty(URI value) { super(value, extractor); } } }
31,199
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StopMediaGroupTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/test/java/org/restcomm/connect/interpreter/mediagroup/StopMediaGroupTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2017, 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.interpreter.mediagroup; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActorFactory; import akka.testkit.JavaTestKit; import akka.testkit.TestActorRef; import com.google.common.base.Function; import junit.runner.Version; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.joda.time.DateTime; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.Mockito; import org.restcomm.connect.commons.HttpConnector; import org.restcomm.connect.commons.cache.DiskCacheRequest; import org.restcomm.connect.commons.cache.DiskCacheResponse; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.fsm.State; 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.IncomingPhoneNumbersDao; import org.restcomm.connect.dao.entities.MediaAttributes; 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.Fork; import org.restcomm.connect.interpreter.StartInterpreter; import org.restcomm.connect.interpreter.VoiceInterpreter; import org.restcomm.connect.interpreter.VoiceInterpreterParams; import org.restcomm.connect.interpreter.rcml.MockedActor; import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.Play; import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup; 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.Hangup; import scala.concurrent.ExecutionContext; import javax.servlet.ServletContext; import java.net.URI; /** * @author [email protected] */ public class StopMediaGroupTest { private static ActorSystem system; private Configuration configuration; private MockedActor mockedCallManager; private URI requestUri = URI.create("http://127.0.0.1/gather.xml"); private String dialRcmlNoAction = "<Response><Dial><Client>bob</Client><Client>alice</Client></Dial></Response>"; private String dialRcmlAction = "<Response><Dial action=\"http://127.0.0.1:8989\"><Client>bob</Client><Client>alice</Client></Dial></Response>"; private URI playUri = URI.create("http://127.0.0.1/play.wav"); public StopMediaGroupTest() { super(); } @BeforeClass public static void before() throws Exception { system = ActorSystem.create(); } @AfterClass public static void after() throws Exception { system.shutdown(); } @Before public void init() { String restcommXmlPath = this.getClass().getResource("/restcomm.xml").getFile(); try { configuration = getConfiguration(restcommXmlPath); RestcommConfiguration.createOnce(configuration); } catch (ConfigurationException e) { throw new RuntimeException(); } } private Configuration getConfiguration(String path) throws ConfigurationException { XMLConfiguration xmlConfiguration = new XMLConfiguration(); xmlConfiguration.setDelimiterParsingDisabled(true); xmlConfiguration.setAttributeSplittingDisabled(true); xmlConfiguration.load(path); return xmlConfiguration; } private HttpResponseDescriptor getOkRcml(URI uri, String rcml) { HttpResponseDescriptor.Builder builder = HttpResponseDescriptor.builder(); builder.setURI(uri); builder.setStatusCode(200); builder.setStatusDescription("OK"); builder.setContent(rcml); builder.setContentLength(rcml.length()); builder.setContentType("text/xml"); return builder.build(); } private TestActorRef<Actor> createVoiceInterpreter(final ActorRef observer, final String ... fsmStateBypass) { System.out.println("JUnit version is: " + Version.id()); DaoManager storage = Mockito.mock(DaoManager.class); UriUtils uriUtils = Mockito.mock(UriUtils.class); RestcommConnectServiceProvider.getInstance().setUriUtils(uriUtils); Mockito.when(uriUtils.resolve(Mockito.any(URI.class), Mockito.any(Sid.class))).thenReturn(URI.create("http://127.0.0.1")); //dao final CallDetailRecordsDao recordsDao = Mockito.mock(CallDetailRecordsDao.class); Mockito.when(recordsDao.getCallDetailRecord(Mockito.any(Sid.class))).thenReturn(null); IncomingPhoneNumbersDao incomingPhoneNumbersDao = Mockito.mock(IncomingPhoneNumbersDao.class); Mockito.when(storage.getCallDetailRecordsDao()).thenReturn(recordsDao); //actors final ActorRef downloader = new MockedActor("downloader") .add(DiskCacheRequest.class, new DiskCacheRequestProperty(playUri), new DiskCacheResponse(playUri)) .asRef(system); mockedCallManager = new MockedActor("callManager"); final ActorRef callManager = mockedCallManager.asRef(system); final VoiceInterpreterParams.Builder builder = new VoiceInterpreterParams.Builder(); builder.setConfiguration(configuration); builder.setStorage(storage); builder.setCallManager(callManager); builder.setAccount(new Sid("ACae6e420f425248d6a26948c17a9e2acf")); builder.setVersion("2012-04-24"); builder.setUrl(requestUri); builder.setMethod("GET"); builder.setAsImsUa(false); final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new VoiceInterpreter(builder.build()){ @Override protected ActorRef downloader() { return observer; } @Override protected ActorRef cache(String path, String uri) { return downloader; } @Override public ActorRef getCache() { return downloader; } @Override protected boolean is(State state) { //bypass fsm state so the test logic can be reduced String id = state.getId(); for(int i = 0; i < fsmStateBypass.length; i++){ if(id.equals(fsmStateBypass[i])){ return true; } } //if there is no state to bypass, stick to formal verification return super.is(state); } }; } }); return TestActorRef.create(system, props, "VoiceInterpreter" + System.currentTimeMillis()); } @Test public void testForkingBusyStop() throws Exception { new JavaTestKit(system){ { //creating and starting vi final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer, "forking"); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); //notifying vi that the last/only call answered with busy final CallStateChanged callStateChanged = new CallStateChanged(CallStateChanged.State.BUSY); interpreter.tell(callStateChanged, null); //check if StopMediaGroup was requested to media actors //this request originally continues through the actors Call > CallController > MediaGroup //reaching media server and stopping whats currently playing. But at this test, both call and //vi actors are using the same observer, so we receive StopMediaGroup directly expectMsgClass(StopMediaGroup.class); //emulate the response that comes from media server, through media group, reaching vi interpreter.tell(new MediaGroupResponse<String>("stopped"), observer); //check if vi stays still and DO NOT ask for next verb expectNoMsg(); } }; } @Test public void testForkingBusyStopNextVerb() throws Exception { new JavaTestKit(system){ { //creating and starting vi final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); //creating new call interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); expectMsgClass(HttpRequestDescriptor.class); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, dialRcmlNoAction)), observer); expectNoMsg(); //force forking state at FSM interpreter.tell(new Fork(), observer); expectMsgClass(Play.class); //notifying vi that the last/only call answered as busy final CallStateChanged callStateChanged = new CallStateChanged(CallStateChanged.State.BUSY); interpreter.tell(callStateChanged, null); //check if StopMediaGroup was requested to media actors //this request originally continues through the actors Call > CallController > MediaGroup //reaching media server and stopping whats currently playing. But at this test, both call and //vi actors are using the same observer, so we receive StopMediaGroup directly expectMsgClass(StopMediaGroup.class); //emulate the response that comes from media server, through media group, reaching vi interpreter.tell(new MediaGroupResponse<String>("stopped"), observer); //check if vi asked for next verb, reaching End tag and consequently hangs up the call expectMsgClass(Hangup.class); } }; } @Test public void testForkingTimeoutStop() throws Exception { new JavaTestKit(system){ { //creating and starting vi final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); //creating new call interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); expectMsgClass(HttpRequestDescriptor.class); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, dialRcmlAction)), observer); expectNoMsg(); //force forking state at FSM interpreter.tell(new Fork(), observer); expectMsgClass(Play.class); //notifying vi that the last/only call reached timeout ReceiveTimeout timeout = new ReceiveTimeout(){}; interpreter.tell(timeout, observer); //check if StopMediaGroup was requested to media actors //this request originally continues through the actors Call > CallController > MediaGroup //reaching media server and stopping whats currently playing. But at this test, both call and //vi actors are using the same observer, so we receive StopMediaGroup directly expectMsgClass(StopMediaGroup.class); //emulate the response that comes from media server, through media group, reaching vi interpreter.tell(new MediaGroupResponse<String>("stopped"), observer); //check if vi stays still and DO NOT ask for next verb expectNoMsg(); } }; } @Test public void testForkingTimeoutStopNextVerb() throws Exception { new JavaTestKit(system){ { //creating and starting vi final ActorRef observer = getRef(); final ActorRef interpreter = createVoiceInterpreter(observer); interpreter.tell(new StartInterpreter(observer), observer); expectMsgClass(GetCallInfo.class); //creating new call interpreter.tell(new CallResponse(new CallInfo( new Sid("ACae6e420f425248d6a26948c17a9e2acf"), new Sid("ACae6e420f425248d6a26948c17a9e2acf"), CallStateChanged.State.IN_PROGRESS, CreateCallType.SIP, "inbound", new DateTime(), null, "test", "test", "testTo", null, null, false, false, false, new DateTime(), new MediaAttributes())), observer); expectMsgClass(Observe.class); expectMsgClass(HttpRequestDescriptor.class); interpreter.tell(new DownloaderResponse(getOkRcml(requestUri, dialRcmlNoAction)), observer); expectNoMsg(); //force forking state at FSM interpreter.tell(new Fork(), observer); expectMsgClass(Play.class); //notifying vi that the last/only call reached timeout ReceiveTimeout timeout = new ReceiveTimeout(){}; interpreter.tell(timeout, observer); //check if StopMediaGroup was requested to media actors //this request originally continues through the actors Call > CallController > MediaGroup //reaching media server and stopping whats currently playing. But at this test, both call and //vi actors are using the same observer, so we receive StopMediaGroup directly expectMsgClass(StopMediaGroup.class); //emulate the response that comes from media server, through media group, reaching vi interpreter.tell(new MediaGroupResponse<String>("stopped"), observer); //check if vi asked for next verb, reaching End tag and consequently hangs up the call expectMsgClass(Hangup.class); } }; } public static class DiskCacheRequestProperty extends MockedActor.SimplePropertyPredicate<DiskCacheRequest, URI> { static Function<DiskCacheRequest, URI> extractor = new Function<DiskCacheRequest, URI>() { @Override public URI apply(DiskCacheRequest diskCacheRequest) { return diskCacheRequest.uri(); } }; public DiskCacheRequestProperty(URI value) { super(value, extractor); } } }
18,401
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ParserTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/test/java/org/restcomm/connect/interpreter/rcml/ParserTest.java
package org.restcomm.connect.interpreter.rcml; /* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import akka.testkit.JavaTestKit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import java.io.InputStream; import java.util.List; import static org.junit.Assert.assertTrue; import static org.restcomm.connect.interpreter.rcml.Verbs.dial; import static org.restcomm.connect.interpreter.rcml.Verbs.gather; import static org.restcomm.connect.interpreter.rcml.Verbs.pause; import static org.restcomm.connect.interpreter.rcml.Verbs.play; import static org.restcomm.connect.interpreter.rcml.Verbs.record; import static org.restcomm.connect.interpreter.rcml.Verbs.say; /** * @author [email protected] (Thomas Quintana) */ public final class ParserTest { private static ActorSystem system; public ParserTest() { super(); } @BeforeClass public static void before() throws Exception { system = ActorSystem.create(); } @AfterClass public static void after() throws Exception { system.shutdown(); } private ActorRef parser(final InputStream input) { return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Parser(input, null, null); } })); } private ActorRef parser(final String input) { return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new Parser(input, null); } })); } @Test public void testParser() { final InputStream input = getClass().getResourceAsStream("/rcml.xml"); new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new parser. final GetNextVerb next = new GetNextVerb(); final ActorRef parser = parser(input); // Start consuming verbs until the end of the document. parser.tell(next, observer); Tag verb = expectMsgClass(Tag.class); assertTrue(record.equals(verb.name())); assertTrue(verb.attribute("action").value().equals("https://127.0.0.1:8080/restcomm/demos/hello-world.jsp")); assertTrue(verb.attribute("method").value().equals("GET")); assertTrue(verb.attribute("maxLength").value().equals("60")); assertTrue(verb.attribute("timeout").value().equals("5")); assertTrue(verb.attribute("finishOnKey").value().equals("#")); assertTrue(verb.attribute("transcribe").value().equals("true")); assertTrue(verb.attribute("transcribeCallback").value().equals("transcribe.jsp")); assertTrue(verb.attribute("playBeep").value().equals("false")); parser.tell(next, observer); verb = expectMsgClass(Tag.class); assertTrue(gather.equals(verb.name())); assertTrue(verb.attribute("timeout").value().equals("30")); assertTrue(verb.attribute("finishOnKey").value().equals("#")); assertTrue(verb.hasChildren()); final List<Tag> children = verb.children(); Tag child = children.get(0); assertTrue(say.equals(child.name())); assertTrue(child.attribute("voice").value().equals("man")); assertTrue(child.attribute("language").value().equals("en")); assertTrue(child.attribute("loop").value().equals("1")); assertTrue(child.text().equals("Hello World!")); child = children.get(1); assertTrue(play.equals(child.name())); assertTrue(child.attribute("loop").value().equals("1")); assertTrue(child.text().equals("https://127.0.0.1:8080/restcomm/audio/hello-world.wav")); child = children.get(2); assertTrue(pause.equals(child.name())); assertTrue(child.attribute("length").value().equals("1")); parser.tell(next, observer); expectMsgClass(End.class); } }; } @Test // Test for SIP Noun Parsing for Issue // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out public void testParserDialSIP() { final InputStream input = getClass().getResourceAsStream("/rcml-sip.xml"); new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new parser. final GetNextVerb next = new GetNextVerb(); final ActorRef parser = parser(input); // Start consuming verbs until the end of the document. parser.tell(next, observer); Tag verb = expectMsgClass(Tag.class); assertTrue(dial.equals(verb.name())); assertTrue(verb.attribute("record").value().equals("true")); assertTrue(verb.attribute("timeout").value().equals("10")); assertTrue(verb.attribute("hangupOnStar").value().equals("true")); assertTrue(verb.attribute("callerId").value().equals("bob")); assertTrue(verb.attribute("method").value().equals("POST")); assertTrue(verb.attribute("action").value().equals("/handle_post_dial")); final List<Tag> children = verb.children(); Tag child = children.get(0); assertTrue(Nouns.SIP.equals(child.name())); assertTrue(child.attribute("username").value().equals("admin")); assertTrue(child.attribute("password").value().equals("1234")); assertTrue(child.attribute("method").value().equals("POST")); assertTrue(child.attribute("url").value().equals("/handle_screening_on_answer")); assertTrue(child.text().equals("sip:[email protected]?customheader=foo")); parser.tell(next, observer); expectMsgClass(End.class); } }; } @Test // Test for SIP Noun Parsing for Issue // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out public void testParserDialSIPText() { final String rcmlContent = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<Response>\n" + "<Dial\n" + " record=\"true\"\n" + " timeout=\"10\"\n" + " hangupOnStar=\"true\"\n" + " callerId=\"bob\"\n" + " method=\"POST\"\n" + " action=\"/handle_post_dial\">\n" + "<Sip \n" + " username=\"admin\"\n" + " password=\"1234\"\n" + " method=\"POST\"\n" + " url=\"/handle_screening_on_answer\">\n" + "sip:[email protected]?customheader=foo&myotherheader=bar\n" + "</Sip>\n" + "</Dial>\n" + "</Response>"; // final InputStream input = getClass().getResourceAsStream("/rcml-sip.xml"); new JavaTestKit(system) { { final ActorRef observer = getRef(); // Create a new parser. final GetNextVerb next = new GetNextVerb(); System.out.println(rcmlContent); final ActorRef parser = parser(rcmlContent); // Start consuming verbs until the end of the document. parser.tell(next, observer); Tag verb = expectMsgClass(Tag.class); assertTrue(dial.equals(verb.name())); assertTrue(verb.attribute("record").value().equals("true")); assertTrue(verb.attribute("timeout").value().equals("10")); assertTrue(verb.attribute("hangupOnStar").value().equals("true")); assertTrue(verb.attribute("callerId").value().equals("bob")); assertTrue(verb.attribute("method").value().equals("POST")); assertTrue(verb.attribute("action").value().equals("/handle_post_dial")); final List<Tag> children = verb.children(); Tag child = children.get(0); assertTrue(Nouns.SIP.equals(child.name())); assertTrue(child.attribute("username").value().equals("admin")); assertTrue(child.attribute("password").value().equals("1234")); assertTrue(child.attribute("method").value().equals("POST")); assertTrue(child.attribute("url").value().equals("/handle_screening_on_answer")); assertTrue(child.text().equals("sip:[email protected]?customheader=foo&myotherheader=bar")); parser.tell(next, observer); expectMsgClass(End.class); } }; } }
9,924
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MockedActor.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/test/java/org/restcomm/connect/interpreter/rcml/MockedActor.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; import akka.actor.*; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import org.mockito.stubbing.Answer1; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by gdubina on 6/24/17. */ public class MockedActor { private final Map<Class<?>, List<Object>> mapping; private final String name; public MockedActor(String name, Map<Class<?>, List<Object>> mapping) { super(); this.name = name; this.mapping = mapping; } public MockedActor(String name) { this(name, new HashMap<Class<?>, List<Object>>()); } public void onReceive(ActorRef self, ActorRef sender, Object msg) throws Throwable { List<Object> responses = this.mapping.get(msg.getClass()); if (responses == null || responses.isEmpty()) { System.err.println("MockedActor." + name + ": unhandled request - " + msg); return; } for (Object response : responses) { if (response instanceof Answer1) { response = ((Answer1) response).answer(msg); if (response instanceof Optional) { Optional resp = ((Optional) response); if (resp.isPresent()) { response = resp.get(); } else { continue; } } } sender.tell(response, self); return; } } public MockedActor add(Class<?> clazz, Object resp) { List<Object> responses = mapping.get(clazz); if (responses == null) { mapping.put(clazz, responses = new ArrayList<>()); } responses.add(resp); return this; } public MockedActor add(final Class<?> request, final Predicate<Object> matcher, final Object resp) { this.add(request, new Answer1<Optional, Object>() { @Override public Optional answer(Object msg) throws Throwable { if (matcher.apply(msg)) { return Optional.fromNullable(resp); } return Optional.absent(); } }); return this; } private class MockedActorRef extends UntypedActor { public MockedActorRef() { } @Override public void onReceive(Object o) throws Exception { try { MockedActor.this.onReceive(self(), sender(), o); } catch (Throwable t) { throw new RuntimeException(t); } } } public ActorRef asRef(ActorSystem system) { return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new MockedActorRef(); } })); } public static class SimplePropertyPredicate<T, P> implements Predicate<Object> { private final P value; private final Function<T, P> extractor; public SimplePropertyPredicate(P value, Function<T, P> extractor) { this.value = value; this.extractor = extractor; } @Override public boolean apply(Object t) { return value.equals(extractor.apply((T) t)); } } }
4,345
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpResponseDescriptor.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/HttpResponseDescriptor.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.http.client; import java.io.IOException; import java.net.URI; import org.apache.http.Header; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.util.HttpUtils; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class HttpResponseDescriptor { private final URI uri; private final int statusCode; private final String statusDescription; private final String content; private final long contentLength; private final String contentEncoding; private final String contentType; private final boolean isChunked; private final Header[] headers; private HttpResponseDescriptor(final URI uri, final int statusCode, final String statusDescription, final String content, final long contentLength, final String contentEncoding, final String contentType, final boolean isChunked, final Header[] headers) { super(); this.uri = uri; this.statusCode = statusCode; this.statusDescription = statusDescription; this.content = content; this.contentLength = contentLength; this.contentEncoding = contentEncoding; this.contentType = contentType; this.isChunked = isChunked; this.headers = headers; } public int getStatusCode() { return statusCode; } public String getStatusDescription() { return statusDescription; } // public InputStream getContent() { // return content; // } public String getContentAsString() throws IOException { // if (buffer != null) { // return buffer; // } else { // synchronized (this) { // if (buffer == null) { // buffer = StringUtils.toString(content); // } // } // return buffer; // } return content; } public long getContentLength() { return contentLength; } public String getContentEncoding() { return contentEncoding; } public String getContentType() { return contentType; } public boolean isChunked() { return isChunked; } public Header[] getHeaders() { return headers; } public String getHeadersAsString() { return HttpUtils.toString(headers); } public URI getURI() { return uri; } public static Builder builder() { return new Builder(); } public static final class Builder { private URI uri; private int statusCode; private String statusDescription; private String content; private long contentLength; private String contentEncoding; private String contentType; private boolean isChunked; private Header[] headers; private Builder() { super(); } public HttpResponseDescriptor build() { return new HttpResponseDescriptor(uri, statusCode, statusDescription, content, contentLength, contentEncoding, contentType, isChunked, headers); } public void setStatusCode(final int statusCode) { this.statusCode = statusCode; } public void setStatusDescription(final String statusDescription) { this.statusDescription = statusDescription; } public void setContent(final String content) { this.content = content; } public void setContentLength(final long contentLength) { this.contentLength = contentLength; } public void setContentEncoding(final String contentEncoding) { this.contentEncoding = contentEncoding; } public void setContentType(final String contentType) { this.contentType = contentType; } public void setIsChunked(final boolean isChunked) { this.isChunked = isChunked; } public void setHeaders(final Header[] headers) { this.headers = headers; } public void setURI(final URI uri) { this.uri = uri; } } }
5,039
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpRequestDescriptor.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/HttpRequestDescriptor.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.http.client; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URIBuilder; import org.apache.http.client.utils.URLEncodedUtils; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class HttpRequestDescriptor { private final URI uri; private final String method; private final List<NameValuePair> parameters; private final Integer timeout; private final Header[] headers; public HttpRequestDescriptor(final URI uri, final String method, final List<NameValuePair> parameters, final Integer timeout, final Header[] headers) { super(); this.timeout = timeout; this.uri = base(uri); this.method = method; if (parameters != null) { this.parameters = parameters; } else { this.parameters = new ArrayList<NameValuePair>(); } final String query = uri.getQuery(); if (query != null) { //FIXME:should we externalize RVD encoding default? final List<NameValuePair> other = URLEncodedUtils.parse(uri, "UTF-8"); parameters.addAll(other); } this.headers = headers; } public HttpRequestDescriptor(final URI uri, final String method, final List<NameValuePair> parameters, final Integer timeout){ this(uri, method, parameters, timeout, null); } public HttpRequestDescriptor(final URI uri, final String method, final List<NameValuePair> parameters) { this(uri,method,parameters, -1); } public HttpRequestDescriptor(final URI uri, final String method) throws UnsupportedEncodingException, URISyntaxException { this(uri, method, null); } private URI base(final URI uri) { try { URIBuilder uriBuilder = new URIBuilder(); uriBuilder.setScheme(uri.getScheme()); uriBuilder.setHost(uri.getHost()); uriBuilder.setPort(uri.getPort()); uriBuilder.setPath(uri.getPath()); if(uri.getUserInfo() != null){ uriBuilder.setUserInfo(uri.getUserInfo()); } return uriBuilder.build(); } catch (final URISyntaxException ignored) { // This should never happen since we are using a valid URI to construct ours. return null; } } public String getMethod() { return method; } public List<NameValuePair> getParameters() { return parameters; } public String getParametersAsString() { //FIXME:should we externalize RVD encoding default? return URLEncodedUtils.format(parameters, "UTF-8"); } public URI getUri() { return uri; } public Integer getTimeout() { return timeout; } public Header[] getHeaders() { return headers; } }
3,993
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Downloader.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/Downloader.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.http.client; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import org.apache.commons.io.IOUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.HttpRequest; 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.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.restcomm.connect.commons.common.http.CustomHttpClientBuilder; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.xml.sax.InputSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.stream.XMLStreamException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; /** * @author [email protected] (Thomas Quintana) */ public final class Downloader extends RestcommUntypedActor { public static final int LOGGED_RESPONSE_MAX_SIZE = 100; private CloseableHttpClient client = null; // Logger. private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); public Downloader () { super(); client = (CloseableHttpClient) CustomHttpClientBuilder.buildDefaultClient(RestcommConfiguration.getInstance().getMain()); } public HttpResponseDescriptor fetch (final HttpRequestDescriptor descriptor) throws IllegalArgumentException, IOException, URISyntaxException, XMLStreamException { int code = -1; HttpRequest request = null; CloseableHttpResponse response = null; HttpRequestDescriptor temp = descriptor; HttpResponseDescriptor responseDescriptor = null; HttpResponseDescriptor rawResponseDescriptor = null; try { do { request = request(temp); //FIXME:should we externalize RVD encoding default? request.setHeader("http.protocol.content-charset", "UTF-8"); if (descriptor.getTimeout() > 0){ HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG, RequestConfig.custom(). setConnectTimeout(descriptor.getTimeout()). setSocketTimeout(descriptor.getTimeout()). setConnectionRequestTimeout(descriptor.getTimeout()).build()); response = client.execute((HttpUriRequest) request, httpContext); } else { response = client.execute((HttpUriRequest) request); } code = response.getStatusLine().getStatusCode(); if (isRedirect(code)) { final Header header = response.getFirstHeader(HttpHeaders.LOCATION); if (header != null) { final String location = header.getValue(); final URI uri = URI.create(location); temp = new HttpRequestDescriptor(uri, temp.getMethod(), temp.getParameters()); continue; } else { break; } } // HttpResponseDescriptor httpResponseDescriptor = response(request, response); rawResponseDescriptor = response(request, response); responseDescriptor = validateXML(rawResponseDescriptor); } while (isRedirect(code)); if (isHttpError(code)) { // TODO - usually this part of code is not reached. Error codes are part of error responses that do not pass validateXML above and an exception is thrown. We need to re-thing this String requestUrl = request.getRequestLine().getUri(); String errorReason = response.getStatusLine().getReasonPhrase(); String httpErrorMessage = String.format( "Problem while fetching http resource: %s \n Http status code: %d \n Http status message: %s", requestUrl, code, errorReason); logger.warning(httpErrorMessage); } } catch (Exception e) { logger.warning("Problem while trying to download RCML from {}, exception: {}", request.getRequestLine(), e); String statusInfo = "n/a"; String responseInfo = "n/a"; if (response != null) { // Build additional information to log. Include http status, url and a small fragment of the response. statusInfo = response.getStatusLine().toString(); if (rawResponseDescriptor != null) { int truncatedSize = (int) Math.min(rawResponseDescriptor.getContentLength(), LOGGED_RESPONSE_MAX_SIZE); if (rawResponseDescriptor.getContentAsString() != null) { responseInfo = String.format("%s %s", rawResponseDescriptor.getContentAsString().substring(0, truncatedSize), (rawResponseDescriptor.getContentLength() < LOGGED_RESPONSE_MAX_SIZE ? "" : "...")); } } } logger.warning(String.format("Problem while trying to download RCML. URL: %s, Status: %s, Response: %s ", request.getRequestLine(), statusInfo, responseInfo)); throw e; // re-throw } finally { if (response != null) { response.close(); } } return responseDescriptor; } private boolean isRedirect (final int code) { return HttpStatus.SC_MOVED_PERMANENTLY == code || HttpStatus.SC_MOVED_TEMPORARILY == code || HttpStatus.SC_SEE_OTHER == code || HttpStatus.SC_TEMPORARY_REDIRECT == code; } private boolean isHttpError (final int code) { return (code >= 400); } private HttpResponseDescriptor validateXML (final HttpResponseDescriptor descriptor) throws XMLStreamException { if (descriptor.getContentLength() > 0) { try { // parse an XML document into a DOM tree String xml = descriptor.getContentAsString().trim().replaceAll("&([^;]+(?!(?:\\w|;)))", "&amp;$1"); DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder(); //FIXME:should we externalize RVD encoding default? parser.parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))); return descriptor; } catch (final Exception e) { throw new XMLStreamException("Error parsing the RCML:" + e); } } return descriptor; } @Override public void onReceive (final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (HttpRequestDescriptor.class.equals(klass)) { final HttpRequestDescriptor request = (HttpRequestDescriptor) message; if (logger.isDebugEnabled()) { logger.debug("New HttpRequestDescriptor, method: " + request.getMethod() + " URI: " + request.getUri() + " parameters: " + request.getParametersAsString()); } DownloaderResponse response = null; try { response = new DownloaderResponse(fetch(request)); } catch (final Exception exception) { response = new DownloaderResponse(exception, "Problem while trying to download RCML"); } if (sender != null && !sender.isTerminated()) { sender.tell(response, self); } else { if (logger.isInfoEnabled()) { logger.info("DownloaderResponse wont be send because sender is :" + (sender.isTerminated() ? "terminated" : "null")); } } } } public HttpUriRequest request (final HttpRequestDescriptor descriptor) throws IllegalArgumentException, URISyntaxException, UnsupportedEncodingException { final URI uri = descriptor.getUri(); final String method = descriptor.getMethod(); if ("GET".equalsIgnoreCase(method)) { final String query = descriptor.getParametersAsString(); URI result = null; if (query != null && !query.isEmpty()) { result = new URIBuilder() .setScheme(uri.getScheme()) .setHost(uri.getHost()) .setPort(uri.getPort()) .setPath(uri.getPath()) .setQuery(query) .build(); } else { result = uri; } return new HttpGet(result); } else if ("POST".equalsIgnoreCase(method)) { final List<NameValuePair> parameters = descriptor.getParameters(); final HttpPost post = new HttpPost(uri); //FIXME:should we externalize RVD encoding default? post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); return post; } else { throw new IllegalArgumentException(method + " is not a supported downloader method."); } } private HttpResponseDescriptor response (final HttpRequest request, final HttpResponse response) throws IOException { final HttpResponseDescriptor.Builder builder = HttpResponseDescriptor.builder(); final URI uri = URI.create(request.getRequestLine().getUri()); builder.setURI(uri); builder.setStatusCode(response.getStatusLine().getStatusCode()); builder.setStatusDescription(response.getStatusLine().getReasonPhrase()); builder.setHeaders(response.getAllHeaders()); final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream stream = entity.getContent(); try { final Header contentEncoding = entity.getContentEncoding(); //FIXME:should we externalize RVD encoding default? String encodingValue = "UTF-8"; if (contentEncoding != null && !contentEncoding.getValue().isEmpty()) { encodingValue = contentEncoding.getValue(); builder.setContentEncoding(encodingValue); } final Header contentType = entity.getContentType(); if (contentType != null) { builder.setContentType(contentType.getValue()); } builder.setContent(IOUtils.toString(stream, encodingValue)); builder.setContentLength(entity.getContentLength()); builder.setIsChunked(entity.isChunked()); } finally { stream.close(); } } return builder.build(); } @Override public void postStop () { if (logger.isDebugEnabled()) { logger.debug("Downloader at post stop"); } super.postStop(); } }
12,732
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DownloaderResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/DownloaderResponse.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.http.client; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author [email protected] (Thomas Quintana) */ public final class DownloaderResponse extends StandardResponse<HttpResponseDescriptor> { public DownloaderResponse(final HttpResponseDescriptor object) { super(object); } public DownloaderResponse(final Throwable cause) { super(cause); } public DownloaderResponse(final Throwable cause, final String message) { super(cause, message); } }
1,369
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallApiResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/CallApiResponse.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.http.client; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author Maria Farooq */ public final class CallApiResponse extends StandardResponse<HttpResponseDescriptor> { public CallApiResponse(final HttpResponseDescriptor object) { super(object); } public CallApiResponse(final Throwable cause) { super(cause); } public CallApiResponse(final Throwable cause, final String message) { super(cause, message); } }
1,326
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommApiClientUtil.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/api/RestcommApiClientUtil.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.http.client.api; import java.nio.charset.Charset; import org.apache.commons.codec.binary.Base64; import org.apache.http.Header; import org.apache.http.HttpHeaders; import org.apache.http.message.BasicHeader; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.dao.entities.Account; /** * @author maria.farooq */ public final class RestcommApiClientUtil { public static String getAuthenticationHeader(Sid sid, DaoManager storage) { Account requestingAccount = storage.getAccountsDao().getAccount(sid); String authenticationHeader = null; if(requestingAccount != null) { String auth = requestingAccount.getSid() + ":" + requestingAccount.getAuthToken(); byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); authenticationHeader = "Basic " + new String(encodedAuth); } return authenticationHeader; } public static Header[] getBasicHeaders(Sid sid, DaoManager storage){ Header authHeader = new BasicHeader(HttpHeaders.AUTHORIZATION, RestcommApiClientUtil.getAuthenticationHeader(sid, storage)); Header contentTypeHeader = new BasicHeader("Content-type", "application/x-www-form-urlencoded"); Header acceptHeader = new BasicHeader("Accept", "application/json"); Header[] headers = { authHeader , contentTypeHeader , acceptHeader }; return headers; } }
2,387
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallApiClient.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/api/CallApiClient.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.http.client.api; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActor; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import org.apache.http.Header; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; 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.dao.DaoManager; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.http.asyncclient.HttpAsycClientHelper; import org.restcomm.connect.http.client.CallApiResponse; import org.restcomm.connect.http.client.DownloaderResponse; import org.restcomm.connect.http.client.HttpRequestDescriptor; import org.restcomm.connect.telephony.api.Hangup; import scala.concurrent.duration.Duration; import java.net.URI; import java.net.URISyntaxException; import java.text.ParseException; import java.util.ArrayList; import java.util.concurrent.TimeUnit; /** * @author mariafarooq * Disposable call api client to be used for one request and get destroyed after that. * */ public class CallApiClient extends RestcommUntypedActor { private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private final DaoManager storage; private final Sid callSid; private CallDetailRecord callDetailRecord; private ActorRef requestee; private ActorRef httpAsycClientHelper; /** * @param callSid * @param storage */ public CallApiClient(final Sid callSid, final DaoManager storage) { super(); this.callSid = callSid; this.storage = storage; //actor will only live in memory for one hour context().setReceiveTimeout(Duration.create(3600, TimeUnit.SECONDS)); } @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(" ********** CallApiClient " + self().path() + " Sender: " + sender); logger.info(" ********** CallApiClient " + self().path() + " Processing Message: " + klass.getName()); } if (Hangup.class.equals(klass)) { onHangup((Hangup) message, self, sender); } else if (DownloaderResponse.class.equals(klass)) { onDownloaderResponse(message, self, sender); } else if (message instanceof ReceiveTimeout) { onDownloaderResponse(new DownloaderResponse(new Exception("Call Api stayed active too long")), self, sender); getContext().stop(self()); } } private void onDownloaderResponse(Object message, ActorRef self, ActorRef sender) { final DownloaderResponse response = (DownloaderResponse) message; if (logger.isInfoEnabled()) { logger.info("Call api response succeeded " + response.succeeded()); logger.info("Call api response: " + response); } requestee = requestee == null ? sender : requestee; CallApiResponse apiResponse; if (response.succeeded()) { apiResponse = new CallApiResponse(response.get()); } else { apiResponse = new CallApiResponse(response.cause(), response.error()); } requestee.tell(apiResponse, self); } protected void onHangup(Hangup message, ActorRef self, ActorRef sender) throws URISyntaxException, ParseException { requestee = sender; callDetailRecord = message.getCallDetailRecord() == null ? getCallDetailRecord() : message.getCallDetailRecord(); if(callDetailRecord == null){ logger.error("could not retrieve cdr by provided Sid"); onDownloaderResponse(new DownloaderResponse(new IllegalArgumentException("could not retrieve cdr by provided Sid")), self, sender); } else { try { URI uri = new URI("/restcomm"+callDetailRecord.getUri()); uri = RestcommConnectServiceProvider.getInstance().uriUtils().resolve(uri, callDetailRecord.getAccountSid()); if (logger.isInfoEnabled()) logger.info("call api uri is: "+uri); Header[] headers = RestcommApiClientUtil.getBasicHeaders(message.getRequestingAccountSid(), storage); ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); postParameters.add(new BasicNameValuePair("Status", "Completed")); httpAsycClientHelper = httpAsycClientHelper(); HttpRequestDescriptor httpRequestDescriptor =new HttpRequestDescriptor(uri, "POST", postParameters, -1, headers); httpAsycClientHelper.tell(httpRequestDescriptor, self); } catch (Exception e) { logger.error("Exception while trying to terminate call via api {} ", e); onDownloaderResponse(new DownloaderResponse(e), self, sender); } } } private CallDetailRecord getCallDetailRecord() { if(callSid != null){ return storage.getCallDetailRecordsDao().getCallDetailRecord(callSid); } return null; } private ActorRef httpAsycClientHelper(){ final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new HttpAsycClientHelper(); } }); return getContext().actorOf(props); } @Override public void postStop () { if (logger.isInfoEnabled()) { logger.info("CallApiClient at post stop"); } if(httpAsycClientHelper != null && !httpAsycClientHelper.isTerminated()) getContext().stop(httpAsycClientHelper); getContext().stop(self()); super.postStop(); } }
7,003
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RcmlserverResolver.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/client/rcmlserver/resolver/RcmlserverResolver.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.http.client.rcmlserver.resolver; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import java.net.URI; import java.net.URISyntaxException; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * A relative URI resolver for Rcmlserver/RVD. It values defined in rcmlserver restcomm.xml configuration * section (rcmlserver.base-url, rcmlserver.api-path) to convert relative urls to absolute i.e. prepent Rcmlserver origin (http://rcmlserver.domain:port). * By design, the resolver is used when resolving Application.rcmlUrl only. An additional filter prefix * is used and helps the resolver affect only urls that start with "/visual-designer/". This filter value is * configurable through rcmlserver.api-path. It will use whatever it between the first pair of slashes "/.../". * If configuration is missing or rcmlserver is deployed bundled with restcomm the resolver won't affect the * uri resolved, typically leaving UriUtils class take care of it. * * @author [email protected] - Orestis Tsakiridis */ public class RcmlserverResolver { protected static Logger logger = Logger.getLogger(RcmlserverResolver.class); static RcmlserverResolver singleton; String rvdOrigin; String filterPrefix; // a pattern used to match against relative urls in application.rcmlUrl. If null, to resolving will occur. static final String DEFAULT_FILTER_PREFIX = "/visual-designer/"; // not really a clean singleton pattern but a way to init once and use many. Only the first time this method is called the parameters are used in the initialization public static RcmlserverResolver getInstance(String rvdOrigin, String apiPath, boolean reinit) { if (singleton == null || reinit) { singleton = new RcmlserverResolver(rvdOrigin, apiPath); } return singleton; } public static RcmlserverResolver getInstance(String rvdOrigin, String apiPath) { return getInstance(rvdOrigin, apiPath, false); } public RcmlserverResolver(String rvdOrigin, String apiPath) { this.rvdOrigin = rvdOrigin; if ( ! StringUtils.isEmpty(apiPath) ) { // extract the first part of the path and use it as a filter prefix Pattern pattern = Pattern.compile("/([^/]*)((/.*)|$)"); Matcher matcher = pattern.matcher(apiPath); if (matcher.matches() && matcher.group(1) != null) { filterPrefix = "/" + matcher.group(1) + "/"; } else filterPrefix = DEFAULT_FILTER_PREFIX; logger.info("RcmlserverResolver initialized. Urls starting with '" + filterPrefix + "' will get prepended with '" + (rvdOrigin == null ? "" : rvdOrigin) + "'"); } else filterPrefix = null; } // if rvdOrigin is null no point in trying to resolve RVD location. We will return passed uri instead public URI resolveRelative(URI uri) { if (uri != null && rvdOrigin != null && filterPrefix != null) { if (uri.isAbsolute()) return uri; try { String uriString = uri.toString(); if (uriString.startsWith(filterPrefix)) return new URI(rvdOrigin + uri.toString()); } catch (URISyntaxException e) { logger.error("Cannot resolve uri: " + uri.toString() + ". Ignoring...", e); } } return uri; } }
4,292
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpAsycClientHelper.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/http/asyncclient/HttpAsycClientHelper.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.http.asyncclient; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.List; import javax.xml.stream.XMLStreamException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.client.utils.URIBuilder; import org.apache.http.concurrent.FutureCallback; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.restcomm.connect.commons.common.http.CustomHttpClientBuilder; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.commons.util.StringUtils; import org.restcomm.connect.http.client.DownloaderResponse; import org.restcomm.connect.http.client.HttpRequestDescriptor; import org.restcomm.connect.http.client.HttpResponseDescriptor; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; /** * @author maria.farooq */ public final class HttpAsycClientHelper extends RestcommUntypedActor { public static final int LOGGED_RESPONSE_MAX_SIZE = 100; private CloseableHttpAsyncClient client = null; // Logger. private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); public HttpAsycClientHelper () { super(); client = (CloseableHttpAsyncClient) CustomHttpClientBuilder.buildCloseableHttpAsyncClient(RestcommConfiguration.getInstance().getMain()); } @Override public void onReceive (final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef sender = sender(); if (logger.isInfoEnabled()) { logger.info(" ********** HttpAsycClientHelper " + self().path() + " Sender: " + sender); logger.info(" ********** HttpAsycClientHelper " + self().path() + " Processing Message: " + klass.getName()); } if (HttpRequestDescriptor.class.equals(klass)) { final HttpRequestDescriptor request = (HttpRequestDescriptor) message; if (logger.isDebugEnabled()) { logger.debug("New HttpRequestDescriptor, method: " + request.getMethod() + " URI: " + request.getUri() + " parameters: " + request.getParametersAsString()); } try { execute(request, sender); } catch (final Exception exception) { DownloaderResponse response = new DownloaderResponse(exception, "Problem while trying to exceute request"); sender.tell(response, self()); } } } public void execute (final HttpRequestDescriptor descriptor, ActorRef sender) throws IllegalArgumentException, IOException, URISyntaxException, XMLStreamException { HttpUriRequest request = null; HttpRequestDescriptor temp = descriptor; try { request = request(temp); request.setHeader("http.protocol.content-charset", "UTF-8"); if (descriptor.getTimeout() > 0){ HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG, RequestConfig.custom(). setConnectTimeout(descriptor.getTimeout()). setSocketTimeout(descriptor.getTimeout()). setConnectionRequestTimeout(descriptor.getTimeout()).build()); client.execute(request, httpContext, getFutureCallback(request, sender)); } else { client.execute(request, getFutureCallback(request, sender)); } } catch (Exception e) { logger.error("Problem while trying to execute http request {}, exception: {}", request.getRequestLine(), e); throw e; } } private FutureCallback<HttpResponse> getFutureCallback(final HttpUriRequest request, final ActorRef sender){ return new FutureCallback<HttpResponse>(){ @Override public void completed(HttpResponse result) { if (logger.isDebugEnabled()) { logger.debug(String.format("success on execution of http request. result %s", result)); } DownloaderResponse response = null; try { response = new DownloaderResponse(response(request, result)); } catch (IOException e) { logger.error("Exception while parsing response", e); response = new DownloaderResponse(e, "Exception while parsing response"); } sender.tell(response, self()); } @Override public void failed(Exception ex) { logger.error("got failure on executing http request {}, exception: {}", request.getRequestLine(), ex); DownloaderResponse response = new DownloaderResponse(ex, "got failure on executing http request"); sender.tell(response, self()); } @Override public void cancelled() { logger.warning("got cancellation on executing http request {}", request.getRequestLine()); DownloaderResponse response = new DownloaderResponse(new Exception("got cancellation on executing http request"), "got cancellation on executing http request"); sender.tell(response, self()); }}; } public HttpUriRequest request (final HttpRequestDescriptor descriptor) throws IllegalArgumentException, URISyntaxException, UnsupportedEncodingException { final URI uri = descriptor.getUri(); final String method = descriptor.getMethod(); HttpUriRequest httpUriRequest = null; if ("GET".equalsIgnoreCase(method)) { final String query = descriptor.getParametersAsString(); URI result = null; if (query != null && !query.isEmpty()) { result = new URIBuilder() .setScheme(uri.getScheme()) .setHost(uri.getHost()) .setPort(uri.getPort()) .setPath(uri.getPath()) .setQuery(query) .build(); } else { result = uri; } httpUriRequest = new HttpGet(result); } else if ("POST".equalsIgnoreCase(method)) { final List<NameValuePair> parameters = descriptor.getParameters(); final HttpPost post = new HttpPost(uri); post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8")); httpUriRequest = post; } else { throw new IllegalArgumentException(method + " is not a supported downloader method."); } if(descriptor.getHeaders() != null && descriptor.getHeaders().length>0){ httpUriRequest.setHeaders(descriptor.getHeaders()); } return httpUriRequest; } private HttpResponseDescriptor response (final HttpRequest request, final HttpResponse response) throws IOException { final HttpResponseDescriptor.Builder builder = HttpResponseDescriptor.builder(); final URI uri = URI.create(request.getRequestLine().getUri()); builder.setURI(uri); builder.setStatusCode(response.getStatusLine().getStatusCode()); builder.setStatusDescription(response.getStatusLine().getReasonPhrase()); builder.setHeaders(response.getAllHeaders()); final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream stream = entity.getContent(); try { final Header contentEncoding = entity.getContentEncoding(); if (contentEncoding != null) { builder.setContentEncoding(contentEncoding.getValue()); } final Header contentType = entity.getContentType(); if (contentType != null) { builder.setContentType(contentType.getValue()); } builder.setContent(StringUtils.toString(stream)); builder.setContentLength(entity.getContentLength()); builder.setIsChunked(entity.isChunked()); } finally { stream.close(); } } return builder.build(); } @Override public void postStop () { if (logger.isDebugEnabled()) { logger.debug("HttpAsycClientHelper at post stop"); } getContext().stop(self()); super.postStop(); } }
10,074
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoiceInterpreter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/VoiceInterpreter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActorContext; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.pattern.AskTimeoutException; import akka.util.Timeout; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; 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.joda.time.Interval; import org.restcomm.connect.asr.AsrResponse; import org.restcomm.connect.commons.cache.DiskCacheResponse; 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.StopObserving; 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.NotificationsDao; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.dao.entities.MediaAttributes; import org.restcomm.connect.dao.entities.Notification; import org.restcomm.connect.email.api.EmailResponse; import org.restcomm.connect.extension.api.ExtensionResponse; import org.restcomm.connect.extension.api.IExtensionFeatureAccessRequest; import org.restcomm.connect.extension.controller.ExtensionController; import org.restcomm.connect.fax.FaxResponse; import org.restcomm.connect.http.client.DownloaderResponse; import org.restcomm.connect.http.client.HttpRequestDescriptor; 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.Nouns; import org.restcomm.connect.interpreter.rcml.ParserFailed; import org.restcomm.connect.interpreter.rcml.Tag; import org.restcomm.connect.interpreter.rcml.Verbs; import org.restcomm.connect.interpreter.rcml.domain.GatherAttributes; import org.restcomm.connect.mscontrol.api.messages.CollectedResult; import org.restcomm.connect.mscontrol.api.messages.JoinComplete; import org.restcomm.connect.mscontrol.api.messages.Left; import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.Mute; import org.restcomm.connect.mscontrol.api.messages.Play; import org.restcomm.connect.mscontrol.api.messages.StartRecording; import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup; import org.restcomm.connect.mscontrol.api.messages.Unmute; import org.restcomm.connect.sms.api.SmsServiceResponse; import org.restcomm.connect.sms.api.SmsSessionResponse; import org.restcomm.connect.telephony.api.AddParticipant; import org.restcomm.connect.telephony.api.Answer; import org.restcomm.connect.telephony.api.BridgeManagerResponse; import org.restcomm.connect.telephony.api.BridgeStateChanged; import org.restcomm.connect.telephony.api.CallFail; import org.restcomm.connect.telephony.api.CallHoldStateChange; 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.Cancel; import org.restcomm.connect.telephony.api.ConferenceCenterResponse; import org.restcomm.connect.telephony.api.ConferenceInfo; import org.restcomm.connect.telephony.api.ConferenceModeratorPresent; import org.restcomm.connect.telephony.api.ConferenceResponse; import org.restcomm.connect.telephony.api.ConferenceStateChanged; import org.restcomm.connect.telephony.api.CreateBridge; import org.restcomm.connect.telephony.api.CreateCall; import org.restcomm.connect.telephony.api.CreateConference; import org.restcomm.connect.telephony.api.DestroyCall; import org.restcomm.connect.telephony.api.DestroyConference; import org.restcomm.connect.telephony.api.Dial; import org.restcomm.connect.telephony.api.FeatureAccessRequest; import org.restcomm.connect.telephony.api.GetCallInfo; import org.restcomm.connect.telephony.api.GetConferenceInfo; import org.restcomm.connect.telephony.api.GetRelatedCall; import org.restcomm.connect.telephony.api.Hangup; import org.restcomm.connect.telephony.api.JoinCalls; import org.restcomm.connect.telephony.api.Reject; import org.restcomm.connect.telephony.api.RemoveParticipant; import org.restcomm.connect.telephony.api.StartBridge; import org.restcomm.connect.telephony.api.StopBridge; import org.restcomm.connect.telephony.api.StopConference; import org.restcomm.connect.telephony.api.StopWaiting; import org.restcomm.connect.tts.api.SpeechSynthesizerResponse; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; import javax.servlet.sip.SipServletMessage; 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.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.Currency; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static akka.pattern.Patterns.ask; /** * @author [email protected] (Thomas Quintana) * @author [email protected] * @author [email protected] * @author [email protected] (Amit Bhayani) * @author [email protected] * @author [email protected] */ public class VoiceInterpreter extends BaseVoiceInterpreter { // Logger. private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // States for the FSM. private final State startDialing; private final State processingDialChildren; private final State acquiringOutboundCallInfo; private final State forking; // private final State joiningCalls; private final State creatingBridge; private final State initializingBridge; private final State bridging; private final State bridged; private final State finishDialing; private final State acquiringConferenceInfo; private final State joiningConference; private final State conferencing; private final State finishConferencing; private final State downloadingRcml; private final State downloadingFallbackRcml; private final State initializingCall; // private final State initializedCall; private final State ready; private final State notFound; private final State rejecting; private final State finished; // FSM. // The conference Ceneter. private final ActorRef conferenceCenter; // State for outbound calls. private boolean isForking; private List<ActorRef> dialBranches; private List<Tag> dialChildren; private Map<ActorRef, Tag> dialChildrenWithAttributes; // The conferencing stuff private int maxParticipantLimit = 40; private ActorRef conference; private Sid conferenceSid; private ConferenceInfo conferenceInfo; private ConferenceStateChanged.State conferenceState; private boolean muteCall; private boolean startConferenceOnEnter = true; private boolean endConferenceOnExit = false; private boolean confModeratorPresent = false; private ActorRef confSubVoiceInterpreter; private Attribute dialRecordAttribute; private boolean dialActionExecuted = false; private ActorRef sender; private boolean liveCallModification = false; private boolean recordingCall = true; protected boolean isParserFailed = false; protected boolean playWaitUrlPending = false; Tag conferenceVerb; List<URI> conferenceWaitUris; private boolean playMusicForConference = false; private MediaAttributes mediaAttributes; //Used for system apps, such as when WebRTC client is dialing out. //The rcml will be used instead of download the RCML private String rcml; // Call bridging private final ActorRef bridgeManager; private ActorRef bridge; private boolean beep; private boolean enable200OkDelay; // IMS authentication private boolean asImsUa; private String imsUaLogin; private String imsUaPassword; private String forwardedFrom; private Attribute action; private String conferenceNameWithAccountAndFriendlyName; private Sid callSid; // Controls if VI will wait MS response to move to the next verb protected boolean msResponsePending; private boolean msStopingRingTone = false; private boolean callWaitingForAnswer = false; private Tag callWaitingForAnswerPendingTag; private long timeout; private UriUtils uriUtils; public VoiceInterpreter(VoiceInterpreterParams params) { super(); final ActorRef source = self(); downloadingRcml = new State("downloading rcml", new DownloadingRcml(source), null); downloadingFallbackRcml = new State("downloading fallback rcml", new DownloadingFallbackRcml(source), null); initializingCall = new State("initializing call", new InitializingCall(source), null); // initializedCall = new State("initialized call", new InitializedCall(source), new PostInitializedCall(source)); ready = new State("ready", new Ready(source), null); notFound = new State("notFound", new NotFound(source), null); rejecting = new State("rejecting", new Rejecting(source), null); startDialing = new State("start dialing", new StartDialing(source), null); processingDialChildren = new State("processing dial children", new ProcessingDialChildren(source), null); acquiringOutboundCallInfo = new State("acquiring outbound call info", new AcquiringOutboundCallInfo(source), null); forking = new State("forking", new Forking(source), null); // joiningCalls = new State("joining calls", new JoiningCalls(source), null); this.creatingBridge = new State("creating bridge", new CreatingBridge(source), null); this.initializingBridge = new State("initializing bridge", new InitializingBridge(source), null); this.bridging = new State("bridging", new Bridging(source), null); bridged = new State("bridged", new Bridged(source), null); finishDialing = new State("finish dialing", new FinishDialing(source), null); acquiringConferenceInfo = new State("acquiring conference info", new AcquiringConferenceInfo(source), null); joiningConference = new State("joining conference", new JoiningConference(source), null); conferencing = new State("conferencing", new Conferencing(source), null); finishConferencing = new State("finish conferencing", new FinishConferencing(source), null); finished = new State("finished", new Finished(source), null); /* * dialing = new State("dialing", null, null); bridging = new State("bridging", null, null); conferencing = new * State("conferencing", null, null); */ transitions.add(new Transition(acquiringAsrInfo, finished)); transitions.add(new Transition(acquiringSynthesizerInfo, finished)); transitions.add(new Transition(acquiringCallInfo, initializingCall)); transitions.add(new Transition(acquiringCallInfo, downloadingRcml)); transitions.add(new Transition(acquiringCallInfo, finished)); transitions.add(new Transition(acquiringCallInfo, ready)); transitions.add(new Transition(initializingCall, downloadingRcml)); transitions.add(new Transition(initializingCall, ready)); transitions.add(new Transition(initializingCall, finishDialing)); transitions.add(new Transition(initializingCall, hangingUp)); transitions.add(new Transition(initializingCall, finished)); transitions.add(new Transition(downloadingRcml, ready)); transitions.add(new Transition(downloadingRcml, notFound)); transitions.add(new Transition(downloadingRcml, downloadingFallbackRcml)); transitions.add(new Transition(downloadingRcml, hangingUp)); transitions.add(new Transition(downloadingRcml, finished)); transitions.add(new Transition(downloadingFallbackRcml, ready)); transitions.add(new Transition(downloadingFallbackRcml, hangingUp)); transitions.add(new Transition(downloadingFallbackRcml, finished)); transitions.add(new Transition(downloadingFallbackRcml, notFound)); transitions.add(new Transition(ready, initializingCall)); transitions.add(new Transition(ready, faxing)); transitions.add(new Transition(ready, sendingEmail)); transitions.add(new Transition(ready, pausing)); transitions.add(new Transition(ready, checkingCache)); transitions.add(new Transition(ready, caching)); transitions.add(new Transition(ready, synthesizing)); transitions.add(new Transition(ready, rejecting)); transitions.add(new Transition(ready, redirecting)); transitions.add(new Transition(ready, processingGatherChildren)); transitions.add(new Transition(ready, creatingRecording)); transitions.add(new Transition(ready, creatingSmsSession)); transitions.add(new Transition(ready, startDialing)); transitions.add(new Transition(ready, hangingUp)); transitions.add(new Transition(ready, finished)); transitions.add(new Transition(pausing, ready)); transitions.add(new Transition(pausing, finished)); transitions.add(new Transition(rejecting, finished)); transitions.add(new Transition(faxing, ready)); transitions.add(new Transition(faxing, finished)); transitions.add(new Transition(sendingEmail, ready)); transitions.add(new Transition(sendingEmail, finished)); transitions.add(new Transition(sendingEmail, finishDialing)); transitions.add(new Transition(checkingCache, caching)); transitions.add(new Transition(checkingCache, conferencing)); transitions.add(new Transition(caching, finished)); transitions.add(new Transition(caching, conferencing)); transitions.add(new Transition(caching, finishConferencing)); transitions.add(new Transition(playing, ready)); transitions.add(new Transition(playing, finishConferencing)); transitions.add(new Transition(playing, finished)); transitions.add(new Transition(synthesizing, finished)); transitions.add(new Transition(redirecting, ready)); transitions.add(new Transition(redirecting, finished)); transitions.add(new Transition(creatingRecording, finished)); transitions.add(new Transition(finishRecording, ready)); transitions.add(new Transition(finishRecording, finished)); transitions.add(new Transition(processingGatherChildren, finished)); transitions.add(new Transition(gathering, finished)); transitions.add(new Transition(finishGathering, ready)); transitions.add(new Transition(finishGathering, finishGathering)); transitions.add(new Transition(finishGathering, finished)); transitions.add(new Transition(creatingSmsSession, finished)); transitions.add(new Transition(sendingSms, ready)); transitions.add(new Transition(sendingSms, startDialing)); transitions.add(new Transition(sendingSms, finished)); transitions.add(new Transition(startDialing, processingDialChildren)); transitions.add(new Transition(startDialing, acquiringConferenceInfo)); transitions.add(new Transition(startDialing, faxing)); transitions.add(new Transition(startDialing, sendingEmail)); transitions.add(new Transition(startDialing, pausing)); transitions.add(new Transition(startDialing, checkingCache)); transitions.add(new Transition(startDialing, caching)); transitions.add(new Transition(startDialing, synthesizing)); transitions.add(new Transition(startDialing, redirecting)); transitions.add(new Transition(startDialing, processingGatherChildren)); transitions.add(new Transition(startDialing, creatingRecording)); transitions.add(new Transition(startDialing, creatingSmsSession)); transitions.add(new Transition(startDialing, startDialing)); transitions.add(new Transition(startDialing, hangingUp)); transitions.add(new Transition(startDialing, finished)); transitions.add(new Transition(processingDialChildren, processingDialChildren)); transitions.add(new Transition(processingDialChildren, forking)); transitions.add(new Transition(processingDialChildren, startDialing)); transitions.add(new Transition(processingDialChildren, checkingCache)); transitions.add(new Transition(processingDialChildren, sendingEmail)); transitions.add(new Transition(processingDialChildren, faxing)); transitions.add(new Transition(processingDialChildren, sendingSms)); transitions.add(new Transition(processingDialChildren, playing)); transitions.add(new Transition(processingDialChildren, pausing)); transitions.add(new Transition(processingDialChildren, ready)); transitions.add(new Transition(processingDialChildren, hangingUp)); transitions.add(new Transition(processingDialChildren, finished)); transitions.add(new Transition(forking, acquiringOutboundCallInfo)); transitions.add(new Transition(forking, finishDialing)); transitions.add(new Transition(forking, hangingUp)); transitions.add(new Transition(forking, finished)); transitions.add(new Transition(forking, ready)); transitions.add(new Transition(forking, checkingCache)); transitions.add(new Transition(forking, caching)); transitions.add(new Transition(forking, faxing)); transitions.add(new Transition(forking, sendingEmail)); transitions.add(new Transition(forking, pausing)); transitions.add(new Transition(forking, synthesizing)); transitions.add(new Transition(forking, redirecting)); transitions.add(new Transition(forking, processingGatherChildren)); transitions.add(new Transition(forking, creatingRecording)); transitions.add(new Transition(forking, creatingSmsSession)); // transitions.add(new Transition(acquiringOutboundCallInfo, joiningCalls)); transitions.add(new Transition(acquiringOutboundCallInfo, hangingUp)); transitions.add(new Transition(acquiringOutboundCallInfo, finished)); transitions.add(new Transition(acquiringOutboundCallInfo, creatingBridge)); transitions.add(new Transition(creatingBridge, initializingBridge)); transitions.add(new Transition(creatingBridge, finishDialing)); transitions.add(new Transition(initializingBridge, bridging)); transitions.add(new Transition(initializingBridge, hangingUp)); transitions.add(new Transition(initializingBridge, finished)); transitions.add(new Transition(bridging, bridged)); transitions.add(new Transition(bridging, finishDialing)); transitions.add(new Transition(bridged, finishDialing)); transitions.add(new Transition(bridged, finished)); transitions.add(new Transition(finishDialing, ready)); transitions.add(new Transition(finishDialing, faxing)); transitions.add(new Transition(finishDialing, sendingEmail)); transitions.add(new Transition(finishDialing, pausing)); transitions.add(new Transition(finishDialing, checkingCache)); transitions.add(new Transition(finishDialing, caching)); transitions.add(new Transition(finishDialing, synthesizing)); transitions.add(new Transition(finishDialing, redirecting)); transitions.add(new Transition(finishDialing, processingGatherChildren)); transitions.add(new Transition(finishDialing, creatingRecording)); transitions.add(new Transition(finishDialing, creatingSmsSession)); transitions.add(new Transition(finishDialing, startDialing)); transitions.add(new Transition(finishDialing, hangingUp)); transitions.add(new Transition(finishDialing, finished)); transitions.add(new Transition(finishDialing, initializingCall)); transitions.add(new Transition(acquiringConferenceInfo, joiningConference)); transitions.add(new Transition(acquiringConferenceInfo, hangingUp)); transitions.add(new Transition(acquiringConferenceInfo, finished)); transitions.add(new Transition(joiningConference, conferencing)); transitions.add(new Transition(joiningConference, acquiringConferenceInfo)); transitions.add(new Transition(joiningConference, hangingUp)); transitions.add(new Transition(joiningConference, finished)); transitions.add(new Transition(conferencing, finishConferencing)); transitions.add(new Transition(conferencing, hangingUp)); transitions.add(new Transition(conferencing, finished)); transitions.add(new Transition(conferencing, checkingCache)); transitions.add(new Transition(conferencing, caching)); transitions.add(new Transition(conferencing, playing)); transitions.add(new Transition(conferencing, startDialing)); transitions.add(new Transition(conferencing, creatingSmsSession)); transitions.add(new Transition(conferencing, sendingEmail)); transitions.add(new Transition(finishConferencing, ready)); transitions.add(new Transition(finishConferencing, faxing)); transitions.add(new Transition(finishConferencing, sendingEmail)); transitions.add(new Transition(finishConferencing, pausing)); transitions.add(new Transition(finishConferencing, checkingCache)); transitions.add(new Transition(finishConferencing, caching)); transitions.add(new Transition(finishConferencing, synthesizing)); transitions.add(new Transition(finishConferencing, redirecting)); transitions.add(new Transition(finishConferencing, processingGatherChildren)); transitions.add(new Transition(finishConferencing, creatingRecording)); transitions.add(new Transition(finishConferencing, creatingSmsSession)); transitions.add(new Transition(finishConferencing, startDialing)); transitions.add(new Transition(finishConferencing, hangingUp)); transitions.add(new Transition(finishConferencing, finished)); transitions.add(new Transition(hangingUp, finished)); transitions.add(new Transition(hangingUp, finishConferencing)); transitions.add(new Transition(hangingUp, finishDialing)); transitions.add(new Transition(hangingUp, ready)); transitions.add(new Transition(uninitialized, finished)); transitions.add(new Transition(notFound, 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.viStatusCallback = params.getStatusCallback(); this.viStatusCallbackMethod = params.getStatusCallbackMethod(); this.referTarget = params.getReferTarget(); this.transferor = params.getTransferor(); this.transferee = params.getTransferee(); this.emailAddress = params.getEmailAddress(); this.configuration = params.getConfiguration(); this.callManager = params.getCallManager(); this.conferenceCenter = params.getConferenceCenter(); this.bridgeManager = params.getBridgeManager(); this.smsService = params.getSmsService(); this.smsSessions = new HashMap<Sid, ActorRef>(); this.storage = params.getStorage(); final Configuration runtime = configuration.subset("runtime-settings"); playMusicForConference = Boolean.parseBoolean(runtime.getString("play-music-for-conference","false")); this.enable200OkDelay = this.configuration.subset("runtime-settings").getBoolean("enable-200-ok-delay",false); this.downloader = downloader(); this.monitoring = params.getMonitoring(); this.rcml = params.getRcml(); this.asImsUa = params.isAsImsUa(); this.imsUaLogin = params.getImsUaLogin(); this.imsUaPassword = params.getImsUaPassword(); this.timeout = params.getTimeout(); this.msResponsePending = false; this.mediaAttributes = new MediaAttributes(); this.uriUtils = RestcommConnectServiceProvider.getInstance().uriUtils(); } public static Props props(final VoiceInterpreterParams params) { return new Props(new UntypedActorFactory() { @Override public Actor create() throws Exception { return new VoiceInterpreter(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); String base = configuration.subset("runtime-settings").getString("error-dictionary-uri"); try { base = uriUtils.resolve(new URI(base), accountId).toString(); } catch (URISyntaxException e) { logger.error("URISyntaxException when trying to resolve Error-Dictionary URI: " + e); } 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(); } @SuppressWarnings("unchecked") @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final State state = fsm.state(); sender = sender(); ActorRef self = self(); if (logger.isInfoEnabled()) { logger.info(" ********** VoiceInterpreter's " + self().path() + " Current State: " + state.toString() + "\n" + ", Processing Message: " + klass.getName() + " Sender is: "+sender.path()); } if (StartInterpreter.class.equals(klass)) { final StartInterpreter request = (StartInterpreter) message; call = request.resource(); fsm.transition(message, acquiringAsrInfo); } else if (AsrResponse.class.equals(klass)) { onAsrResponse(message); } else if (SpeechSynthesizerResponse.class.equals(klass)) { onSpeechSynthesizerResponse(message); } else if (CallResponse.class.equals(klass)) { onCallResponse(message, state); } else if (CallStateChanged.class.equals(klass)) { onCallStateChanged(message, sender); } else if (CallManagerResponse.class.equals(klass)) { onCallManagerResponse(message); } else if (StartForking.class.equals(klass)) { fsm.transition(message, processingDialChildren); } else if (ConferenceCenterResponse.class.equals(klass)) { onConferenceCenterResponse(message); } else if (Fork.class.equals(klass)) { onForkMessage(message); } else if (ConferenceResponse.class.equals(klass)) { onConferenceResponse(message); } else if (ConferenceStateChanged.class.equals(klass)) { onConferenceStateChanged(message); } else if (DownloaderResponse.class.equals(klass)) { onDownloaderResponse(message, state); } else if (DiskCacheResponse.class.equals(klass)) { onDiskCacheResponse(message); } else if (ParserFailed.class.equals(klass)) { onParserFailed(message); } else if (Tag.class.equals(klass)) { onTagMessage(message); } else if (End.class.equals(klass)) { onEndMessage(message); } else if (StartGathering.class.equals(klass)) { fsm.transition(message, gathering); } else if (MediaGroupResponse.class.equals(klass)) { onMediaGroupResponse(message); } else if (SmsServiceResponse.class.equals(klass)) { onSmsServiceResponse(message); } else if (SmsSessionResponse.class.equals(klass)) { smsResponse(message); } else if (FaxResponse.class.equals(klass)) { fsm.transition(message, ready); } else if (EmailResponse.class.equals(klass)) { onEmailResponse(message); } else if (StopInterpreter.class.equals(klass)) { onStopInterpreter(message); } else if (message instanceof ReceiveTimeout) { onReceiveTimeout(message); } else if (BridgeManagerResponse.class.equals(klass)) { onBridgeManagerResponse((BridgeManagerResponse) message, self, sender); } else if (BridgeStateChanged.class.equals(klass)) { onBridgeStateChanged((BridgeStateChanged) message, self, sender); } else if (GetRelatedCall.class.equals(klass)) { onGetRelatedCall((GetRelatedCall) message, self, sender); } else if (JoinComplete.class.equals(klass)) { onJoinComplete((JoinComplete)message); } else if (CallHoldStateChange.class.equals(klass)) { onCallHoldStateChange((CallHoldStateChange)message, sender); } } private void onJoinComplete(JoinComplete message) throws TransitionNotFoundException, TransitionFailedException, TransitionRollbackException { if (logger.isInfoEnabled()) { logger.info("JoinComplete received, sender: " + sender().path() + ", VI state: " + fsm.state()); } if (is(joiningConference)) { fsm.transition(message, conferencing); } } private void onAsrResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { if (outstandingAsrRequests > 0) { asrResponse(message); } else { fsm.transition(message, acquiringSynthesizerInfo); } } private void onForkMessage(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { if (is(processingDialChildren)) { fsm.transition(message, forking); } } private void onConferenceCenterResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { if (is(startDialing) || is(joiningConference)) { ConferenceCenterResponse ccReponse = (ConferenceCenterResponse)message; if(ccReponse.succeeded()){ fsm.transition(message, acquiringConferenceInfo); }else{ fsm.transition(message, hangingUp); } } } private void onConferenceResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final ConferenceResponse<ConferenceInfo> response = (ConferenceResponse<ConferenceInfo>) message; final Class<?> klass = ((ConferenceResponse)message).get().getClass(); if (logger.isDebugEnabled()) { logger.debug("New ConferenceResponse received with message: "+klass.getName()); } if (Left.class.equals(klass)) { Left left = (Left) ((ConferenceResponse)message).get(); ActorRef leftCall = left.get(); if (leftCall.equals(call) && conference != null) { if(conferenceInfo.globalParticipants() !=0 ){ String path = configuration.subset("runtime-settings").getString("prompts-uri"); if (!path.endsWith("/")) { path += "/"; } String exitAudio = configuration.subset("runtime-settings").getString("conference-exit-audio"); path += exitAudio == null || exitAudio.equals("") ? "alert.wav" : exitAudio; URI uri = null; try { uri = uriUtils.resolve(new URI(path), accountId); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 12400, exception.getMessage()); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); self().tell(stop, self()); return; } if (logger.isInfoEnabled()) { logger.info("going to play conference-exit-audio beep"); } final Play play = new Play(uri, 1); conference.tell(play, self()); } if (endConferenceOnExit) { // Stop the conference if endConferenceOnExit is true final StopConference stop = new StopConference(); conference.tell(stop, self()); } Attribute attribute = null; if (verb != null) { attribute = verb.attribute(GatherAttributes.ATTRIBUTE_ACTION); } if (attribute == null) { if (logger.isInfoEnabled()) { logger.info("Attribute is null, will ask for the next verb from parser"); } final GetNextVerb next = new GetNextVerb(); parser.tell(next, self()); } else { if (logger.isInfoEnabled()) { logger.info("Dial Action is set, executing Dial Action"); } executeDialAction(message, sender); } conference.tell(new StopObserving(self()), null); } } else if (ConferenceInfo.class.equals(klass)) { conferenceInfo = response.get(); if (logger.isInfoEnabled()) { logger.info("VoiceInterpreter received ConferenceResponse from Conference: " + conferenceInfo.name() + ", path: " + sender().path() + ", current confernce size: " + conferenceInfo.globalParticipants() + ", VI state: " + fsm.state()); } if (is(acquiringConferenceInfo)) { fsm.transition(message, joiningConference); } } } private void onConferenceStateChanged(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final ConferenceStateChanged event = (ConferenceStateChanged) message; if(logger.isInfoEnabled()) { logger.info("onConferenceStateChanged: "+event.state()); } switch (event.state()) { case RUNNING_MODERATOR_PRESENT: conferenceState = event.state(); conferenceStateModeratorPresent(message); break; case COMPLETED: conferenceState = event.state(); //Move to finishConferencing only if we are not in Finished state already //There are cases were we have already finished conferencing, for example when there is //conference timeout if (!is(finished)) fsm.transition(message, finishConferencing); break; case STOPPING: conferenceState = event.state(); if(is(joiningConference)){ if(logger.isInfoEnabled()) { logger.info("We tried to join a stopping conference. Will ask Conference Center to create a new conference for us."); } final CreateConference create = new CreateConference(conferenceNameWithAccountAndFriendlyName, callSid); conferenceCenter.tell(create, self()); } default: break; } // !!IMPORTANT!! // Do not listen to COMPLETED nor FAILED conference state changes // When a conference stops it will ask all its calls to Leave // Then the call state will change and the voice interpreter will take proper action then } private void onParserFailed(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { if(logger.isInfoEnabled()) { logger.info("ParserFailed received. Will stop the call"); } isParserFailed = true; fsm.transition(message, hangingUp); } private void onStopInterpreter(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { this.liveCallModification = ((StopInterpreter) message).isLiveCallModification(); if (logger.isInfoEnabled()) { String msg = String.format("Got StopInterpreter, liveCallModification %s, CallState %s", liveCallModification, callState); logger.info(msg); } if (CallStateChanged.State.IN_PROGRESS.equals(callState) && !liveCallModification) { fsm.transition(message, hangingUp); } else { fsm.transition(message, finished); } } private void onReceiveTimeout(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { if (logger.isInfoEnabled()) { logger.info("Timeout received"); } if (is(pausing)) { fsm.transition(message, ready); } else if (is(conferencing)) { fsm.transition(message, finishConferencing); } else if (is(forking)) { fsm.transition(message, finishDialing); } else if (is(bridged)) { fsm.transition(message, finishDialing); } else if (is(bridging)) { fsm.transition(message, finishDialing); } else if (is(playing) || is(initializingCall)) { fsm.transition(message, finished); } } private void onEmailResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final EmailResponse response = (EmailResponse) message; if (!response.succeeded()) { logger.error( "There was an error while sending an email :" + response.error(), response.cause()); return; } fsm.transition(message, ready); } private void onSmsServiceResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final SmsServiceResponse<ActorRef> response = (SmsServiceResponse<ActorRef>) message; if (response.succeeded()) { if (is(creatingSmsSession)) { fsm.transition(message, sendingSms); } } else { fsm.transition(message, hangingUp); } } private void onMediaGroupResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final MediaGroupResponse response = (MediaGroupResponse) message; if(logger.isInfoEnabled()) { logger.info("MediaGroupResponse, succeeded: " + response.succeeded() + " " + response.cause()); } if (response.succeeded()) { if (is(playingRejectionPrompt)) { fsm.transition(message, hangingUp); } else if (is(playing)) { logger.info ("Is restcomm stoping ring tone: " + msStopingRingTone); // When RestComm is requesting stop ring tone, the first NTFY response is for stop ring tone, // instead for play/say verb. When enable200OkDelay = true, there is no NTFY for stop ring tone. if (!msStopingRingTone || enable200OkDelay) { fsm.transition(message, ready); } } else if (is(creatingRecording)) { if (logger.isInfoEnabled()) { logger.info("Will move to finishRecording because of MediaGroupResponse"); } fsm.transition(message, finishRecording); } // This is either MMS collected digits or SIP INFO DTMF. If the DTMF is from SIP INFO, then more DTMF might // come later else if (is(gathering) || (is(finishGathering) && !super.dtmfReceived)) { final MediaGroupResponse dtmfResponse = (MediaGroupResponse) message; Object data = dtmfResponse.get(); if (data instanceof CollectedResult && ((CollectedResult)data).isAsr() && ((CollectedResult)data).isPartial()) { try { //we dont need a new state for this action. The notification //is purely async, and the Interpreter logic will resume //regardless notification result. new PartialGathering(self()).execute(message); } catch (Exception ex) { this.logger.debug("Notifying partial result", ex); } } else if (data instanceof CollectedResult && ((CollectedResult)data).isAsr() && !((CollectedResult)data).isPartial() && collectedDigits.length() == 0) { speechResult = ((CollectedResult)data).getResult(); fsm.transition(message, finishGathering); } else { if (sender == call) { // DTMF using SIP INFO, check if all digits collected here collectedDigits.append(dtmfResponse.get()); // Collected digits == requested num of digits the complete the collect digits //Zendesk_34592: if collected digits smaller than numDigits in gather verb // when timeout on gather occur, garthering cannot move to finishGathering // If collected digits have finish on key at the end then complete the collect digits if (collectedDigits.toString().endsWith(finishOnKey)) { dtmfReceived = true; fsm.transition(message, finishGathering); } else { if (numberOfDigits != Short.MAX_VALUE) { if (collectedDigits.length() == numberOfDigits) { dtmfReceived = true; fsm.transition(message, finishGathering); } else { dtmfReceived = false; return; } } else { dtmfReceived = false; return; } } } else { collectedDigits.append(((CollectedResult)data).getResult()); fsm.transition(message, finishGathering); } } } else if (is(bridging)) { // Finally proceed with call bridging if (logger.isInfoEnabled()) { String msg = String.format("About to join calls, inbound call %s, outbound call %s", call, outboundCall); logger.info(msg); } final JoinCalls bridgeCalls = new JoinCalls(call, outboundCall); bridge.tell(bridgeCalls, self()); } else if (msResponsePending) { // Move to next verb once media server completed Play msResponsePending = false; final boolean noBranches = dialBranches == null || dialBranches.size() == 0; final boolean activeParser = parser != null; final boolean noDialAction = action == null; if (noBranches && activeParser && noDialAction) { final GetNextVerb next = new GetNextVerb(); parser.tell(next, self()); } } if (msStopingRingTone) { msStopingRingTone = !(((MediaGroupResponse) message).get() instanceof CollectedResult); } } else { fsm.transition(message, hangingUp); } } private void onEndMessage(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { //Because of RMS issue https://github.com/RestComm/mediaserver/issues/158 we cannot have List<URI> for waitUrl if (playWaitUrlPending && conferenceWaitUris != null && conferenceWaitUris.size() > 0) { if (logger.isInfoEnabled()) { String msg = String.format("End tag received, playWaitUrlPending is %s, conferenceWaitUris.size() %d",playWaitUrlPending, conferenceWaitUris.size()); logger.info(msg); } fsm.transition(conferenceWaitUris, conferencing); return; } if (callState.equals(CallStateChanged.State.COMPLETED) || callState.equals(CallStateChanged.State.CANCELED)) { if(logger.isInfoEnabled()) { String msg = String.format("End tag received, Call state %s , VI state %s will move to finished state",callState, fsm.state()); logger.info(msg); } fsm.transition(message, finished); } else { if (!isParserFailed) { if(logger.isInfoEnabled()) { logger.info("End tag received will move to hangup the call, VI state: "+fsm.state()); } fsm.transition(message, hangingUp); } else { if(logger.isInfoEnabled()) { logger.info("End tag received but parser failed earlier so hangup would have been already sent to the call"); } } } } private void onTagMessage(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { verb = (Tag) message; if (logger.isDebugEnabled()) { logger.debug("Tag received, name: "+verb.name()+", text: "+verb.text()); } // if 200 ok delay is enabled we need to answer only the calls // which are having any further call enabler verbs in their RCML. if(enable200OkDelay && callWaitingForAnswer && Verbs.isThisVerbCallEnabler(verb)){ if(logger.isInfoEnabled()) { logger.info("Tag received, but callWaitingForAnswer: will tell call to stop waiting"); } callWaitingForAnswerPendingTag = verb; call.tell(new StopWaiting(), self()); } else { if (playWaitUrlPending) { if (!(Verbs.play.equals(verb.name()) || Verbs.say.equals(verb.name()))) { if (logger.isInfoEnabled()) { logger.info("Tag for waitUrl is neither Play or Say"); } fsm.transition(message, hangingUp); } if (Verbs.say.equals(verb.name())) { fsm.transition(message, checkingCache); } else if (Verbs.play.equals(verb.name())) { fsm.transition(message, caching); } return; } if (CallStateChanged.State.RINGING == callState) { if (Verbs.reject.equals(verb.name())) { fsm.transition(message, rejecting); } else if (Verbs.pause.equals(verb.name())) { fsm.transition(message, pausing); } else { fsm.transition(message, initializingCall); } } else if (Verbs.dial.equals(verb.name()) && callState != CallStateChanged.State.COMPLETED) { action = verb.attribute(GatherAttributes.ATTRIBUTE_ACTION); if (action != null && dialActionExecuted) { //We have a new Dial verb that contains Dial Action URL again. //We set dialActionExecuted to false in order to execute Dial Action again dialActionExecuted = false; } dialRecordAttribute = verb.attribute("record"); fsm.transition(message, startDialing); } else if (Verbs.fax.equals(verb.name())) { fsm.transition(message, caching); } else if (Verbs.play.equals(verb.name()) && callState != CallStateChanged.State.COMPLETED) { fsm.transition(message, caching); } else if (Verbs.say.equals(verb.name()) && callState != CallStateChanged.State.COMPLETED) { // fsm.transition(message, synthesizing); fsm.transition(message, checkingCache); } else if (Verbs.gather.equals(verb.name()) && callState != CallStateChanged.State.COMPLETED) { gatherVerb = verb; fsm.transition(message, processingGatherChildren); } else if (Verbs.pause.equals(verb.name()) && callState != CallStateChanged.State.COMPLETED) { fsm.transition(message, pausing); } else if (Verbs.hangup.equals(verb.name()) && callState != CallStateChanged.State.COMPLETED) { if (logger.isInfoEnabled()) { String msg = String.format("Next verb is Hangup, current state is %s , callInfo state %s", fsm.state(), callInfo.state()); logger.info(msg); } if (is(finishDialing)) { fsm.transition(message, finished); } else { fsm.transition(message, hangingUp); } } else if (Verbs.redirect.equals(verb.name()) && callState != CallStateChanged.State.COMPLETED) { fsm.transition(message, redirecting); } else if (Verbs.record.equals(verb.name()) && callState != CallStateChanged.State.COMPLETED) { fsm.transition(message, creatingRecording); } else if (Verbs.sms.equals(verb.name())) { //Check if Outbound SMS is allowed ExtensionController ec = ExtensionController.getInstance(); final IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.OUTBOUND_SMS, accountId); ExtensionResponse er = ec.executePreOutboundAction(far, this.extensions); if (er.isAllowed()) { fsm.transition(message, creatingSmsSession); ec.executePostOutboundAction(far, extensions); } else { if (logger.isDebugEnabled()) { final String errMsg = "Outbound SMS is not Allowed"; logger.debug(errMsg); } final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 11001, "Outbound SMS is now allowed"); notifications.addNotification(notification); fsm.transition(message, rejecting); ec.executePostOutboundAction(far, extensions); return; } } else if (Verbs.email.equals(verb.name())) { fsm.transition(message, sendingEmail); } else { invalidVerb(verb); } } } private void onDiskCacheResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final DiskCacheResponse response = (DiskCacheResponse) message; if (response.succeeded()) { //Because of RMS issue https://github.com/RestComm/mediaserver/issues/158 we cannot have List<URI> for waitUrl if (playWaitUrlPending) { if (conferenceWaitUris == null) conferenceWaitUris = new ArrayList<URI>(); URI waitUrl = response.get(); conferenceWaitUris.add(waitUrl); final GetNextVerb next = new GetNextVerb(); parser.tell(next, self()); return; } if (is(caching) || is(checkingCache)) { if (Verbs.play.equals(verb.name()) || Verbs.say.equals(verb.name())) { fsm.transition(message, playing); } else if (Verbs.fax.equals(verb.name())) { fsm.transition(message, faxing); } else if (Verbs.email.equals(verb.name())) { fsm.transition(message, sendingEmail); } } else if (is(processingGatherChildren)) { fsm.transition(message, processingGatherChildren); } } else { if (logger.isDebugEnabled()) { logger.debug("DiskCacheResponse is " + response.toString()); } if (is(checkingCache) || is(processingGatherChildren)) { fsm.transition(message, synthesizing); } else { if(response.cause() != null){ Notification notification = notification(WARNING_NOTIFICATION, 13233, response.cause().getMessage()); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); sendMail(notification); } fsm.transition(message, hangingUp); } } } private void onCallManagerResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final CallManagerResponse<Object> response = (CallManagerResponse<Object>) message; if (response.succeeded()) { if (is(startDialing)) { fsm.transition(message, processingDialChildren); } else if (is(processingDialChildren)) { fsm.transition(message, processingDialChildren); } } else { if (logger.isDebugEnabled()) { String msg = String.format("CallManager failed to create Call for %s, current state %s, dialChilder.size %s, dialBranches.size %s", response.getCreateCall().to(), fsm.state().toString(), dialChildren.size(), dialBranches.size()); logger.debug(msg); } if (dialChildren != null && dialChildren.size() > 0) { fsm.transition(message, processingDialChildren); } else { fsm.transition(message, hangingUp); } } } private void onSpeechSynthesizerResponse(Object message) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { if (is(acquiringSynthesizerInfo)) { fsm.transition(message, acquiringCallInfo); } else if (is(processingGatherChildren) || processingGather) { final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message; if (response.succeeded()) { fsm.transition(message, processingGatherChildren); } else { fsm.transition(message, hangingUp); } } else if (is(synthesizing)) { final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message; if (response.succeeded()) { fsm.transition(message, caching); } else { fsm.transition(message, hangingUp); } } } private void onCallResponse(Object message, State state) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { if (forking.equals(state)) { // Allow updating of the callInfo at the VoiceInterpreter so that we can do Dial SIP Screening // (https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out) accurately from latest // response received final CallResponse<CallInfo> response = (CallResponse<CallInfo>) message; // Check from whom is the message (initial call or outbound call) and update info accordingly if (sender == call) { callInfo = response.get(); } else { outboundCall = sender; outboundCallInfo = response.get(); } } else if (acquiringCallInfo.equals(state)) { final CallResponse<CallInfo> response = (CallResponse<CallInfo>) message; // Check from whom is the message (initial call or outbound call) and update info accordingly if (sender == call) { callInfo = response.get(); if (callInfo.state() == CallStateChanged.State.CANCELED || (callInfo.invite() != null && callInfo.invite().getSession().getState().equals(SipSession.State.TERMINATED))) { fsm.transition(message, finished); return; } else { call.tell(new Observe(self()), self()); //Enable Monitoring Service for the call if (monitoring != null) call.tell(new Observe(monitoring), self()); } } else { outboundCallInfo = response.get(); } final String direction = callInfo.direction(); if ("inbound".equals(direction)) { if (rcml!=null && !rcml.isEmpty()) { if (logger.isInfoEnabled()) { logger.info("System app is present will proceed to ready state, system app: "+rcml); } createInitialCallRecord((CallResponse<CallInfo>) message); fsm.transition(message, ready); } else { fsm.transition(message, downloadingRcml); } } else { fsm.transition(message, initializingCall); } } else if (acquiringOutboundCallInfo.equals(state)) { final CallResponse<CallInfo> response = (CallResponse<CallInfo>) message; this.outboundCallInfo = response.get(); fsm.transition(message, creatingBridge); } } private void onDownloaderResponse(Object message, State state) throws IOException, TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final DownloaderResponse response = (DownloaderResponse) message; if (logger.isDebugEnabled()) { logger.debug("Download Rcml response succeeded " + response.succeeded()); if (response.get() != null ) logger.debug("statusCode " + response.get().getStatusCode()); } if (response.succeeded() && HttpStatus.SC_OK == response.get().getStatusCode()) { if (gathering.equals(state)) { //no need change state return; } if (conferencing.equals(state)) { //This is the downloader response for Conferencing waitUrl if (parser != null) { getContext().stop(parser); parser = null; } final String type = response.get().getContentType(); if (type != null) { if (type.contains("text/xml") || type.contains("application/xml") || type.contains("text/html")) { parser = parser(response.get().getContentAsString()); } else if (type.contains("audio/wav") || type.contains("audio/wave") || type.contains("audio/x-wav")) { parser = parser("<Play>" + request.getUri() + "</Play>"); } else if (type.contains("text/plain")) { parser = parser("<Say>" + response.get().getContentAsString() + "</Say>"); } } else { //If the waitUrl is invalid then move to notFound fsm.transition(message, hangingUp); } final GetNextVerb next = new GetNextVerb(); parser.tell(next, self()); return; } if (dialBranches == null || dialBranches.size()==0) { if(logger.isInfoEnabled()) { logger.info("Downloader response is success, moving to Ready state"); } fsm.transition(message, ready); } else { return; } } else if (downloadingRcml.equals(state) && fallbackUrl != null) { fsm.transition(message, downloadingFallbackRcml); } else if (response.succeeded() && HttpStatus.SC_NOT_FOUND == response.get().getStatusCode()) { fsm.transition(message, notFound); } else { call.tell(new CallFail(response.error()), self()); // fsm.transition(message, finished); } } private void onCallStateChanged(Object message, ActorRef sender) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { final CallStateChanged event = (CallStateChanged) message; if (sender == call) callState = event.state(); else if(event.sipResponse()!=null && event.sipResponse()>=400){ outboundCallResponse = event.sipResponse(); } if(logger.isInfoEnabled()){ String msg = String.format("VoiceInterpreter received CallStateChanged event: [%s] , from sender path: [%s] , sender is initial call: [%s] , current VI state: [%s] , current call state: [%s] , current outboundCall actor is: [%s]", event, sender.path(),(sender == call), fsm.state(), callState != null ? callState.toString() : "null", outboundCall != null ? outboundCall.path(): "null"); logger.info(msg); } switch (event.state()) { case QUEUED: //Do nothing break; case RINGING: break; case CANCELED: if (is(creatingBridge) || is(initializingBridge) || is(acquiringOutboundCallInfo) || is(bridging) || is(bridged)) { //This is a canceled branch from a previous forking call. We need to destroy the branch // removeDialBranch(message, sender); callManager.tell(new DestroyCall(sender), self()); return; } else { if (enable200OkDelay && dialBranches != null && sender.equals(call)) { if (callRecord != null) { final CallDetailRecordsDao records = storage.getCallDetailRecordsDao(); callRecord = records.getCallDetailRecord(callRecord.getSid()); callRecord = callRecord.setStatus(callState.toString()); records.updateCallDetailRecord(callRecord); } fsm.transition(message, finishDialing); } else if (sender == call) { //Move to finished state only if the call actor send the Cancel. fsm.transition(message, finished); } else { //This is a Cancel from a dial branch previously canceled if (dialBranches != null && dialBranches.contains(sender)) { removeDialBranch(message, sender); checkDialBranch(message, sender, action); } else { //case for LCM testTerminateDialForkCallWhileRinging_LCM_to_dial_branches callState = event.state(); } } } break; case BUSY: if (is(forking)) { if (sender == call) { //Move to finishDialing to clear the call and cancel all branches fsm.transition(message, finishDialing); } else { if (dialBranches != null && dialBranches.contains(sender)) { removeDialBranch(message, sender); } if (dialBranches == null || dialBranches.size() == 0){ // Stop playing the ringing tone from inbound call stopRingTone(); } checkDialBranch(message, sender, action); return; } } if (is(initializingCall)) { fsm.transition(message, finished); } else { fsm.transition(message, finishDialing); return; } break; case NOT_FOUND: //Do nothing break; case NO_ANSWER: //NOANSWER calls should be canceled. At CANCELED event will be removed from //dialBranches and will be destroyed. if (is(bridging) || (is(bridged) && !sender.equals(call))) { fsm.transition(message, finishDialing); } else if (is(forking)){ if (!sender.equals(call)) { //One of the dial branches sent NO-ANSWER and we should ask to CANCEL // sender.tell(new Cancel(), self()); } } else if (is(finishDialing)) { if ((dialBranches == null || dialBranches.size()==0) && sender.equals(call)) { //TODO HERE logger.info("No-Answer event received, and dialBrances is either null or 0 size, sender: "+sender.path()+", vi state: "+fsm.state()); checkDialBranch(message, sender, action); } } if (is(initializingCall)) { sender.tell(new Hangup(), self()); } break; case FAILED: if (!sender.equals(call)) { if (dialBranches != null && dialBranches.contains(sender)) { dialBranches.remove(sender); } if (dialBranches == null || dialBranches.size() == 0){ // Stop playing the ringing tone from inbound call stopRingTone(); } checkDialBranch(message,sender,action); } else if (sender.equals(call)) { fsm.transition(message, finished); } break; case COMPLETED: //NO_ANSWER, COMPLETED and FAILED events are handled the same if (is(bridging) || is(bridged)) { if (sender == outboundCall || sender == call) { if(logger.isInfoEnabled()) { String msg = String.format("Received CallStateChanged COMPLETED from call %s, current fsm state %s, will move to finishDialingState ", sender(), fsm.state()); logger.info(msg); } fsm.transition(message, finishDialing); } else { if (dialBranches != null && dialBranches.contains(sender)) { removeDialBranch(message, sender); } callManager.tell(new DestroyCall(sender()), self()); } return; } else // changed for https://bitbucket.org/telestax/telscale-restcomm/issue/132/ so that we can do Dial SIP Screening if (is(forking) && ((dialBranches != null && dialBranches.contains(sender)) || outboundCall == null)) { if (!sender.equals(call)) { removeDialBranch(message, sender); //Properly clean up FAILED or BUSY outgoing calls //callManager.tell(new DestroyCall(sender), self()); checkDialBranch(message,sender,action); return; } else { fsm.transition(message, finishDialing); } } else if (is(creatingRecording)) { fsm.transition(message, finishRecording); } else if ((is(bridged) || is(forking)) && call == sender()) { if (!dialActionExecuted) { fsm.transition(message, finishDialing); } } else if (is(finishDialing)) { if (sender.equals(call)) { fsm.transition(message, finished); } else { checkDialBranch(message, sender(), action); } break; } else if (is(conferencing) || is(finishConferencing)) { //If the CallStateChanged.Completed event from the Call arrived before the ConferenceStateChange.Completed //event, then return and wait for the FinishConferencing to deal with the event (either execute dial action or //get next verb from parser if (logger.isInfoEnabled()) { logger.info("VoiceInterpreter received CallStateChanged.Completed VI in: " + fsm.state() + " state, will return and wait for ConferenceStateChanged.Completed event"); } return; } else { if (!is(finishDialing) && !is(finished)) fsm.transition(message, finished); } break; case WAIT_FOR_ANSWER: case IN_PROGRESS: if(call!=null && (call == sender) && event.state().equals(CallStateChanged.State.WAIT_FOR_ANSWER)){ callWaitingForAnswer = true; } if (enable200OkDelay && sender.equals(call) && event.state().equals(CallStateChanged.State.IN_PROGRESS) && callWaitingForAnswerPendingTag != null) { if (logger.isInfoEnabled()) { logger.info("Waiting call is inProgress we can proceed to the pending tag execution"); } callWaitingForAnswer = false; onTagMessage(callWaitingForAnswerPendingTag); } else if (is(initializingCall) || is(rejecting)) { if (parser != null) { //This is an inbound call fsm.transition(message, ready); } else { //This is a REST API created outgoing call fsm.transition(message, downloadingRcml); } } else if (is(forking)) { if (outboundCall == null || !sender.equals(call)) { if (logger.isInfoEnabled()) { String msg = String.format("Got CallStateChanged.InProgress while forking, from outbound call %s, will proceed to cancel other branches", sender()); logger.info(msg); } outboundCall = sender; fsm.transition(message, acquiringOutboundCallInfo); } } else if (is(conferencing)) { // Call left the conference successfully if (!liveCallModification) { // Hang up the call final Hangup hangup = new Hangup(); call.tell(hangup, sender); } else { // XXX start processing new RCML and give instructions to call // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, self()); } } // Update the storage for conferencing. if (callRecord != null && !is(initializingCall) && !is(rejecting)) { final CallDetailRecordsDao records = storage.getCallDetailRecordsDao(); callRecord = records.getCallDetailRecord(callRecord.getSid()); callRecord = callRecord.setStatus(callState.toString()); records.updateCallDetailRecord(callRecord); } break; } } private void removeDialBranch(Object message, ActorRef sender) { //Just remove the branch from dialBranches and send the CANCEL //Later at onCallStateChanged.CANCEL we should ask call manager to destroy call and //either execute dial action or ask parser for next verb CallStateChanged.State state = null; if (message instanceof CallStateChanged) { state = ((CallStateChanged)message).state(); } else if (message instanceof ReceiveTimeout) { state = CallStateChanged.State.NO_ANSWER; } if(logger.isInfoEnabled()) { logger.info("Dial branch new call state: " + state + " call path: " + sender().path() + " VI state: " + fsm.state()); } if (state != null && !state.equals(CallStateChanged.State.CANCELED)) { if (logger.isInfoEnabled()) { logger.info("At removeDialBranch() will cancel call: "+sender.path()+", isTerminated: "+sender.isTerminated()); } sender.tell(new Cancel(), self()); } if (outboundCall != null && outboundCall.equals(sender)) { outboundCall = null; } if (dialBranches != null && dialBranches.contains(sender)) dialBranches.remove(sender); } private void checkDialBranch(Object message, ActorRef sender, Attribute attribute) { CallStateChanged.State state = null; if (message instanceof CallStateChanged) { state = ((CallStateChanged)message).state(); } else if (message instanceof ReceiveTimeout) { state = CallStateChanged.State.NO_ANSWER; } if (dialBranches == null || dialBranches.size() == 0) { dialBranches = null; //https://telestax.atlassian.net/browse/RESTCOMM-1738 // If Finish Dial verb. RC need to cancel timeout for this verb before moving to next verb. context().setReceiveTimeout(Duration.Undefined()); if (attribute == null) { if (logger.isInfoEnabled()) { logger.info("Attribute is null, will destroy call and ask for the next verb from parser"); } if (sender != null && !sender.equals(call)) { callManager.tell(new DestroyCall(sender), self()); } // VI cannot move to next verb if media still being reproduced by media server // GetNextVerb is skipped while StopMediaGroup request is sent to media server // RCML Parser/VI activity continues when media server successful response is received if (parser != null && !msResponsePending) { final GetNextVerb next = new GetNextVerb(); parser.tell(next, self()); } } else { if (logger.isInfoEnabled()) { logger.info("Executing Dial Action for inbound call"); } if (sender.equals(call)) { executeDialAction(message, outboundCall); } else { executeDialAction(message, sender); } if (sender != null && !sender.equals(call)) { if (logger.isInfoEnabled()) { logger.info("Will destroy sender"); } callManager.tell(new DestroyCall(sender), self()); } } if (bridge != null) { // Stop the bridge bridge.tell(new StopBridge(liveCallModification), self()); recordingCall = false; bridge = null; } } else if (state != null && (state.equals(CallStateChanged.State.BUSY) || state.equals(CallStateChanged.State.CANCELED) || state.equals(CallStateChanged.State.FAILED))) { callManager.tell(new DestroyCall(sender), self()); } } private void onBridgeManagerResponse(BridgeManagerResponse message, ActorRef self, ActorRef sender) throws Exception { if (is(creatingBridge)) { this.bridge = message.get(); fsm.transition(message, initializingBridge); } } private void onBridgeStateChanged(BridgeStateChanged message, ActorRef self, ActorRef sender) throws Exception { switch (message.getState()) { case READY: if (is(initializingBridge)) { fsm.transition(message, bridging); } break; case BRIDGED: if (is(bridging)) { fsm.transition(message, bridged); } break; case FAILED: if (is(initializingBridge)) { fsm.transition(message, hangingUp); } default: break; } } private void onGetRelatedCall(GetRelatedCall message, ActorRef self, ActorRef sender) { final ActorRef callActor = message.call(); if (is(forking)) { sender.tell(dialBranches, self); return; } if (outboundCall != null) { if (callActor.equals(outboundCall)) { sender.tell(call, self); } else if (callActor.equals(call)) { sender.tell(outboundCall, self); } } else { // If previously that was a p2p call that changed to conference (for hold) // and now it changes again to a new url, the outbound call is null since // When we joined the call to the conference, we made outboundCall = null; sender.tell(new org.restcomm.connect.telephony.api.NotFound(), sender); } } private void onCallHoldStateChange(CallHoldStateChange message, ActorRef sender){ if (logger.isInfoEnabled()) { logger.info("CallHoldStateChange received, state: " + message.state()); } if (asImsUa){ if (sender.equals(outboundCall)) { call.tell(message, self()); } else if (sender.equals(call)) { outboundCall.tell(message, self()); } } } private void conferenceStateModeratorPresent(final Object message) { if(logger.isInfoEnabled()) { logger.info("VoiceInterpreter#conferenceStateModeratorPresent will unmute the call: " + call.path().toString()+", direction: "+callInfo.direction()); } call.tell(new Unmute(), self()); if (confSubVoiceInterpreter != null) { if(logger.isInfoEnabled()) { logger.info("VoiceInterpreter stopping confSubVoiceInterpreter"); } // Stop the conference back ground music final StopInterpreter stop = new StopInterpreter(); confSubVoiceInterpreter.tell(stop, self()); } } List<NameValuePair> parameters() { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); final String callSid = callInfo.sid().toString(); parameters.add(new BasicNameValuePair("CallSid", callSid)); parameters.add(new BasicNameValuePair("InstanceId", restcommConfiguration.getMain().getInstanceId())); if (outboundCallInfo != null) { final String outboundCallSid = outboundCallInfo.sid().toString(); parameters.add(new BasicNameValuePair("OutboundCallSid", outboundCallSid)); } final String accountSid = accountId.toString(); parameters.add(new BasicNameValuePair("AccountSid", accountSid)); final String from = e164(callInfo.from()); parameters.add(new BasicNameValuePair("From", from)); final String to = e164(callInfo.to()); parameters.add(new BasicNameValuePair("To", to)); final String state = callState.toString(); parameters.add(new BasicNameValuePair("CallStatus", state)); parameters.add(new BasicNameValuePair("ApiVersion", version)); final String direction = callInfo.direction(); parameters.add(new BasicNameValuePair("Direction", direction)); final String callerName = (callInfo.fromName() == null || callInfo.fromName().isEmpty()) ? "null" : callInfo.fromName(); parameters.add(new BasicNameValuePair("CallerName", callerName)); final String forwardedFrom = (callInfo.forwardedFrom() == null || callInfo.forwardedFrom().isEmpty()) ? "null" : callInfo.forwardedFrom(); parameters.add(new BasicNameValuePair("ForwardedFrom", forwardedFrom)); parameters.add(new BasicNameValuePair("CallTimestamp", callInfo.dateCreated().toString())); if (referTarget != null) { parameters.add(new BasicNameValuePair("ReferTarget", referTarget)); } if (transferor != null) { parameters.add(new BasicNameValuePair("Transferor", transferor)); } if (transferee != null) { parameters.add(new BasicNameValuePair("Transferee", transferee)); } // logger.info("Type " + callInfo.type()); SipServletResponse lastResponse = callInfo.lastResponse(); if (CreateCallType.SIP == callInfo.type()) { // Adding SIP OUT Headers and SipCallId for // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out // 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)); processCustomAndDiversionHeaders(lastResponse, "DialSipHeader_", parameters); } } } if (lastResponse == null) { // Restcomm VoiceInterpreter should check the INVITE for custom headers and pass them to RVD // https://telestax.atlassian.net/browse/RESTCOMM-710 final SipServletRequest invite = callInfo.invite(); // For outbound calls created with Calls REST API, the invite at this point will be null if (invite != null) { processCustomAndDiversionHeaders(invite, "SipHeader_", parameters); } } else { processCustomAndDiversionHeaders(lastResponse, "SipHeader_", parameters); } return parameters; } private void processCustomAndDiversionHeaders(SipServletMessage sipMessage, String prefix, List<NameValuePair> parameters) { Iterator<String> headerNames = sipMessage.getHeaderNames(); while (headerNames.hasNext()) { String headerName = headerNames.next(); if (headerName.startsWith("X-")) { if (logger.isDebugEnabled()) { logger.debug("%%%%%%%%%%% Identified customer header: " + headerName); } parameters.add(new BasicNameValuePair(prefix + headerName, sipMessage.getHeader(headerName))); } else if (headerName.startsWith("Diversion")) { final String sipDiversionHeader = sipMessage.getHeader(headerName); if (logger.isDebugEnabled()) { logger.debug("%%%%%%%%%%% Identified diversion header: " + sipDiversionHeader); } parameters.add(new BasicNameValuePair(prefix + headerName, sipDiversionHeader)); try { forwardedFrom = sipDiversionHeader.substring(sipDiversionHeader.indexOf("sip:") + 4, sipDiversionHeader.indexOf("@")); for(int i=0; i < parameters.size(); i++) { if (parameters.get(i).getName().equals("ForwardedFrom")) { if (parameters.get(i).getValue().equals("null")) { parameters.remove(i); parameters.add(new BasicNameValuePair("ForwardedFrom", forwardedFrom)); break; } else { // Not null, so it's not going to be overwritten with Diversion Header break; } } } } catch (Exception e) { logger.warning("Error parsing SIP Diversion header"+ e.getMessage()); } } } } private void stopRingTone() { // Stop playing the ringing tone from inbound call msResponsePending = true; msStopingRingTone = true; call.tell(new StopMediaGroup(), self()); } private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } protected Tag conference(final Tag container) { final List<Tag> children = container.children(); for (final Tag child : children) { if (Nouns.conference.equals(child.name())) { return child; } } return null; } protected Tag video(final Tag container) { final List<Tag> children = container.children(); for (final Tag child : children) { if (Nouns.video.equals(child.name())) { return child; } } return null; } } private final class InitializingCall extends AbstractAction { public InitializingCall(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (CallResponse.class.equals(klass)) { // Update the interpreter state. final CallResponse<CallInfo> response = (CallResponse<CallInfo>) message; callInfo = response.get(); callState = callInfo.state(); if (callState.name().equalsIgnoreCase(CallStateChanged.State.IN_PROGRESS.name())) { final CallStateChanged event = new CallStateChanged(CallStateChanged.State.IN_PROGRESS); source.tell(event, source); // fsm.transition(event, acquiringCallMediaGroup); return; } // Update the storage. if (callRecord != null) { callRecord = callRecord.setStatus(callState.toString()); final CallDetailRecordsDao records = storage.getCallDetailRecordsDao(); records.updateCallDetailRecord(callRecord); } // Update the application. callback(); // Start dialing. call.tell(new Dial(), source); // Set the timeout period. final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.create(timeout, TimeUnit.SECONDS)); } else if (Tag.class.equals(klass)) { // Update the interpreter state. verb = (Tag) message; // Answer the call. boolean confirmCall = true; if (enable200OkDelay && Verbs.dial.equals(verb.name())) { confirmCall=false; } call.tell(new Answer(callRecord.getSid(),confirmCall), 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 { final Class<?> klass = message.getClass(); if (CallResponse.class.equals(klass)) { createInitialCallRecord((CallResponse<CallInfo>) message); } // 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 void createInitialCallRecord(CallResponse<CallInfo> message) { final CallDetailRecordsDao records = storage.getCallDetailRecordsDao(); final CallResponse<CallInfo> response = message; callInfo = response.get(); callState = callInfo.state(); if (callInfo.direction().equals("inbound")) { callRecord = records.getCallDetailRecord(callInfo.sid()); if (callRecord == null) { // Create a call detail record for the call. 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()); if (callInfo.fromName() != null) { builder.setCallerName(callInfo.fromName()); } else { builder.setCallerName("Unknown"); } if (callInfo.from() != null) { builder.setFrom(callInfo.from()); } else { builder.setFrom("Unknown"); } 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")); builder.setMuted(false); builder.setOnHold(false); // 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(call.path().toString()); callRecord = builder.build(); records.addCallDetailRecord(callRecord); } // Update the application. callback(); } } private final class DownloadingFallbackRcml extends AbstractAction { public DownloadingFallbackRcml(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { 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 IOException { final UntypedActorContext context = getContext(); final State state = fsm.state(); if (initializingCall.equals(state)) { // Update the interpreter state. final CallStateChanged event = (CallStateChanged) message; callState = event.state(); // Update the application. callback(); // Update the storage. if (callRecord != null) { final CallDetailRecordsDao records = storage.getCallDetailRecordsDao(); callRecord = records.getCallDetailRecord(callRecord.getSid()); callRecord = callRecord.setStatus(callState.toString()); callRecord = callRecord.setStartTime(DateTime.now()); callRecord = callRecord.setForwardedFrom(forwardedFrom); records.updateCallDetailRecord(callRecord); } // Handle pending verbs. source.tell(verb, source); return; } else if (downloadingRcml.equals(state) || downloadingFallbackRcml.equals(state) || redirecting.equals(state) || finishGathering.equals(state) || finishRecording.equals(state) || sendingSms.equals(state) || finishDialing.equals(state) || finishConferencing.equals(state) || is(forking)) { response = ((DownloaderResponse) message).get(); if (parser != null) { context.stop(parser); parser = null; } final String type = response.getContentType(); if (type != null) { if (type.contains("text/xml") || type.contains("application/xml") || type.contains("text/html")) { parser = parser(response.getContentAsString()); } else if (type.contains("audio/wav") || type.contains("audio/wave") || type.contains("audio/x-wav")) { parser = parser("<Play>" + request.getUri() + "</Play>"); } else if (type.contains("text/plain")) { parser = parser("<Say>" + response.getContentAsString() + "</Say>"); } } else { if (call != null) { call.tell(new Hangup(outboundCallResponse), null); } final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } else if ((message instanceof CallResponse) && (rcml != null && !rcml.isEmpty())) { if (parser != null) { context.stop(parser); parser = null; } parser = parser(rcml); } else if (pausing.equals(state)) { context.setReceiveTimeout(Duration.Undefined()); } // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); if (parser != null) { parser.tell(next, source); } else if(logger.isInfoEnabled()) { logger.info("Parser is null"); } } } private final class NotFound extends AbstractAction { public NotFound(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { 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. call.tell(new org.restcomm.connect.telephony.api.NotFound(), source); } } private final class Rejecting extends AbstractAction { public Rejecting(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } String reason = "rejected"; Attribute attribute = verb.attribute("reason"); if (attribute != null) { reason = attribute.value(); if (reason != null && !reason.isEmpty()) { if ("rejected".equalsIgnoreCase(reason)) { reason = "rejected"; } else if ("busy".equalsIgnoreCase(reason)) { reason = "busy"; } else { reason = "rejected"; } } else { reason = "rejected"; } } // Reject the call. call.tell(new Reject(reason), source); } } private abstract class AbstractDialAction extends AbstractAction { public AbstractDialAction(final ActorRef source) { super(source); } protected String callerId(final Tag container) { // Parse "from". String callerId = null; // Issue 210: https://telestax.atlassian.net/browse/RESTCOMM-210 final boolean useInitialFromAsCallerId = configuration.subset("runtime-settings").getBoolean("from-address-to-proxied-calls"); Attribute attribute = verb.attribute("callerId"); if (attribute != null) { callerId = attribute.value(); if (callerId != null && !callerId.isEmpty()) { callerId = e164(callerId); if (callerId == null) { callerId = verb.attribute("callerId").value(); final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(ERROR_NOTIFICATION, 13214, callerId + " is an invalid callerId."); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return null; } } } if (callerId == null && useInitialFromAsCallerId) callerId = callInfo.from(); return callerId; } protected int timeout(final Tag container) { int timeout = 30; Attribute attribute = container.attribute("timeout"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { timeout = Integer.parseInt(value); } catch (final NumberFormatException exception) { final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 13212, value + " is not a valid timeout value for <Dial>"); notifications.addNotification(notification); } } } return timeout; } protected int timeLimit(final Tag container) { int timeLimit = 14400; Attribute attribute = container.attribute("timeLimit"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { timeLimit = Integer.parseInt(value); } catch (final NumberFormatException exception) { final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 13216, value + " is not a valid timeLimit value for <Dial>"); notifications.addNotification(notification); } } } return timeLimit; } protected MediaAttributes.MediaType videoEnabled(final Tag container) { boolean videoEnabled = false; Attribute attribute = container.attribute("enable"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { videoEnabled = Boolean.valueOf(value); } } if (videoEnabled) { return MediaAttributes.MediaType.AUDIO_VIDEO; } else { return MediaAttributes.MediaType.AUDIO_ONLY; } } protected MediaAttributes.VideoMode videoMode(final Tag container){ MediaAttributes.VideoMode videoMode = MediaAttributes.VideoMode.MCU; Attribute attribute = container.attribute("mode"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { videoMode = MediaAttributes.VideoMode.getValueOf(value); } catch (IllegalArgumentException e) { final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 15001, value + " is not a valid mode value for <Video>"); notifications.addNotification(notification); } } } return videoMode; } protected MediaAttributes.VideoResolution videoResolution(final Tag container) { MediaAttributes.VideoResolution videoResolution = MediaAttributes.VideoResolution.SEVEN_TWENTY_P; Attribute attribute = container.attribute("resolution"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { videoResolution = MediaAttributes.VideoResolution.getValueOf(value); } catch (IllegalArgumentException e) { final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 15002, value + " is not a valid resolution value for <Video>"); notifications.addNotification(notification); } } } return videoResolution; } protected MediaAttributes.VideoLayout videoLayout(final Tag container) { MediaAttributes.VideoLayout videoLayout = MediaAttributes.VideoLayout.LINEAR; Attribute attribute = container.attribute("layout"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { videoLayout = MediaAttributes.VideoLayout.getValueOf(value); } catch (IllegalArgumentException e) { final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 15003, value + " is not a valid layout value for <Video>"); notifications.addNotification(notification); } } } return videoLayout; } protected String videoOverlay(final Tag container) { String videoOverlay = null; Attribute attribute = container.attribute("overlay"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { videoOverlay = value; } } return videoOverlay; } public void fetchMediaAttributes(final Tag container){ Tag video = video(container); if(video != null){ MediaAttributes.MediaType mediaType = videoEnabled(video); if (!MediaAttributes.MediaType.AUDIO_ONLY.equals(mediaType)) { final MediaAttributes.VideoMode videoMode = videoMode(video); final MediaAttributes.VideoResolution videoResolution = videoResolution(video); final MediaAttributes.VideoLayout videoLayout = videoLayout(video); final String videoOverlay = videoOverlay(video); mediaAttributes = new MediaAttributes(mediaType, videoMode, videoResolution, videoLayout, videoOverlay); } } } } private final class StartDialing extends AbstractDialAction { public StartDialing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } if (logger.isInfoEnabled()) { logger.info("At StartDialing state, preparing Dial for RCML: "+verb.toString().trim().replace("\\n","")); } final String text = verb.text(); if (text != null && !text.isEmpty()) { // Build the appropriate tag for the text, such as Number, Client or SIP final Tag.Builder builder = Tag.builder(); // Read the next tag. if (text.contains("@")) { builder.setName(Nouns.SIP); } else if (text.startsWith("client")) { builder.setName(Nouns.client); } else { builder.setName(Nouns.number); } builder.setText(text); Tag numberTag = builder.build(); // Change the Dial verb to include the Tag we created before Tag.Builder tagBuilder = Tag.builder(); tagBuilder.addChild(numberTag); tagBuilder.setIterable(verb.isIterable()); tagBuilder.setName(verb.name()); tagBuilder.setParent(verb.parent()); for (Attribute attribute : verb.attributes()) { if (attribute != null) tagBuilder.addAttribute(attribute); } verb = null; verb = tagBuilder.build(); } if (verb.hasChildren()) { // Handle conferencing. final Tag child = conference(verb); if (child != null) { String name = null; final Tag grandchild = video(child); if (grandchild == null) { name = child.text(); } else { // Handle video conferencing Attribute attribute = child.attribute("name"); if (attribute != null && !StringUtils.isEmpty(attribute.toString())) { name = attribute.value(); } else { String errorMsg = "Attribute \"name\" not found or \"name\" value is empty inside <Conference> verb."; logger.error(errorMsg); throw new Exception(errorMsg); } fetchMediaAttributes(child); } final StringBuilder buffer = new StringBuilder(); //conference account should be phone account. i.e account of whoever owns that phone number. //https://github.com/RestComm/Restcomm-Connect/issues/1939 Sid conferenceAccountId = phoneId == null? accountId : phoneId; buffer.append(conferenceAccountId.toString()).append(":").append(name); conferenceNameWithAccountAndFriendlyName = buffer.toString(); callSid = null; if (callInfo != null && callInfo.sid() != null) { callSid = callInfo.sid(); } if (callSid == null && callRecord != null) { callSid = callRecord.getSid(); } final CreateConference create = new CreateConference(conferenceNameWithAccountAndFriendlyName, callSid, mediaAttributes); conferenceCenter.tell(create, source); } else { // Handle forking. dialBranches = new ArrayList<ActorRef>(); dialChildren = new ArrayList<Tag>(verb.children()); dialChildrenWithAttributes = new HashMap<ActorRef, Tag>(); isForking = true; final StartForking start = new StartForking(); source.tell(start, source); if (logger.isInfoEnabled()) { logger.info("Dial verb "+verb.toString().replace("\\n","")+" with more that one element, will start forking. Dial Children size: "+dialChildren.size()); } } } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } } private final class ProcessingDialChildren extends AbstractDialAction { public ProcessingDialChildren(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { Class<?> klass = message.getClass(); if (CallManagerResponse.class.equals(klass) && ((CallManagerResponse)message).succeeded()) { Tag child = dialChildren.get(0); final CallManagerResponse<Object> response = (CallManagerResponse<Object>) message; if (response.get() instanceof List) { List<ActorRef> calls = (List<ActorRef>) response.get(); for (ActorRef branch: calls) { dialBranches.add(branch); if (child.hasAttributes()) { dialChildrenWithAttributes.put(branch, child); } } } else { final ActorRef branch = (ActorRef) response.get(); dialBranches.add(branch); if (child.hasAttributes()) { dialChildrenWithAttributes.put(branch, child); } } dialChildren.remove(child); } else if (CallManagerResponse.class.equals(klass) && !((CallManagerResponse)message).succeeded()) { dialChildren.remove(0); } if (!dialChildren.isEmpty()) { CreateCall create = null; final Tag child = dialChildren.get(0); URI statusCallback = null; String statusCallbackMethod = "POST"; List<String> statusCallbackEvent = new LinkedList<String>(); if (child.hasAttribute("statusCallback")) { statusCallback = new URI(child.attribute("statusCallback").value()); } if (statusCallback != null) { if (child.hasAttribute("statusCallbackMethod")) { statusCallbackMethod = child.attribute("statusCallbackMethod").value(); } if (child.hasAttribute("statusCallbackEvent")) { statusCallbackEvent.addAll(Arrays.asList(child.attribute("statusCallbackEvent").value().replaceAll("\\s+","").split(","))); } else { statusCallbackEvent = new LinkedList<String>(); statusCallbackEvent.add("initiated"); statusCallbackEvent.add("ringing"); statusCallbackEvent.add("answered"); statusCallbackEvent.add("completed"); } } fetchMediaAttributes(child); //Get To String to; if(video(child) != null){ to = child.attribute("name").value(); } else { to = child.text(); } String callee = to; //Extract and pass custom headers for Dial Client and Dial Number String customHeaders = getCustomHeaders(to); //Get Callee after removing any custom headers (this way there will be no impact on the Extensions execution) callee = customHeaders != null ? to.substring(0, to.indexOf("?")) : to; if (Nouns.client.equals(child.name())) { if (call != null && callInfo != null) { create = new CreateCall(e164(callerId(verb)), e164(callee), null, null, callInfo.isFromApi(), timeout(verb), CreateCallType.CLIENT, accountId, callInfo.sid(), statusCallback, statusCallbackMethod, statusCallbackEvent, mediaAttributes, customHeaders); } else { create = new CreateCall(e164(callerId(verb)), e164(callee), null, null, false, timeout(verb), CreateCallType.CLIENT, accountId, null, statusCallback, statusCallbackMethod, statusCallbackEvent, mediaAttributes, customHeaders); } } else if (Nouns.number.equals(child.name())) { if (call != null && callInfo != null) { create = new CreateCall(e164(callerId(verb)), e164(callee), null, null, callInfo.isFromApi(), timeout(verb), CreateCallType.PSTN, accountId, callInfo.sid(), statusCallback, statusCallbackMethod, statusCallbackEvent, customHeaders); } else { create = new CreateCall(e164(callerId(verb)), e164(callee), null, null, false, timeout(verb), CreateCallType.PSTN, accountId, null, statusCallback, statusCallbackMethod, statusCallbackEvent, customHeaders); } } else if (Nouns.uri.equals(child.name())) { if (call != null && callInfo != null) { create = new CreateCall(e164(callerId(verb)), e164(callee), null, null, callInfo.isFromApi(), timeout(verb), CreateCallType.SIP, accountId, callInfo.sid(), statusCallback, statusCallbackMethod, statusCallbackEvent, mediaAttributes, customHeaders); } else { create = new CreateCall(e164(callerId(verb)), e164(callee), null, null, false, timeout(verb), CreateCallType.SIP, accountId, null, statusCallback, statusCallbackMethod, statusCallbackEvent, mediaAttributes, customHeaders); } } else if (Nouns.SIP.equals(child.name())) { // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out String username = null; String password = null; if (asImsUa) { username = imsUaLogin; password = imsUaPassword; } else { if (child.attribute("username") != null) { username = child.attribute("username").value(); } if (child.attribute("password") != null) { password = child.attribute("password").value(); } if (username == null || username.isEmpty()) { final Sid organizationSid = storage.getAccountsDao().getAccount(accountId).getOrganizationSid(); if (storage.getClientsDao().getClient(callInfo.from(), organizationSid) != null) { username = callInfo.from(); password = storage.getClientsDao().getClient(callInfo.from(), organizationSid).getPassword(); } } } if (call != null && callInfo != null) { create = new CreateCall(e164(callerId(verb)), e164(callee), username, password, false, timeout(verb), CreateCallType.SIP, accountId, callInfo.sid(), statusCallback, statusCallbackMethod, statusCallbackEvent, mediaAttributes, customHeaders); } else { create = new CreateCall(e164(callerId(verb)), e164(callee), username, password, false, timeout(verb), CreateCallType.SIP, accountId, null, statusCallback, statusCallbackMethod, statusCallbackEvent, mediaAttributes, customHeaders); } } callManager.tell(create, source); } else { if (dialBranches != null && dialBranches.size() > 0) { // Fork. final Fork fork = new Fork(); source.tell(fork, source); dialChildren = null; } else { // fsm.transition(message, hangingUp); Attribute attribute = null; if (verb != null) { attribute = verb.attribute("action"); } if (attribute == null) { if (logger.isInfoEnabled()) { logger.info("At ProcessingDialChildren with dialerBranches either null or 0 and attribute is null, will check for the next verb"); } final GetNextVerb next = new GetNextVerb(); if (parser != null) { parser.tell(next, source); } } else { if (logger.isInfoEnabled()) { logger.info("At ProcessingDialChildren with dialerBranches either null or 0 will execute Dial Action"); } executeDialAction(message, outboundCall); } } } } } private String getCustomHeaders(final String to) { String customHeaders = null; if (to.contains("?")) { customHeaders = to.substring(to.indexOf("?")+1, to.length()); } return customHeaders; } private final class Forking extends AbstractDialAction { public Forking(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (CallManagerResponse.class.equals(klass)) { final CallManagerResponse<ActorRef> response = (CallManagerResponse<ActorRef>) message; outboundCall = response.get(); outboundCall.tell(new Observe(source), source); if (monitoring != null) { outboundCall.tell(new Observe(monitoring), self()); } outboundCall.tell(new Dial(), source); } else if (Fork.class.equals(klass)) { final Observe observe = new Observe(source); final Dial dial = new Dial(); for (final ActorRef branch : dialBranches) { branch.tell(observe, source); if (monitoring != null) { branch.tell(new Observe(monitoring), self()); } branch.tell(dial, source); } } String path = configuration.subset("runtime-settings").getString("prompts-uri"); if (!path.endsWith("/")) { path += "/"; } path += "ringing.wav"; URI uri = null; try { uri = uriUtils.resolve(new URI(path), accountId); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 12400, exception.getMessage()); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } final Play play = new Play(uri, Short.MAX_VALUE); call.tell(play, source); final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.create(timeout(verb), TimeUnit.SECONDS)); } } private final class AcquiringOutboundCallInfo extends AbstractDialAction { public AcquiringOutboundCallInfo(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (isForking) { if (logger.isInfoEnabled()) { String msg = String.format("About to cancel Calls in dialBranches and keep outboundCall %s", outboundCall); logger.info(msg); } dialBranches.remove(outboundCall); for (final ActorRef branch : dialBranches) { branch.tell(new Cancel(), null); if (logger.isInfoEnabled()) { String msg = String.format("Canceled outbound Call %s", branch); logger.info(msg); } } dialBranches = null; } outboundCall.tell(new GetCallInfo(), source); } } private final class Bridged extends AbstractDialAction { public Bridged(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final int timeLimit = timeLimit(verb); final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.create(timeLimit, TimeUnit.SECONDS)); if (dialRecordAttribute != null && "true".equalsIgnoreCase(dialRecordAttribute.value())) { if(logger.isInfoEnabled()) { logger.info("Start recording of the bridge"); } record(bridge); } if(enable200OkDelay && verb !=null && Verbs.dial.equals(verb.name())){ call.tell(message, self()); } } } private void record(ActorRef target) { if(logger.isInfoEnabled()) { logger.info("Start recording of the call: "+target.path()+", VI state: "+fsm.state()); } Configuration runtimeSettings = configuration.subset("runtime-settings"); recordingSid = Sid.generate(Sid.Type.RECORDING); String path = runtimeSettings.getString("recordings-path"); String httpRecordingUri = runtimeSettings.getString("recordings-uri"); if (!path.endsWith("/")) { path += "/"; } if (!httpRecordingUri.endsWith("/")) { httpRecordingUri += "/"; } path += recordingSid.toString() + ".wav"; httpRecordingUri += recordingSid.toString() + ".wav"; this.recordingUri = URI.create(path); try { this.publicRecordingUri = uriUtils.resolve(new URI(httpRecordingUri), accountId); } catch (URISyntaxException e) { logger.error("URISyntaxException when trying to resolve Recording URI: " + e); } recordingCall = true; StartRecording message = new StartRecording(accountId, callInfo.sid(), runtimeSettings, storage, recordingSid, recordingUri); target.tell(message, null); } // private void recordCall() { // if(logger.isInfoEnabled()) { // logger.info("Start recording of the call"); // } // record(call); // } private void recordConference() { logger.info("Start recording of the conference"); record(conference); } @SuppressWarnings("unchecked") private void executeDialAction(final Object message, final ActorRef outboundCall) { Attribute attribute = null; if (verb != null && Verbs.dial.equals(verb.name())) { attribute = verb.attribute("action"); } else { if (logger.isInfoEnabled()) { logger.info("Either Verb is null OR not Dial, Dial Action will not be executed"); } } if (attribute != null && !dialActionExecuted) { if(logger.isInfoEnabled()){ logger.info("Proceeding to execute Dial Action attribute"); } this.dialActionExecuted = true; if (call != null) { try { if(logger.isInfoEnabled()) { logger.info("Trying to get inbound call Info"); } final Timeout expires = new Timeout(Duration.create(5, TimeUnit.SECONDS)); Future<Object> future = (Future<Object>) ask(call, new GetCallInfo(), expires); CallResponse<CallInfo> callResponse = (CallResponse<CallInfo>) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); callInfo = callResponse.get(); callState = callInfo.state(); } catch (Exception e) { if(logger.isDebugEnabled()) { logger.debug("Timeout waiting for inbound call info: \n" + e.getMessage()); } } } final List<NameValuePair> parameters = parameters(); if (outboundCall != null && !outboundCall.isTerminated()) { try { if(logger.isInfoEnabled()) { logger.info("Trying to get outboundCall Info"); } final Timeout expires = new Timeout(Duration.create(10, TimeUnit.SECONDS)); Future<Object> future = (Future<Object>) ask(outboundCall, new GetCallInfo(), expires); CallResponse<CallInfo> callResponse = (CallResponse<CallInfo>) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); outboundCallInfo = callResponse.get(); final long dialRingDuration = new Interval(this.outboundCallInfo.dateCreated(), this.outboundCallInfo.dateConUpdated()).toDuration() .getStandardSeconds(); parameters.add(new BasicNameValuePair("DialRingDuration", String.valueOf(dialRingDuration))); } catch (AskTimeoutException askTimeoutException){ logger.warning("Akka ask Timeout waiting for outbound call info: \n" + askTimeoutException.getMessage()); } catch (Exception e) { logger.error("Exception while waiting for outbound call info: \n" + e); } } // Handle Failed Calls if (message instanceof CallManagerResponse && !(((CallManagerResponse<ActorRef>) message).succeeded())) { if (outboundCallInfo != null) { parameters.add(new BasicNameValuePair("DialCallSid", (outboundCallInfo.sid() == null) ? "null" : outboundCallInfo.sid().toString())); } else { parameters.add(new BasicNameValuePair("DialCallSid", "null")); } parameters.add(new BasicNameValuePair("DialCallStatus", CallStateChanged.State.FAILED.toString())); parameters.add(new BasicNameValuePair("DialCallDuration", "0")); parameters.add(new BasicNameValuePair("RecordingUrl", null)); parameters.add(new BasicNameValuePair("PublicRecordingUrl", null)); } // Handle No-Answer calls else if (message instanceof ReceiveTimeout) { if (outboundCallInfo != null) { final String dialCallSid = this.outboundCallInfo.sid().toString(); long dialCallDuration; if (outboundCallInfo.state().toString().equalsIgnoreCase("Completed")) { dialCallDuration = new Interval(this.outboundCallInfo.dateConUpdated(), DateTime.now()).toDuration() .getStandardSeconds(); } else { dialCallDuration = 0L; } final String recordingUrl = this.recordingUri == null ? null : this.recordingUri.toString(); final String publicRecordingUrl = this.publicRecordingUri == null ? null : this.publicRecordingUri.toString(); parameters.add(new BasicNameValuePair("DialCallSid", dialCallSid)); // parameters.add(new BasicNameValuePair("DialCallStatus", dialCallStatus == null ? null : dialCallStatus // .toString())); parameters.add(new BasicNameValuePair("DialCallStatus", outboundCallInfo.state().toString())); parameters.add(new BasicNameValuePair("DialCallDuration", String.valueOf(dialCallDuration))); parameters.add(new BasicNameValuePair("RecordingUrl", recordingUrl)); parameters.add(new BasicNameValuePair("PublicRecordingUrl", publicRecordingUrl)); } else { parameters.add(new BasicNameValuePair("DialCallSid", "null")); parameters.add(new BasicNameValuePair("DialCallStatus", CallStateChanged.State.NO_ANSWER.toString())); parameters.add(new BasicNameValuePair("DialCallDuration", "0")); parameters.add(new BasicNameValuePair("RecordingUrl", null)); parameters.add(new BasicNameValuePair("PublicRecordingUrl", null)); } } else { // Handle the rest of the cases if (outboundCallInfo != null) { final String dialCallSid = this.outboundCallInfo.sid().toString(); final CallStateChanged.State dialCallStatus = this.outboundCallInfo.state(); long dialCallDuration = 0L; //In some cases, such as when the outbound dial is busy, the dialCallDuration wont be possbile to be calculated and will throw exception try { dialCallDuration = new Interval(this.outboundCallInfo.dateConUpdated(), DateTime.now()).toDuration() .getStandardSeconds(); } catch (Exception e) {} final String recordingUrl = this.recordingUri == null ? null : this.recordingUri.toString(); final String publicRecordingUrl = this.publicRecordingUri == null ? null : this.publicRecordingUri.toString(); parameters.add(new BasicNameValuePair("DialCallSid", dialCallSid)); // If Caller sent the BYE request, at the time we execute this method, the outbound call status is still in // progress if (callInfo.state().equals(CallStateChanged.State.COMPLETED)) { parameters.add(new BasicNameValuePair("DialCallStatus", callInfo.state().toString())); } else { parameters.add(new BasicNameValuePair("DialCallStatus", dialCallStatus == null ? null : dialCallStatus .toString())); } if (callState == CallStateChanged.State.BUSY) parameters.add(new BasicNameValuePair("DialCallDuration", "0")); else parameters.add(new BasicNameValuePair("DialCallDuration", String.valueOf(dialCallDuration))); parameters.add(new BasicNameValuePair("RecordingUrl", recordingUrl)); parameters.add(new BasicNameValuePair("PublicRecordingUrl", publicRecordingUrl)); } else { parameters.add(new BasicNameValuePair("DialCallSid", "null")); parameters.add(new BasicNameValuePair("DialCallStatus", "null")); parameters.add(new BasicNameValuePair("DialCallDuration", "0")); parameters.add(new BasicNameValuePair("RecordingUrl", null)); parameters.add(new BasicNameValuePair("PublicRecordingUrl", "null")); } } final NotificationsDao notifications = storage.getNotificationsDao(); if (attribute != null) { if(logger.isInfoEnabled()) { logger.info("Executing Dial Action attribute."); } String action = attribute.value(); if (action != null && !action.isEmpty()) { URI target = null; try { target = URI.create(action); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, action + " is an invalid URI."); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); self().tell(stop, self()); return; } final URI base = request.getUri(); final URI uri = uriUtils.resolveWithBase(base, target); // Parse "method". String method = "POST"; attribute = verb.attribute("method"); if (attribute != null) { method = attribute.value(); if (method != null && !method.isEmpty()) { if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) { final Notification notification = notification(WARNING_NOTIFICATION, 13210, method + " is not a valid HTTP method for <Dial>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } if(logger.isInfoEnabled()) { logger.info("Dial Action URL: " + uri.toString() + " Method: " + method); } if(logger.isDebugEnabled()) { logger.debug("Dial Action parameters: \n" + parameters); } // Redirect to the action url. request = new HttpRequestDescriptor(uri, method, parameters); // Tell the downloader to send the Dial Parameters to the Action url but we don't need a reply back so sender == null downloader.tell(request, self()); return; } } } else { if (logger.isInfoEnabled()) { if (attribute == null) { logger.info("DialAction URL is null, DialAction will not be executed"); } else { logger.info("DialAction has already been executed"); } } } } private final class FinishDialing extends AbstractDialAction { public FinishDialing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final State state = fsm.state(); if(logger.isInfoEnabled()) { logger.info("At FinishDialing, current VI state: " + state); } if (message instanceof ReceiveTimeout) { if(logger.isInfoEnabled()) { logger.info("Received timeout, will cancel branches, current VoiceIntepreter state: " + state); } if(enable200OkDelay){ outboundCallResponse = SipServletResponse.SC_REQUEST_TIMEOUT; } //The forking timeout reached, we have to cancel all dial branches final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); if (dialBranches != null) { Iterator<ActorRef> dialBranchesIterator = dialBranches.iterator(); while (dialBranchesIterator.hasNext()) { ActorRef branch = dialBranchesIterator.next(); branch.tell(new Cancel(), source); if(logger.isInfoEnabled()) { logger.info("Canceled branch: " + branch.path()+", isTerminated: "+branch.isTerminated()); } } // Stop playing the ringing tone from inbound call stopRingTone(); } else if (outboundCall != null) { outboundCall.tell(new Cancel(), source); call.tell(new Hangup(outboundCallResponse), self()); } if (dialBranches == null) { checkDialBranch(message,sender,action); } dialChildren = null; callback(); return; } if (message instanceof CallStateChanged) { if(logger.isInfoEnabled()) { String msg = String.format("CallStateChanged state received: [%s] , sender path: [%s] , is initial call: [%s] , call state: [%s], fsm state: [%s]", ((CallStateChanged)message).toString(), sender().path(), (sender == call), callState.toString(), fsm.state()); logger.info(msg); } if (forking.equals(state) || finishDialing.equals(state) || is(bridged) || is(bridging) ) { if (sender.equals(call)) { //Initial call wants to finish dialing if(logger.isInfoEnabled()) { logger.info("Sender == call: " + sender.equals(call)); } final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); if (dialBranches != null) { Iterator<ActorRef> dialBranchesIterator = dialBranches.iterator(); while (dialBranchesIterator.hasNext()) { ActorRef branch = dialBranchesIterator.next(); branch.tell(new Cancel(), source); } } else if (outboundCall != null) { outboundCall.tell(new Cancel(), source); } //Issue https://github.com/RestComm/Restcomm-Connect/issues/2157. If outbound call != null, //then checking the DialBranch here will cause race condition that will prevent outbound call to move //to completed state because checkDialBranch() method will ask for the next verb which could be the End.tag if (dialBranches == null && outboundCall == null) { checkDialBranch(message,sender,action); } dialChildren = null; callback(); return; } else if (dialBranches != null && dialBranches.contains(sender)) { if (logger.isInfoEnabled()) { logger.info("At FinishDialing. Sender in the dialBranches, will remove and check next verb"); } removeDialBranch(message, sender); return; } else { if (callState == CallStateChanged.State.IN_PROGRESS) { if (logger.isInfoEnabled()) { String msg = String.format("At finishDialingState, will ASK call to hangup. Current VI State %s Call State: %s ",state, callState); logger.info(msg); } call.tell(new Hangup(), self()); } else { if (logger.isInfoEnabled()) { String msg = String.format("Didn't sent Hangup to call because current call state is: [%s]", callState.toString()); logger.info(msg); } } } } } } } private final class AcquiringConferenceInfo extends AbstractDialAction { public AcquiringConferenceInfo(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final ConferenceCenterResponse response = (ConferenceCenterResponse) message; conference = response.get(); conference.tell(new Observe(source), source); conference.tell(new GetConferenceInfo(), source); } } private final class JoiningConference extends AbstractDialAction { public JoiningConference(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { conferenceState = conferenceInfo.state(); conferenceSid = conferenceInfo.sid(); final Tag child = conference(verb); // If there is room join the conference. Attribute attribute = child.attribute("maxParticipants"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { maxParticipantLimit = Integer.parseInt(value); } catch (final NumberFormatException ignored) { } } } if (conferenceInfo.globalParticipants() < maxParticipantLimit) { // Play beep. beep = true; attribute = child.attribute("beep"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { beep = Boolean.parseBoolean(value); } } // Only play beep if conference is already running // Do not play it while participants are listening to background music if (beep && ConferenceStateChanged.State.RUNNING_MODERATOR_PRESENT.equals(conferenceInfo.state())) { playBeepOnEnter(source); }else{ if (logger.isInfoEnabled()) { logger.info("Wont play beep bcz: beep="+beep+" AND conferenceInfo.state()="+conferenceInfo.state()); } } if (logger.isInfoEnabled()) { logger.info("About to join call to Conference: "+conferenceInfo.name()+", with state: "+conferenceInfo.state()+", with moderator present: "+conferenceInfo.isModeratorPresent()+", and current participants: "+conferenceInfo.globalParticipants()); } // Join the conference. //Adding conference record in DB //For outbound call the CDR will be updated at Call.InProgress() addConferenceStuffInCDR(conferenceSid); final AddParticipant request = new AddParticipant(call, mediaAttributes); conference.tell(request, source); } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } // parse mute attribute = child.attribute("muted"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { muteCall = Boolean.parseBoolean(value); } } // parse startConferenceOnEnter. attribute = child.attribute("startConferenceOnEnter"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { startConferenceOnEnter = Boolean.parseBoolean(value); } } // Parse "endConferenceOnExit" attribute = child.attribute("endConferenceOnExit"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { endConferenceOnExit = Boolean.parseBoolean(value); } } } private void addConferenceStuffInCDR(Sid conferenceSid) { //updating conferenceSid and other conference related info in cdr if (callRecord != null) { if (logger.isInfoEnabled()) { logger.info("Updating CDR for call: "+callInfo.sid()+", call status: "+callInfo.state()+", to include Conference details, conference: "+conferenceSid); } callRecord = callRecord.setConferenceSid(conferenceSid); callRecord = callRecord.setMuted(muteCall); callRecord = callRecord.setStartConferenceOnEnter(startConferenceOnEnter); callRecord = callRecord.setEndConferenceOnExit(endConferenceOnExit); final CallDetailRecordsDao records = storage.getCallDetailRecordsDao(); records.updateCallDetailRecord(callRecord); } } } private final class Conferencing extends AbstractDialAction { public Conferencing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { boolean onHoldInCDR = false; boolean onMuteInCDR = muteCall; if (message instanceof List<?>) { List<URI> waitUrls = (List<URI>) message; playWaitUrl(waitUrls, self()); playWaitUrlPending = false; return; } final NotificationsDao notifications = storage.getNotificationsDao(); final Tag child = conference(verb); conferenceVerb = verb; if (muteCall) { final Mute mute = new Mute(); call.tell(mute, source); } // Parse start conference. Attribute attribute = child.attribute("startConferenceOnEnter"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { startConferenceOnEnter = Boolean.parseBoolean(value); } } else { //Default values is startConferenceOnEnter = true startConferenceOnEnter = true; } confModeratorPresent = startConferenceOnEnter; if (logger.isInfoEnabled()) { logger.info("At conferencing, VI state: "+fsm.state()+" , playMusicForConference: "+playMusicForConference+" ConferenceState: "+conferenceState.name()+" startConferenceOnEnter: "+startConferenceOnEnter+" conferenceInfo.globalParticipants(): "+conferenceInfo.globalParticipants()); } if (playMusicForConference) { // && startConferenceOnEnter) { //playMusicForConference is true, take over control of startConferenceOnEnter if (conferenceInfo.globalParticipants() == 1) { startConferenceOnEnter = false; } else if (conferenceInfo.globalParticipants() > 1) { if (startConferenceOnEnter || conferenceInfo.isModeratorPresent()) { startConferenceOnEnter = true; } else { startConferenceOnEnter = false; } } } if (!startConferenceOnEnter && conferenceState == ConferenceStateChanged.State.RUNNING_MODERATOR_ABSENT) { if (!muteCall) { final Mute mute = new Mute(); if(logger.isInfoEnabled()) { logger.info("Muting the call as startConferenceOnEnter =" + startConferenceOnEnter + " , callMuted = " + muteCall); } call.tell(mute, source); onMuteInCDR = true; } // Only play background music if conference is not doing that already // If conference state is RUNNING_MODERATOR_ABSENT and participants > 0 then BG music is playing already if(logger.isInfoEnabled()) { logger.info("Play background music? " + (conferenceInfo.globalParticipants() == 1)); } boolean playBackground = conferenceInfo.globalParticipants() == 1; if (playBackground) { // Parse wait url. URI waitUrl = new URI("/restcomm/music/electronica/teru_-_110_Downtempo_Electronic_4.wav"); attribute = child.attribute("waitUrl"); if (attribute != null) { String value = attribute.value(); if (value != null && !value.isEmpty()) { try { waitUrl = URI.create(value); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 13233, method + " is not a valid waitUrl value for <Conference>"); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); // TODO shouldn't we return here? } } } final URI base = request.getUri(); waitUrl = uriUtils.resolveWithBase(base, waitUrl); // Parse method. String method = "POST"; attribute = child.attribute("waitMethod"); if (attribute != null) { method = attribute.value(); if (method != null && !method.isEmpty()) { if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) { final Notification notification = notification(WARNING_NOTIFICATION, 13234, method + " is not a valid waitMethod value for <Conference>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } if (!waitUrl.getPath().toLowerCase().endsWith("wav")) { if (logger.isInfoEnabled()) { logger.info("WaitUrl for Conference will use RCML from URI: "+waitUrl.toString()); } final List<NameValuePair> parameters = parameters(); request = new HttpRequestDescriptor(waitUrl, method, parameters); downloader.tell(request, self()); playWaitUrlPending = true; return; } // Tell conference to play music to participants on hold if (waitUrl != null && !playWaitUrlPending) { onHoldInCDR = true; playWaitUrl(waitUrl, super.source); } } } else if (conferenceState == ConferenceStateChanged.State.RUNNING_MODERATOR_ABSENT) { // Tell the conference the moderator is now present // Causes background music to stop playing and all participants will be unmuted conference.tell(new ConferenceModeratorPresent(beep), source); if (beep) { playBeepOnEnter(source); }else{ if (logger.isInfoEnabled()) { logger.info("Wont play beep bcz: beep="+beep+" AND conferenceInfo.state()="+conferenceInfo.state()); } } // Check if moderator wants to record the conference Attribute record = verb.attribute("record"); if (record != null && "true".equalsIgnoreCase(record.value())) { // XXX get record limit etc from dial verb recordConference(); } // Call is no more on hold //open this block when mute/hold functionality in conference API is fixed //updateMuteAndHoldStatusOfAllConferenceCalls(conferenceDetailRecord.getAccountSid(), conferenceDetailRecord.getSid(), false, false); } else { // Call is no more on hold //open this block when mute/hold functionality in conference API is fixed //updateMuteAndHoldStatusOfAllConferenceCalls(conferenceDetailRecord.getAccountSid(), conferenceDetailRecord.getSid(), false, false); } // update Call hold and mute status if(callRecord != null){ callRecord = callRecord.setOnHold(onHoldInCDR); callRecord = callRecord.setMuted(onMuteInCDR); final CallDetailRecordsDao callRecords = storage.getCallDetailRecordsDao(); callRecords.updateCallDetailRecord(callRecord); } // Set timer. final int timeLimit = timeLimit(verb); final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.create(timeLimit, TimeUnit.SECONDS)); } } protected void playBeepOnEnter(ActorRef source){ String path = configuration.subset("runtime-settings").getString("prompts-uri"); if (!path.endsWith("/")) { path += "/"; } String entryAudio = configuration.subset("runtime-settings").getString("conference-entry-audio"); path += entryAudio == null || entryAudio.equals("") ? "beep.wav" : entryAudio; URI uri = null; try { uri = uriUtils.resolve(new URI(path), accountId); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 12400, exception.getMessage()); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } if (logger.isInfoEnabled()) { logger.info("Will ask conference: "+conferenceInfo.name()+" ,to play beep: "+uri); } final Play play = new Play(uri, 1); conference.tell(play, source); } //Because of RMS issue https://github.com/RestComm/mediaserver/issues/158 we cannot have List<URI> for waitUrl protected void playWaitUrl(final List<URI> waitUrls, final ActorRef source) { conference.tell(new Play(waitUrls, Short.MAX_VALUE, confModeratorPresent), source); } protected void playWaitUrl(final URI waitUrl, final ActorRef source) { conference.tell(new Play(waitUrl, Short.MAX_VALUE, confModeratorPresent), source); } /* open this block when mute/hold functionality in conference API is fixed * protected void updateMuteAndHoldStatusOfAllConferenceCalls(final Sid accountSid, final Sid conferenceSid, final boolean mute, final boolean hold) throws ParseException{ if (conferenceSid != null){ CallDetailRecordFilter filter = new CallDetailRecordFilter(accountSid.toString(), null, null, null, "in-progress", null, null, null, conferenceSid.toString(), 50, 0); CallDetailRecordsDao callRecordsDAO = storage.getCallDetailRecordsDao(); List<CallDetailRecord> conferenceCallRecords = callRecordsDAO.getCallDetailRecords(filter); if(conferenceCallRecords != null){ for(CallDetailRecord singleRecord:conferenceCallRecords){ singleRecord.setMuted(mute); singleRecord.setOnHold(hold); callRecordsDAO = storage.getCallDetailRecordsDao(); callRecordsDAO.updateCallDetailRecord(singleRecord); } } } }*/ private final class FinishConferencing extends AbstractDialAction { public FinishConferencing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (message instanceof ReceiveTimeout) { if (logger.isInfoEnabled()) { logger.info("At FinishConferencing received timeout, VI path: "+self().path()+", call path: "+call.path()); } final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.Undefined()); final RemoveParticipant remove = new RemoveParticipant(call); conference.tell(remove, source); } // Clean up if (message instanceof ConferenceStateChanged) { // Destroy conference if state changed to completed (last participant in call) ConferenceStateChanged confStateChanged = (ConferenceStateChanged) message; if (ConferenceStateChanged.State.COMPLETED.equals(confStateChanged.state())) { DestroyConference destroyConference = new DestroyConference(conferenceInfo.name()); conferenceCenter.tell(destroyConference, super.source); } } conference = null; // Parse remaining conference attributes. final NotificationsDao notifications = storage.getNotificationsDao(); // Parse "action". Attribute attribute = conferenceVerb.attribute("action"); if (attribute != null) { String action = attribute.value(); if (action != null && !action.isEmpty()) { URI target = null; try { target = URI.create(action); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, action + " 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 = conferenceVerb.attribute("method"); if (attribute != null) { method = attribute.value(); if (method != null && !method.isEmpty()) { if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) { final Notification notification = notification(WARNING_NOTIFICATION, 13210, method + " is not a valid HTTP method for <Dial>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } // Redirect to the action url. final List<NameValuePair> parameters = parameters(); request = new HttpRequestDescriptor(uri, method, parameters); downloader.tell(request, source); return; } } // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } 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("At Finished state, state: " + fsm.state()+", liveCallModification: "+liveCallModification); } final Class<?> klass = message.getClass(); if (callRecord != null) { final CallDetailRecordsDao records = storage.getCallDetailRecordsDao(); callRecord = records.getCallDetailRecord(callRecord.getSid()); 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); records.updateCallDetailRecord(callRecord); } if (!dialActionExecuted) { executeDialAction(message, outboundCall); } callback(true); // XXX review bridge cleanup!! // Cleanup bridge // if ((bridge != null) && (is(forking) || is(acquiringOutboundCallInfo) || is(bridged))) { if (bridge != null) { // Stop the bridge bridge.tell(new StopBridge(liveCallModification), super.source); recordingCall = false; bridge = null; } // Cleanup the outbound call if necessary. // XXX verify if this code is still necessary if (outboundCall != null && !liveCallModification) { outboundCall.tell(new StopObserving(source), null); outboundCall.tell(new Hangup(), null); callManager.tell(new DestroyCall(outboundCall), null); } // If the call is in a conference remove it. // if (conference != null) { // // Stop Observing the conference // conference.tell(new StopObserving(super.source), null); // // // Play beep when participant leave the conference. // // Do not play beep if this was the last participant to leave the conference, because there is no one to listen to the beep. // if(conferenceInfo.participants() != null && conferenceInfo.participants().size() !=0 ){ // String path = configuration.subset("runtime-settings").getString("prompts-uri"); // if (!path.endsWith("/")) { // path += "/"; // } // String exitAudio = configuration.subset("runtime-settings").getString("conference-exit-audio"); // path += exitAudio == null || exitAudio.equals("") ? "alert.wav" : exitAudio; // URI uri = null; // try { // uri = UriUtils.resolve(new URI(path)); // } catch (final Exception exception) { // final Notification notification = notification(ERROR_NOTIFICATION, 12400, exception.getMessage()); // final NotificationsDao notifications = storage.getNotificationsDao(); // notifications.addNotification(notification); // sendMail(notification); // final StopInterpreter stop = new StopInterpreter(); // source.tell(stop, source); // return; // } // final Play play = new Play(uri, 1); // conference.tell(play, source); // } // if (endConferenceOnExit) { // // Stop the conference if endConferenceOnExit is true // final StopConference stop = new StopConference(); // conference.tell(stop, super.source); // } else { // conference.tell(new RemoveParticipant(call), source); // } // } if (!liveCallModification) { // Destroy the Call(s). if (call!= null && !call.isTerminated()) { // && End.instance().equals(verb.name())) { call.tell(new Hangup(), self()); } if (outboundCall != null &&!outboundCall.isTerminated()) { outboundCall.tell(new Hangup(), self()); } callManager.tell(new DestroyCall(call), super.source); if (outboundCall != null) { callManager.tell(new DestroyCall(outboundCall), super.source); } if (sender != call && !sender.equals(self())) { callManager.tell(new DestroyCall(sender), super.source); } } else { // Make sure the media operations of the call are stopped // so we can start processing a new RestComm application call.tell(new StopMediaGroup(true), super.source); // if (is(conferencing)) // call.tell(new Leave(true), self()); } // Stop the dependencies. final UntypedActorContext context = getContext(); if (mailerNotify != null) context.stop(mailerNotify); if (mailerService != null) context.stop(mailerService); context.stop(getAsrService()); context.stop(getFaxService()); context.stop(getCache()); context.stop(getSynthesizer()); // Stop the interpreter. postCleanup(); } } @Override public void postStop() { if (!fsm.state().equals(uninitialized)) { if(logger.isInfoEnabled()) { logger.info("VoiceIntepreter: " + self().path() + "At the postStop() method. Will clean up Voice Interpreter. Keep calls: " + liveCallModification); } if (fsm.state().equals(bridged) && outboundCall != null && !liveCallModification) { if(logger.isInfoEnabled()) { logger.info("At postStop(), will clean up outbound call"); } outboundCall.tell(new Hangup(), null); callManager.tell(new DestroyCall(outboundCall), null); outboundCall = null; } if (call != null && !liveCallModification) { if(logger.isInfoEnabled()) { logger.info("At postStop(), will clean up call"); } callManager.tell(new DestroyCall(call), null); call = null; } getContext().stop(self()); postCleanup(); } if(asImsUa){ if(callRecord != null){ final CallDetailRecordsDao callRecords = storage.getCallDetailRecordsDao(); callRecords.removeCallDetailRecord(callRecord.getSid()); } } super.postStop(); } private final class CreatingBridge extends AbstractAction { public CreatingBridge(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { final CreateBridge create = new CreateBridge(outboundCallInfo.mediaAttributes()); bridgeManager.tell(create, super.source); } } private final class InitializingBridge extends AbstractAction { public InitializingBridge(ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Start monitoring bridge state changes final Observe observe = new Observe(super.source); bridge.tell(observe, super.source); // Initialize bridge final StartBridge start = new StartBridge(); bridge.tell(start, super.source); } } private final class Bridging extends AbstractAction { public Bridging(ActorRef source) { super(source); } private ActorRef buildSubVoiceInterpreter(Tag child) throws MalformedURLException, URISyntaxException { // URI url = new URL(child.attribute("url").value()).toURI(); URI url = null; if (request != null) { final URI base = request.getUri(); url = uriUtils.resolveWithBase(base, new URI(child.attribute("url").value())); } else { url = uriUtils.resolve(new URI(child.attribute("url").value()), accountId); } String method; if (child.hasAttribute("method")) { method = child.attribute("method").value().toUpperCase(); } else { method = "POST"; } final SubVoiceInterpreterParams.Builder builder = new SubVoiceInterpreterParams.Builder(); builder.setConfiguration(configuration); builder.setStorage(storage); builder.setCallManager(super.source); builder.setSmsService(smsService); builder.setAccount(accountId); builder.setVersion(version); builder.setUrl(url); builder.setMethod(method); final Props props = SubVoiceInterpreter.props(builder.build()); return getContext().actorOf(props); } @Override public void execute(Object message) throws Exception { if(logger.isInfoEnabled()) { String msg = String.format("Joining call %s from: %s to: %s with outboundCall %s from: %s to: %s", call, callInfo.from(), callInfo.to(), outboundCall, outboundCallInfo.from(), outboundCallInfo.to()); logger.info(msg); } // Check for any Dial verbs with url attributes (call screening url) Tag child = dialChildrenWithAttributes.get(outboundCall); if (child != null && child.attribute("url") != null) { if (logger.isInfoEnabled()) { String msg = String.format("Call screening is enabled and will execute for %s", child.attribute("url")); logger.info(msg); } final ActorRef interpreter = buildSubVoiceInterpreter(child); StartInterpreter start = new StartInterpreter(outboundCall); try { Timeout expires = new Timeout(Duration.create(60, TimeUnit.SECONDS)); Future<Object> future = (Future<Object>) ask(interpreter, start, expires); Object object = Await.result(future, Duration.create(60, TimeUnit.SECONDS)); if (!End.class.equals(object.getClass())) { fsm.transition(message, hangingUp); return; } } catch (Exception e) { if(logger.isInfoEnabled()) { logger.info("Exception while trying to execute call screening: "+e); } fsm.transition(message, hangingUp); return; } // Stop SubVoiceInterpreter outboundCall.tell(new StopObserving(interpreter), null); getContext().stop(interpreter); } if (logger.isInfoEnabled()) { String msg = String.format("Will ask call %s to stop ringing", call); logger.info(msg); } // Stop ringing from inbound call final StopMediaGroup stop = new StopMediaGroup(); call.tell(stop, super.source); } } }
182,896
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SubVoiceInterpreterParams.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/SubVoiceInterpreterParams.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; 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 SubVoiceInterpreterParams { private Configuration configuration; private DaoManager storage; private ActorRef callManager; private ActorRef conferenceCenter; private ActorRef smsService; 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; private Boolean hangupOnEnd; private SubVoiceInterpreterParams(Configuration configuration, DaoManager storage, ActorRef callManager, ActorRef conferenceCenter, ActorRef smsService, Sid account, Sid phone, String version, URI url, String method, URI fallbackUrl, String fallbackMethod, URI statusCallback, String statusCallbackMethod, String emailAddress, Boolean hangupOnEnd) { this.configuration = configuration; this.storage = storage; this.callManager = callManager; this.conferenceCenter = conferenceCenter; this.smsService = smsService; 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; this.hangupOnEnd = hangupOnEnd; } public Configuration getConfiguration() { return configuration; } public DaoManager getStorage() { return storage; } public ActorRef getCallManager() { return callManager; } public ActorRef getConferenceCenter() { return conferenceCenter; } public ActorRef getSmsService() { return smsService; } 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; } public Boolean getHangupOnEnd() { return hangupOnEnd; } public static final class Builder { private Configuration configuration; private DaoManager storage; private ActorRef callManager; private ActorRef conferenceCenter; private ActorRef smsService; 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; private Boolean hangupOnEnd = false; public Builder() { } public Builder setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } public Builder setStorage(DaoManager storage) { this.storage = storage; return this; } public Builder setCallManager(ActorRef callManager) { this.callManager = callManager; return this; } public Builder setConferenceCenter(ActorRef conferenceCenter) { this.conferenceCenter = conferenceCenter; return this; } public Builder setSmsService(ActorRef smsService) { this.smsService = smsService; 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 Builder setHangupOnEnd(Boolean hangupOnEnd) { this.hangupOnEnd = hangupOnEnd; return this; } public SubVoiceInterpreterParams build() { return new SubVoiceInterpreterParams(configuration, storage, callManager, conferenceCenter, smsService, account, phone, version, url, method, fallbackUrl, fallbackMethod, statusCallback, statusCallbackMethod, emailAddress, hangupOnEnd); } } }
6,970
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StartForking.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/StartForking.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class StartForking { public StartForking() { super(); } }
1,087
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BaseVoiceInterpreter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/BaseVoiceInterpreter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; 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 akka.util.Timeout; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.joda.time.DateTime; import org.restcomm.connect.asr.AsrInfo; import org.restcomm.connect.asr.AsrRequest; import org.restcomm.connect.asr.AsrResponse; import org.restcomm.connect.asr.GetAsrInfo; import org.restcomm.connect.asr.ISpeechAsr; import org.restcomm.connect.commons.cache.DiskCacheFactory; 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.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.util.WavUtils; 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.RecordingsDao; import org.restcomm.connect.dao.SmsMessagesDao; import org.restcomm.connect.dao.TranscriptionsDao; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.dao.entities.MediaAttributes; import org.restcomm.connect.dao.entities.Notification; import org.restcomm.connect.dao.entities.Recording; import org.restcomm.connect.dao.entities.SmsMessage; import org.restcomm.connect.dao.entities.SmsMessage.Direction; import org.restcomm.connect.dao.entities.SmsMessage.Status; import org.restcomm.connect.dao.entities.Transcription; import org.restcomm.connect.email.EmailService; import org.restcomm.connect.email.api.EmailRequest; import org.restcomm.connect.email.api.EmailResponse; 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.fax.FaxRequest; import org.restcomm.connect.fax.InterfaxService; import org.restcomm.connect.http.asyncclient.HttpAsycClientHelper; 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.rcml.Attribute; 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.SmsVerb; import org.restcomm.connect.interpreter.rcml.Tag; import org.restcomm.connect.interpreter.rcml.Verbs; import org.restcomm.connect.interpreter.rcml.domain.GatherAttributes; import org.restcomm.connect.mscontrol.api.messages.Collect; import org.restcomm.connect.mscontrol.api.messages.CollectedResult; import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.Play; import org.restcomm.connect.mscontrol.api.messages.Record; import org.restcomm.connect.sms.api.CreateSmsSession; import org.restcomm.connect.sms.api.DestroySmsSession; import org.restcomm.connect.sms.api.SmsServiceResponse; import org.restcomm.connect.sms.api.SmsSessionAttribute; import org.restcomm.connect.sms.api.SmsSessionInfo; import org.restcomm.connect.sms.api.SmsSessionRequest; import org.restcomm.connect.sms.api.SmsSessionResponse; import org.restcomm.connect.telephony.api.CallInfo; import org.restcomm.connect.telephony.api.CallManagerResponse; 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.telephony.api.Hangup; import org.restcomm.connect.telephony.api.Reject; 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.Await; import scala.concurrent.Future; import scala.concurrent.duration.Duration; import javax.servlet.sip.SipServletResponse; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; import static akka.pattern.Patterns.ask; /** * @author [email protected] (Thomas Quintana) * @author [email protected] * @author [email protected] * @author [email protected] */ public abstract class BaseVoiceInterpreter 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 = "[email protected]"; // States for the FSM. // ========================== final State uninitialized; final State acquiringAsrInfo; final State acquiringSynthesizerInfo; final State acquiringCallInfo; final State playingRejectionPrompt; final State pausing; final State caching; final State checkingCache; final State playing; final State synthesizing; final State redirecting; final State faxing; final State processingGatherChildren; final State gathering; final State finishGathering; final State creatingRecording; final State finishRecording; final State creatingSmsSession; final State sendingSms; final State hangingUp; final State sendingEmail; // final State finished; // FSM. FiniteStateMachine fsm = null; // The user specific configuration. Configuration configuration = null; // The block storage cache. private ActorRef cache; String cachePath = null; // The downloader will fetch resources for us using HTTP. ActorRef downloader = null; // The mail man that will deliver e-mail. ActorRef mailerNotify = null; ActorRef mailerService = null; // The call manager. ActorRef callManager = null; // The conference manager. ActorRef conferenceManager = null; // The automatic speech recognition service. private ActorRef asrService; int outstandingAsrRequests; // The fax service. private ActorRef faxService; // The SMS service = null. ActorRef smsService = null; Map<Sid, ActorRef> smsSessions = null; // The storage engine. DaoManager storage = null; // The text to speech synthesizer service. private ActorRef synthesizer; // The languages supported by the automatic speech recognition service. AsrInfo asrInfo = null; // The languages supported by the text to speech synthesizer service. SpeechSynthesizerInfo synthesizerInfo = null; // The call being handled by this interpreter. ActorRef call = null; // The information for this call. CallInfo callInfo = null; // The call state. CallStateChanged.State callState = null; // The last outbound call response. Integer outboundCallResponse = null; // A call detail record. CallDetailRecord callRecord = null; // State for outbound calls. ActorRef outboundCall = null; CallInfo outboundCallInfo = null; // State for the gather verb. List<Tag> gatherChildren = null; List<URI> gatherPrompts = null; // The call recording stuff. Sid recordingSid = null; URI recordingUri = null; URI publicRecordingUri = null; MediaAttributes.MediaType recordingMediaType = null; // Information to reach the application that will be executed // by this interpreter. Sid accountId; Sid phoneId; String version; URI url; String method; URI fallbackUrl; String fallbackMethod; URI referUrl; String referMethod; String referTarget; String transferor; String transferee; URI viStatusCallback; String viStatusCallbackMethod; String emailAddress; // application data. HttpRequestDescriptor request; HttpRequestDescriptor requestCallback; HttpResponseDescriptor response; // The RCML parser. ActorRef parser; Tag verb; Tag gatherVerb; Boolean processingGather = false; Boolean dtmfReceived = false; String finishOnKey; String startInputKey; int numberOfDigits = Short.MAX_VALUE; StringBuffer collectedDigits; String speechResult; //Monitoring service ActorRef monitoring; final Set<Transition> transitions = new HashSet<Transition>(); int recordingDuration = -1; protected RestcommConfiguration restcommConfiguration; //List of extensions for VoiceInterpreter List<RestcommExtensionGeneric> extensions; private UriUtils uriUtils; public BaseVoiceInterpreter() { super(); restcommConfiguration = RestcommConfiguration.getInstance(); final ActorRef source = self(); // 20 States in common uninitialized = new State("uninitialized", null, null); acquiringAsrInfo = new State("acquiring asr info", new AcquiringAsrInfo(source), null); acquiringSynthesizerInfo = new State("acquiring tts info", new AcquiringSpeechSynthesizerInfo(source), null); acquiringCallInfo = new State("acquiring call info", new AcquiringCallInfo(source), null); playingRejectionPrompt = new State("playing rejection prompt", new PlayingRejectionPrompt(source), null); pausing = new State("pausing", new Pausing(source), null); caching = new State("caching", new Caching(source), null); checkingCache = new State("checkingCache", new CheckCache(source), null); playing = new State("playing", new Playing(source), null); synthesizing = new State("synthesizing", new Synthesizing(source), null); redirecting = new State("redirecting", new Redirecting(source), null); faxing = new State("faxing", new Faxing(source), null); gathering = new State("gathering", new Gathering(source), null); processingGatherChildren = new State("processing gather children", new ProcessingGatherChildren(source), null); finishGathering = new State("finish gathering", new FinishGathering(source), null); creatingRecording = new State("creating recording", new CreatingRecording(source), null); finishRecording = new State("finish recording", new FinishRecording(source), null); creatingSmsSession = new State("creating sms session", new CreatingSmsSession(source), null); sendingSms = new State("sending sms", new SendingSms(source), null); hangingUp = new State("hanging up", new HangingUp(source), null); sendingEmail = new State("sending Email", new SendingEmail(source), null); // Initialize the transitions for the FSM. transitions.add(new Transition(uninitialized, acquiringAsrInfo)); transitions.add(new Transition(acquiringAsrInfo, acquiringSynthesizerInfo)); transitions.add(new Transition(acquiringSynthesizerInfo, acquiringCallInfo)); transitions.add(new Transition(pausing, hangingUp)); transitions.add(new Transition(playingRejectionPrompt, hangingUp)); transitions.add(new Transition(faxing, faxing)); transitions.add(new Transition(faxing, caching)); transitions.add(new Transition(faxing, pausing)); transitions.add(new Transition(faxing, redirecting)); transitions.add(new Transition(faxing, synthesizing)); transitions.add(new Transition(faxing, processingGatherChildren)); transitions.add(new Transition(faxing, creatingRecording)); transitions.add(new Transition(faxing, creatingSmsSession)); transitions.add(new Transition(faxing, hangingUp)); transitions.add(new Transition(sendingEmail, sendingEmail)); transitions.add(new Transition(sendingEmail, caching)); transitions.add(new Transition(sendingEmail, pausing)); transitions.add(new Transition(sendingEmail, redirecting)); transitions.add(new Transition(sendingEmail, synthesizing)); transitions.add(new Transition(sendingEmail, processingGatherChildren)); transitions.add(new Transition(sendingEmail, creatingRecording)); transitions.add(new Transition(sendingEmail, creatingSmsSession)); transitions.add(new Transition(sendingEmail, hangingUp)); transitions.add(new Transition(caching, faxing)); transitions.add(new Transition(caching, sendingEmail)); transitions.add(new Transition(caching, playing)); transitions.add(new Transition(caching, caching)); transitions.add(new Transition(caching, pausing)); transitions.add(new Transition(caching, redirecting)); transitions.add(new Transition(caching, synthesizing)); transitions.add(new Transition(caching, processingGatherChildren)); transitions.add(new Transition(caching, creatingRecording)); transitions.add(new Transition(caching, creatingSmsSession)); transitions.add(new Transition(caching, hangingUp)); transitions.add(new Transition(checkingCache, synthesizing)); transitions.add(new Transition(checkingCache, playing)); transitions.add(new Transition(checkingCache, checkingCache)); transitions.add(new Transition(playing, hangingUp)); transitions.add(new Transition(synthesizing, faxing)); transitions.add(new Transition(synthesizing, sendingEmail)); transitions.add(new Transition(synthesizing, pausing)); transitions.add(new Transition(synthesizing, checkingCache)); transitions.add(new Transition(synthesizing, caching)); transitions.add(new Transition(synthesizing, redirecting)); transitions.add(new Transition(synthesizing, processingGatherChildren)); transitions.add(new Transition(synthesizing, creatingRecording)); transitions.add(new Transition(synthesizing, creatingSmsSession)); transitions.add(new Transition(synthesizing, synthesizing)); transitions.add(new Transition(synthesizing, hangingUp)); transitions.add(new Transition(redirecting, faxing)); transitions.add(new Transition(redirecting, sendingEmail)); transitions.add(new Transition(redirecting, pausing)); transitions.add(new Transition(redirecting, checkingCache)); transitions.add(new Transition(redirecting, caching)); transitions.add(new Transition(redirecting, synthesizing)); transitions.add(new Transition(redirecting, redirecting)); transitions.add(new Transition(redirecting, processingGatherChildren)); transitions.add(new Transition(redirecting, creatingRecording)); transitions.add(new Transition(redirecting, creatingSmsSession)); transitions.add(new Transition(redirecting, hangingUp)); transitions.add(new Transition(creatingRecording, finishRecording)); transitions.add(new Transition(creatingRecording, hangingUp)); transitions.add(new Transition(finishRecording, faxing)); transitions.add(new Transition(finishRecording, sendingEmail)); transitions.add(new Transition(finishRecording, pausing)); transitions.add(new Transition(finishRecording, checkingCache)); transitions.add(new Transition(finishRecording, caching)); transitions.add(new Transition(finishRecording, synthesizing)); transitions.add(new Transition(finishRecording, redirecting)); transitions.add(new Transition(finishRecording, processingGatherChildren)); transitions.add(new Transition(finishRecording, creatingRecording)); transitions.add(new Transition(finishRecording, creatingSmsSession)); transitions.add(new Transition(finishRecording, hangingUp)); transitions.add(new Transition(processingGatherChildren, processingGatherChildren)); transitions.add(new Transition(processingGatherChildren, gathering)); transitions.add(new Transition(processingGatherChildren, synthesizing)); transitions.add(new Transition(processingGatherChildren, hangingUp)); transitions.add(new Transition(gathering, finishGathering)); transitions.add(new Transition(gathering, hangingUp)); transitions.add(new Transition(finishGathering, faxing)); transitions.add(new Transition(finishGathering, sendingEmail)); transitions.add(new Transition(finishGathering, pausing)); transitions.add(new Transition(finishGathering, checkingCache)); transitions.add(new Transition(finishGathering, caching)); transitions.add(new Transition(finishGathering, synthesizing)); transitions.add(new Transition(finishGathering, redirecting)); transitions.add(new Transition(finishGathering, processingGatherChildren)); transitions.add(new Transition(finishGathering, creatingRecording)); transitions.add(new Transition(finishGathering, creatingSmsSession)); transitions.add(new Transition(finishGathering, hangingUp)); transitions.add(new Transition(creatingSmsSession, sendingSms)); transitions.add(new Transition(creatingSmsSession, hangingUp)); transitions.add(new Transition(sendingSms, faxing)); transitions.add(new Transition(sendingSms, sendingEmail)); transitions.add(new Transition(sendingSms, pausing)); transitions.add(new Transition(sendingSms, caching)); transitions.add(new Transition(sendingSms, synthesizing)); transitions.add(new Transition(sendingSms, redirecting)); transitions.add(new Transition(sendingSms, processingGatherChildren)); transitions.add(new Transition(sendingSms, creatingRecording)); transitions.add(new Transition(sendingSms, creatingSmsSession)); transitions.add(new Transition(sendingSms, hangingUp)); extensions = ExtensionController.getInstance().getExtensions(ExtensionType.FeatureAccessControl); httpAsycClientHelper = httpAsycClientHelper(); this.uriUtils = RestcommConnectServiceProvider.getInstance().uriUtils(); } @Override public abstract void onReceive(Object arg0) throws Exception; abstract List<NameValuePair> parameters(); public ActorRef getAsrService() { if (asrService == null || (asrService != null && asrService.isTerminated())) { asrService = asr(configuration.subset("speech-recognizer")); } return asrService; } private boolean checkAsrService() { boolean AsrActive=false; Configuration Asrconfiguration=configuration.subset("speech-recognizer"); if (Asrconfiguration.getString("api-key") != null && !Asrconfiguration.getString("api-key").isEmpty()){ AsrActive=true; } return AsrActive; } ActorRef asr(final Configuration configuration) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new ISpeechAsr(configuration); } }); return getContext().actorOf(props); } @SuppressWarnings("unchecked") void asrResponse(final Object message) { final Class<?> klass = message.getClass(); if (AsrResponse.class.equals(klass)) { final AsrResponse<String> response = (AsrResponse<String>) message; Transcription transcription = (Transcription) response.attributes().get("transcription"); if (response.succeeded()) { transcription = transcription.setStatus(Transcription.Status.COMPLETED); if (response.get() != null ) { transcription = transcription.setTranscriptionText(response.get()); } } else { transcription = transcription.setStatus(Transcription.Status.FAILED); } final TranscriptionsDao transcriptions = storage.getTranscriptionsDao(); transcriptions.updateTranscription(transcription); // Notify the callback listener. final Object attribute = response.attributes().get("callback"); if (attribute != null) { final URI callback = (URI) attribute; final List<NameValuePair> parameters = parameters(); request = new HttpRequestDescriptor(callback, "POST", parameters); downloader.tell(request, null); } // Update pending asr responses. outstandingAsrRequests--; // Try to stop the interpreter. postCleanup(); } } public ActorRef getFaxService() { if (faxService == null || (faxService != null && faxService.isTerminated())) { faxService = fax(configuration.subset("fax-service")); } return faxService; } ActorRef fax(final Configuration configuration) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new InterfaxService(configuration); } }); return getContext().actorOf(props); } LinkedList<String> states = new LinkedList<String>(Arrays.asList("queued", "ringing", "in-progress", "completed", "busy", "failed", "no-answer", "canceled")); //Callback using the Akka ask pattern (http://doc.akka.io/docs/akka/2.2.5/java/untyped-actors.html#Ask__Send-And-Receive-Future) will force VoiceInterpter to wait until //Downloader finish with this callback before shutdown everything. Issue https://github.com/Mobicents/RestComm/issues/437 void callback(boolean ask) { if (viStatusCallback != null) { if (states.remove(callState.toString().toLowerCase())) { if (logger.isInfoEnabled()) { logger.info("About to execute viStatusCallback: " + viStatusCallback.toString()); } if (viStatusCallbackMethod == null) { viStatusCallbackMethod = "POST"; } final List<NameValuePair> parameters = parameters(); requestCallback = new HttpRequestDescriptor(viStatusCallback, viStatusCallbackMethod, parameters); if (!ask) { downloader.tell(requestCallback, null); } else if (ask) { final Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS)); Future<Object> future = (Future<Object>) ask(downloader, requestCallback, timeout); DownloaderResponse downloaderResponse = null; try { downloaderResponse = (DownloaderResponse) Await.result(future, Duration.create(10, TimeUnit.SECONDS)); } catch (Exception e) { logger.error("Exception during callback with ask pattern"); } } } else { if (logger.isInfoEnabled()) { logger.info("Status Callback has been already executed for state: ",callState.toString()); } } } else if(logger.isInfoEnabled()){ logger.info("status callback is null"); } } void callback() { callback(false); } public ActorRef getCache() { if (cache == null || (cache != null && cache.isTerminated())) { final Configuration runtime = configuration.subset("runtime-settings"); String path = runtime.getString("cache-path"); if (!path.endsWith("/")) { path = path + "/"; } path = path + accountId.toString(); cachePath = path; String uri = runtime.getString("cache-uri"); if (!uri.endsWith("/")) { uri = uri + "/"; } try { uri = uriUtils.resolve(new URI(uri), accountId).toString(); } catch (URISyntaxException e) { logger.error("URISyntaxException while trying to resolve Cache URI: " + e); } uri = uri + accountId.toString(); cache = cache(path, uri); } return cache; } protected ActorRef cache(final String path, final String uri) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new DiskCacheFactory(configuration).getDiskCache(path, uri); } }); return getContext().actorOf(props); } protected 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); } String e164(final String number) { if (configuration.subset("runtime-settings").getBoolean("normalize-numbers-for-outbound-calls")) { final PhoneNumberUtil numbersUtil = PhoneNumberUtil.getInstance(); try { final PhoneNumber result = numbersUtil.parse(number, "US"); return numbersUtil.format(result, PhoneNumberFormat.E164); } catch (final NumberParseException ignored) { return number; } } else { return number; } } void invalidVerb(final Tag verb) { final ActorRef self = self(); // Get the next verb. final GetNextVerb next = new GetNextVerb(); parser.tell(next, self); } 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); } 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); String base = configuration.subset("runtime-settings").getString("error-dictionary-uri"); try { base = uriUtils.resolve(new URI(base), accountId).toString(); } catch (URISyntaxException e) { logger.error("URISyntaxException when trying to resolve Error-Dictionary URI: "+e); } 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 parser(final String xml) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws IOException { return new Parser(xml, self()); } }); return getContext().actorOf(props); } void postCleanup() { if (smsSessions.isEmpty() && outstandingAsrRequests == 0) { final UntypedActorContext context = getContext(); if (parser != null) getContext().stop(parser); context.stop(self()); } if (downloader != null && !downloader.isTerminated()) { getContext().stop(downloader); } if(httpAsycClientHelper != null && !httpAsycClientHelper.isTerminated()) { getContext().stop(httpAsycClientHelper); } } 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()); } private final class SendingEmail extends AbstractAction { public SendingEmail(final ActorRef source){ super(source); } @Override public void execute( final Object message) throws Exception { final Tag verb = (Tag)message; // Parse "from". String from; Attribute attribute = verb.attribute("from"); if (attribute != null) { from = attribute.value(); }else{ Exception error = new Exception("From attribute was not defined"); source.tell(new EmailResponse(error,error.getMessage()), source); return; } // Parse "to". String to; attribute = verb.attribute("to"); if (attribute != null) { to = attribute.value(); }else{ Exception error = new Exception("To attribute was not defined"); source.tell(new EmailResponse(error,error.getMessage()), source); return; } // Parse "cc". String cc=""; attribute = verb.attribute("cc"); if (attribute != null) { cc = attribute.value(); } // Parse "bcc". String bcc=""; attribute = verb.attribute("bcc"); if (attribute != null) { bcc = attribute.value(); } // Parse "subject" String subject; attribute = verb.attribute("subject"); if (attribute != null) { subject = attribute.value(); }else{ subject="Restcomm Email Service"; } // Send the email. final Mail emailMsg = new Mail(from, to, subject, verb.text(),cc,bcc); if (mailerService == null){ mailerService = mailer(configuration.subset("smtp-service")); } mailerService.tell(new EmailRequest(emailMsg), self()); } } void smsResponse(final Object message) { final Class<?> klass = message.getClass(); final ActorRef self = self(); if (SmsSessionResponse.class.equals(klass)) { final SmsSessionResponse response = (SmsSessionResponse) message; final SmsSessionInfo info = response.info(); SmsMessage record = (SmsMessage) info.attributes().get("record"); final SmsMessagesDao messages = storage.getSmsMessagesDao(); messages.updateSmsMessage(record); // Notify the callback listener. final Object attribute = info.attributes().get("callback"); if (attribute != null) { final URI callback = (URI) attribute; final List<NameValuePair> parameters = parameters(); request = new HttpRequestDescriptor(callback, "POST", parameters); downloader.tell(request, null); } // Destroy the sms session. final ActorRef session = smsSessions.remove(record.getSid()); final DestroySmsSession destroy = new DestroySmsSession(session); smsService.tell(destroy, self); } } public ActorRef getSynthesizer() { if (synthesizer == null || (synthesizer != null && synthesizer.isTerminated())) { String ttsEngine = configuration.subset("speech-synthesizer").getString("[@active]"); Configuration ttsConf = configuration.subset(ttsEngine); synthesizer = tts(ttsConf); } return synthesizer; } private ActorRef httpAsycClientHelper; protected ActorRef httpAsycClientHelper(){ final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new HttpAsycClientHelper(); } }); return getContext().actorOf(props); } private void notifyAsyncWebHook(HttpRequestDescriptor httpReq) { httpAsycClientHelper.tell(httpReq, self()); } ActorRef tts(final Configuration ttsConf) { final String classpath = ttsConf.getString("[@class]"); final Props props = 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(ttsConf); } }); return getContext().actorOf(props); } protected boolean is(State state) { return this.fsm.state().equals(state); } abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } } final class AcquiringAsrInfo extends AbstractAction { public AcquiringAsrInfo(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { getAsrService().tell(new GetAsrInfo(), source); } } final class AcquiringSpeechSynthesizerInfo extends AbstractAction { public AcquiringSpeechSynthesizerInfo(final ActorRef source) { super(source); } @SuppressWarnings({ "unchecked" }) @Override public void execute(final Object message) throws Exception { final AsrResponse<AsrInfo> response = (AsrResponse<AsrInfo>) message; asrInfo = response.get(); getSynthesizer().tell(new GetSpeechSynthesizerInfo(), source); } } final class AcquiringCallInfo extends AbstractAction { public AcquiringCallInfo(final ActorRef source) { super(source); } @SuppressWarnings({ "unchecked" }) @Override public void execute(final Object message) throws Exception { final SpeechSynthesizerResponse<SpeechSynthesizerInfo> response = (SpeechSynthesizerResponse<SpeechSynthesizerInfo>) message; synthesizerInfo = response.get(); // call.tell(new Observe(source), source); // //Enable Monitoring Service for the call // if (monitoring != null) // call.tell(new Observe(monitoring), source); call.tell(new GetCallInfo(), source); } } final class NotFound extends AbstractAction { public NotFound(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { // final Class<?> klass = message.getClass(); 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. call.tell(new org.restcomm.connect.telephony.api.NotFound(), source); } } final class Rejecting extends AbstractAction { public Rejecting(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } String reason = "rejected"; Attribute attribute = verb.attribute("reason"); if (attribute != null) { reason = attribute.value(); if (reason != null && !reason.isEmpty()) { if ("rejected".equalsIgnoreCase(reason)) { reason = "rejected"; } else if ("busy".equalsIgnoreCase(reason)) { reason = "busy"; } else { reason = "rejected"; } } else { reason = "rejected"; } } // Reject the call. call.tell(new Reject(reason), source); } } final class PlayingRejectionPrompt extends AbstractAction { public PlayingRejectionPrompt(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { String path = configuration.subset("runtime-settings").getString("prompts-uri"); if (!path.endsWith("/")) { path += "/"; } path += "reject.wav"; URI uri = null; try { uri = uriUtils.resolve(new URI(path), accountId); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 12400, exception.getMessage()); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } final Play play = new Play(uri, 1); call.tell(play, source); } } final class Faxing extends AbstractAction { public Faxing(final ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { final DiskCacheResponse response = (DiskCacheResponse) message; // Parse "from". String from = callInfo.to(); Attribute attribute = verb.attribute("from"); if (attribute != null) { from = attribute.value(); if (from != null && from.isEmpty()) { from = e164(from); if (from == null) { from = verb.attribute("from").value(); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } } // Parse "to". String to = callInfo.from(); attribute = verb.attribute("to"); if (attribute != null) { to = attribute.value(); if (to != null && !to.isEmpty()) { to = e164(to); if (to == null) { to = verb.attribute("to").value(); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } } // Send the fax. final String uri = response.get().toString(); final int offset = uri.lastIndexOf("/"); final String path = cachePath + "/" + uri.substring(offset + 1, uri.length()); final FaxRequest fax = new FaxRequest(to, new File(path)); getFaxService().tell(fax, source); } } final class Pausing extends AbstractAction { public Pausing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } int length = 1; final Attribute attribute = verb.attribute("length"); if (attribute != null) { final String number = attribute.value(); if (number != null && !number.isEmpty()) { try { length = Integer.parseInt(number); } catch (final NumberFormatException exception) { final Notification notification = notification(WARNING_NOTIFICATION, 13910, "Invalid length value."); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); } } } final UntypedActorContext context = getContext(); context.setReceiveTimeout(Duration.create(length, TimeUnit.SECONDS)); } } final class CheckCache extends AbstractAction { public CheckCache(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } // else { // logger.info("Can't check cache, message not verb. Moving to the next verb"); // // final GetNextVerb next = GetNextVerb.instance(); // // parser.tell(next, source); // return; // } String hash = hash(verb); DiskCacheRequest request = new DiskCacheRequest(hash); if (logger.isErrorEnabled()) { logger.info("Checking cache for hash: " + hash); } getCache().tell(request, source); } } final class Caching extends AbstractAction { public Caching(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (SpeechSynthesizerResponse.class.equals(klass)) { final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message; final DiskCacheRequest request = new DiskCacheRequest(response.get()); getCache().tell(request, source); } else if (Tag.class.equals(klass)) { if (Tag.class.equals(klass)) { verb = (Tag) message; } // Parse the URL. final String text = verb.text(); if (text != null && !text.isEmpty()) { // Try to cache the media. URI target = null; try { target = URI.create(text); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, text + " is an invalid URI."); final NotificationsDao notifications = storage.getNotificationsDao(); 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); final DiskCacheRequest request = new DiskCacheRequest(uri); getCache().tell(request, source); } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } } } final class Playing extends AbstractAction { public Playing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (DiskCacheResponse.class.equals(klass)) { // Parse the loop attribute. int loop = 1; final Attribute attribute = verb.attribute("loop"); if (attribute != null) { final String number = attribute.value(); if (number != null && !number.isEmpty()) { try { loop = Integer.parseInt(number); } catch (final NumberFormatException ignored) { final NotificationsDao notifications = storage.getNotificationsDao(); Notification notification = null; if (Verbs.say.equals(verb.name())) { notification = notification(WARNING_NOTIFICATION, 13510, loop + " is an invalid loop value."); notifications.addNotification(notification); } else if (Verbs.play.equals(verb.name())) { notification = notification(WARNING_NOTIFICATION, 13410, loop + " is an invalid loop value."); notifications.addNotification(notification); } } } } final DiskCacheResponse response = (DiskCacheResponse) message; final Play play = new Play(response.get(), loop); call.tell(play, source); } } } String hash(Object message) { Map<String, String> details = getSynthesizeDetails(message); if (details == null) { if (logger.isInfoEnabled()) { logger.info("Cannot generate hash, details are null"); } return null; } String voice = details.get("voice"); String language = details.get("language"); String text = details.get("text"); return HashGenerator.hashMessage(voice, language, text); } Map<String, String> getSynthesizeDetails(final Object message) { final Class<?> klass = message.getClass(); Map<String, String> details = new HashMap<String, String>(); if (Tag.class.equals(klass)) { verb = (Tag) message; } else { return null; } if (!Verbs.say.equals(verb.name())) return null; // Parse the voice attribute. String voice = "man"; Attribute attribute = verb.attribute("voice"); if (attribute != null) { voice = attribute.value(); if (voice != null && !voice.isEmpty()) { if (!"man".equals(voice) && !"woman".equals(voice)) { final Notification notification = notification(WARNING_NOTIFICATION, 13511, voice + " is an invalid voice value."); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); voice = "man"; } } else { voice = "man"; } } // Parse the language attribute. String language = "en"; attribute = verb.attribute(GatherAttributes.ATTRIBUTE_LANGUAGE); if (attribute != null) { language = attribute.value(); if (language != null && !language.isEmpty()) { if (!synthesizerInfo.languages().contains(language)) { language = "en"; } } else { language = "en"; } } // Synthesize. String text = verb.text(); details.put("voice", voice); details.put("language", language); details.put("text", text); return details; } final class Synthesizing extends AbstractAction { public Synthesizing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } Map<String, String> details = getSynthesizeDetails(verb); if (details != null && !details.isEmpty() && details.get("text") != null) { String voice = details.get("voice"); String language = details.get("language"); String text = details.get("text"); final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(voice, language, text); getSynthesizer().tell(synthesize, source); } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } } final class HangingUp extends AbstractAction { public HangingUp(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } // Hang up the call. if (ParserFailed.class.equals(klass)) { call.tell(new Hangup("Problem_to_parse_downloaded_RCML"), source); } else if (CallManagerResponse.class.equals(klass)) { String reason = ((CallManagerResponse)message).cause().getMessage().replaceAll("\\s","_"); call.tell(new Hangup(reason), source); } else if (message instanceof SmsServiceResponse) { //Blocked SMS Session request call.tell(new Hangup(((SmsServiceResponse)message).cause().getMessage()), self()); } else if (Tag.class.equals(klass) && Verbs.hangup.equals(verb.name())) { Integer sipResponse = outboundCallResponse != null ? outboundCallResponse : SipServletResponse.SC_REQUEST_TERMINATED; call.tell(new Hangup(sipResponse), source); } else { call.tell(new Hangup(outboundCallResponse), source); } } } final class Redirecting extends AbstractAction { public Redirecting(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } final NotificationsDao notifications = storage.getNotificationsDao(); String method = "POST"; Attribute attribute = verb.attribute(GatherAttributes.ATTRIBUTE_METHOD); if (attribute != null) { method = attribute.value(); if (method != null && !method.isEmpty()) { if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) { final Notification notification = notification(WARNING_NOTIFICATION, 13710, method + " is not a valid HTTP method for <Redirect>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } final String text = verb.text(); if (text != null && !text.isEmpty()) { // Try to redirect. URI target = null; try { target = URI.create(text); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, text + " 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); final List<NameValuePair> parameters = parameters(); request = new HttpRequestDescriptor(uri, method, parameters); downloader.tell(request, source); } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } } abstract class AbstractGatherAction extends AbstractAction { public AbstractGatherAction(final ActorRef source) { super(source); } protected String finishOnKey(final Tag container) { String finishOnKey = "#"; Attribute attribute = container.attribute(GatherAttributes.ATTRIBUTE_FINISH_ON_KEY); if (attribute != null) { finishOnKey = attribute.value(); if (finishOnKey != null && !finishOnKey.isEmpty()) { if (!PATTERN.matcher(finishOnKey).matches()) { final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 13310, finishOnKey + " is not a valid finishOnKey value"); notifications.addNotification(notification); finishOnKey = "#"; } } else { finishOnKey = "#"; } } return finishOnKey; } } final class ProcessingGatherChildren extends AbstractGatherAction { public ProcessingGatherChildren(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { processingGather = true; final Class<?> klass = message.getClass(); final NotificationsDao notifications = storage.getNotificationsDao(); if (SpeechSynthesizerResponse.class.equals(klass)) { final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message; final DiskCacheRequest request = new DiskCacheRequest(response.get()); getCache().tell(request, source); } else { if (Tag.class.equals(klass)) { verb = (Tag) message; gatherPrompts = new ArrayList<URI>(); gatherChildren = new ArrayList<Tag>(verb.children()); } else if (DiskCacheResponse.class.equals(klass)) { if (gatherPrompts == null) gatherPrompts = new ArrayList<URI>(); if (gatherChildren == null) gatherChildren = new ArrayList<Tag>(verb.children()); final DiskCacheResponse response = (DiskCacheResponse) message; final URI uri = response.get(); Tag child = null; if (!gatherChildren.isEmpty()) child = gatherChildren.remove(0); // Parse the loop attribute. int loop = 1; Attribute attribute = null; if (child != null) attribute = child.attribute("loop"); if (attribute != null) { final String number = attribute.value(); if (number != null && !number.isEmpty()) { try { loop = Integer.parseInt(number); } catch (final NumberFormatException ignored) { Notification notification = null; if (Verbs.say.equals(child.name())) { notification = notification(WARNING_NOTIFICATION, 13322, loop + " is an invalid loop value."); notifications.addNotification(notification); } } } } for (int counter = 0; counter < loop; counter++) { gatherPrompts.add(uri); } } for (int index = 0; index < gatherChildren.size(); index++) { final Tag child = gatherChildren.get(index); if (Verbs.play.equals(child.name())) { final String text = child.text(); if (text != null && !text.isEmpty()) { URI target = null; try { target = URI.create(text); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 13325, text + " 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); // Cache the prompt. final DiskCacheRequest request = new DiskCacheRequest(uri); getCache().tell(request, source); break; } } else if (Verbs.say.equals(child.name())) { // Parse the voice attribute. String voice = "man"; Attribute attribute = child.attribute("voice"); if (attribute != null) { voice = attribute.value(); if (voice != null && !voice.isEmpty()) { if (!"man".equals(voice) && !"woman".equals(voice)) { final Notification notification = notification(WARNING_NOTIFICATION, 13321, voice + " is an invalid voice value."); notifications.addNotification(notification); voice = "man"; } } else { voice = "man"; } } // Parse the language attribute. String language = "en"; attribute = child.attribute("language"); if (attribute != null) { language = attribute.value(); if (language != null && !language.isEmpty()) { if (!synthesizerInfo.languages().contains(language)) { language = "en"; } } else { language = "en"; } } String text = child.text(); if (text != null && !text.isEmpty()) { // final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(voice, language, text); // synthesizer.tell(synthesize, source); // break; String hash = hash(child); DiskCacheRequest request = new DiskCacheRequest(hash); getCache().tell(request, source); break; } } else if (Verbs.pause.equals(child.name())) { int length = 1; final Attribute attribute = child.attribute("length"); if (attribute != null) { final String number = attribute.value(); if (number != null && !number.isEmpty()) { try { length = Integer.parseInt(number); } catch (final NumberFormatException ignored) { } } } String path = configuration.subset("runtime-settings").getString("prompts-uri"); if (!path.endsWith("/")) { path += "/"; } path += "one-second-silence.wav"; final URI uri = uriUtils.resolve(new URI(path)); for (int counter = 0; counter < length; counter++) { gatherPrompts.add(uri); } } } // Make sure we don't leave any pauses at the beginning // since we can't concurrently modify the list. if (!gatherChildren.isEmpty()) { Tag child = null; do { child = gatherChildren.get(0); if (child != null) { if (Verbs.pause.equals(child.name())) { gatherChildren.remove(0); } } } while (Verbs.pause.equals(child.name())); } // Start gathering. if (gatherChildren.isEmpty()) { if (gatherVerb != null) verb = gatherVerb; final StartGathering start = StartGathering.instance(); source.tell(start, source); processingGather = false; } } } } final class Gathering extends AbstractGatherAction { public Gathering(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { // check mandatory attribute partialResultCallback Attribute partialResultCallbackAttr = verb.attribute(GatherAttributes.ATTRIBUTE_PARTIAL_RESULT_CALLBACK); final NotificationsDao notifications = storage.getNotificationsDao(); // parse attribute "input" Attribute typeAttr = verb.attribute(GatherAttributes.ATTRIBUTE_INPUT); Collect.Type inputType = null; if (typeAttr == null) { inputType = Collect.Type.DTMF; } else { inputType = Collect.Type.parseOrDefault(typeAttr.value(), Collect.Type.DTMF); } if (inputType.equals(Collect.Type.SPEECH) || inputType.equals(Collect.Type.DTMF_SPEECH)) { ExtensionController ec = ExtensionController.getInstance(); final IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.ASR, accountId); ExtensionResponse er = ec.executePreInboundAction(far, extensions); if (!er.isAllowed()) { if (logger.isDebugEnabled()) { final String errMsg = "ASR feature is not allowed"; logger.debug(errMsg); } String errMsg = "ASR feature is not allowed"; notification(WARNING_NOTIFICATION, 11001, errMsg); call.tell(new Hangup(errMsg), source); return; } ec.executePostInboundAction(far, extensions); } // parse attribute "language" Attribute langAttr = verb.attribute(GatherAttributes.ATTRIBUTE_LANGUAGE); String defaultLang = restcommConfiguration.getMgAsr().getDefaultLanguage(); String lang = parseAttrLanguage(langAttr, defaultLang); // parse attribute "hints" String hints = null; Attribute hintsAttr = verb.attribute(GatherAttributes.ATTRIBUTE_HINTS); if (hintsAttr != null && !StringUtils.isEmpty(hintsAttr.value())) { hints = hintsAttr.value(); } else if (inputType != Collect.Type.DTMF) { logger.warning("'{}' attribute is null or empty", GatherAttributes.ATTRIBUTE_HINTS); } // Parse finish on key. finishOnKey = finishOnKey(verb); // Parse start Input key startInputKey = "*0123456789"; // Default value. Attribute attribute = verb.attribute(GatherAttributes.ATTRIBUTE_START_INPUT_KEY); if (attribute != null) { final String value = attribute.value(); if (!StringUtils.isEmpty(value)) { if (!PATTERN.matcher(value).matches()) { final Notification notification = notification(WARNING_NOTIFICATION, 13315, value + " is not a valid startInputKey value"); notifications.addNotification(notification); } else { startInputKey = value; } } } // Parse the number of digits. attribute = verb.attribute(GatherAttributes.ATTRIBUTE_NUM_DIGITS); if (attribute != null) { final String value = attribute.value(); if (!StringUtils.isEmpty(value)) { try { numberOfDigits = Integer.parseInt(value); } catch (final NumberFormatException exception) { final Notification notification = notification(WARNING_NOTIFICATION, 13314, numberOfDigits + " is not a valid numDigits value"); notifications.addNotification(notification); } } } // Parse timeout. int timeout = restcommConfiguration.getMgAsr().getDefaultGatheringTimeout(); attribute = verb.attribute(GatherAttributes.ATTRIBUTE_TIME_OUT); if (attribute != null) { final String value = attribute.value(); if (!StringUtils.isEmpty(value)) { try { timeout = Integer.parseInt(value); } catch (final NumberFormatException exception) { final Notification notification = notification(WARNING_NOTIFICATION, 13313, timeout + " is not a valid timeout value"); notifications.addNotification(notification); } } } // Start gathering. final Collect collect = new Collect(restcommConfiguration.getMgAsr().getDefaultDriver(), inputType, gatherPrompts, null, timeout, finishOnKey, startInputKey, numberOfDigits, lang, hints, partialResultCallbackAttr != null && !StringUtils.isEmpty(partialResultCallbackAttr.value())); call.tell(collect, source); // Some clean up. gatherChildren = null; gatherPrompts = null; dtmfReceived = false; collectedDigits = new StringBuffer(""); } private String parseAttrLanguage(Attribute langAttr, String defaultLang) { if (langAttr != null && !StringUtils.isEmpty(langAttr.value())) { return restcommConfiguration.getMgAsr().getLanguages().contains(langAttr.value()) ? langAttr.value() : defaultLang; } else { logger.warning("Illegal or unsupported attribute value: '{}'. Will be use default value '{}'", langAttr, defaultLang); return defaultLang; } } } private abstract class CallbackGatherAction extends AbstractGatherAction { public CallbackGatherAction(ActorRef source) { super(source); } protected void execHttpRequest(final NotificationsDao notifications, final Attribute callbackAttr, final Attribute methodAttr, final List<NameValuePair> parameters) { if (callbackAttr == null) { final Notification notification = notification(ERROR_NOTIFICATION, 11101, "Callback attribute is null"); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); logger.error("CallbackAttribute is null, CallbackGatherAction failed"); } String action = callbackAttr.value(); if (StringUtils.isEmpty(action)) { final Notification notification = notification(ERROR_NOTIFICATION, 11101, "Callback attribute value is null or empty"); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); logger.error("Action url is null or empty"); } URI target; try { target = URI.create(action); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, action + " is an invalid URI."); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } String method = "POST"; if (methodAttr != null) { method = methodAttr.value(); if (!StringUtils.isEmpty(method)) { 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 URI base = request.getUri(); final URI uri = uriUtils.resolveWithBase(base, target); request = new HttpRequestDescriptor(uri, method, parameters); notifyAsyncWebHook(request); } } final class FinishGathering extends CallbackGatherAction { public FinishGathering(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final NotificationsDao notifications = storage.getNotificationsDao(); String digits = collectedDigits.toString(); collectedDigits = new StringBuffer(); if (logger.isInfoEnabled()) { logger.info("Digits collected: " + digits); } if (digits.equals(finishOnKey)) { digits = ""; } if (logger.isDebugEnabled()) { logger.debug("Digits collected : " + digits); } // https://bitbucket.org/telestax/telscale-restcomm/issue/150/verb-is-looping-by-default-and-never // If the 'timeout' is reached before the caller enters any digits, or if the caller enters the 'finishOnKey' value // before entering any other digits, Twilio will not make a request to the 'action' URL but instead continue // processing // the current TwiML document with the verb immediately following the <Gather> Attribute action = verb.attribute(GatherAttributes.ATTRIBUTE_ACTION); if (action != null && (!digits.trim().isEmpty() || !StringUtils.isEmpty(speechResult))) { // Redirect to the action url. if (digits.endsWith(finishOnKey)) { final int finishOnKeyIndex = digits.lastIndexOf(finishOnKey); digits = digits.substring(0, finishOnKeyIndex); } final List<NameValuePair> parameters = parameters(); parameters.add(new BasicNameValuePair("Digits", digits)); parameters.add(new BasicNameValuePair("SpeechResult", speechResult)); execHttpRequest(notifications, action, verb.attribute(GatherAttributes.ATTRIBUTE_METHOD), parameters); speechResult = null; return; } if (logger.isInfoEnabled()) { logger.info("Attribute, Action or Digits is null, FinishGathering failed, moving to the next available verb"); } speechResult = null; // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } final class PartialGathering extends CallbackGatherAction { public PartialGathering(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (verb.attribute(GatherAttributes.ATTRIBUTE_PARTIAL_RESULT_CALLBACK) != null && !StringUtils.isEmpty(verb.attribute(GatherAttributes.ATTRIBUTE_PARTIAL_RESULT_CALLBACK).value())) { final MediaGroupResponse<CollectedResult> asrResponse = (MediaGroupResponse<CollectedResult>) message; final List<NameValuePair> parameters = parameters(); parameters.add(new BasicNameValuePair("UnstableSpeechResult", asrResponse.get().getResult())); final NotificationsDao notifications = storage.getNotificationsDao(); execHttpRequest(notifications, verb.attribute(GatherAttributes.ATTRIBUTE_PARTIAL_RESULT_CALLBACK), verb.attribute(GatherAttributes.ATTRIBUTE_PARTIAL_RESULT_CALLBACK_METHOD), parameters); } } } final class CreatingRecording extends AbstractAction { public CreatingRecording(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } final NotificationsDao notifications = storage.getNotificationsDao(); String finishOnKey = "1234567890*#"; Attribute attribute = verb.attribute(GatherAttributes.ATTRIBUTE_FINISH_ON_KEY); if (attribute != null) { finishOnKey = attribute.value(); if (finishOnKey != null && !finishOnKey.isEmpty()) { //https://github.com/RestComm/Restcomm-Connect/issues/1886 if (!finishOnKey.equals("-1")) { if (!PATTERN.matcher(finishOnKey).matches()) { final Notification notification = notification(WARNING_NOTIFICATION, 13613, finishOnKey + " is not a valid finishOnKey value"); notifications.addNotification(notification); //https://github.com/RestComm/Restcomm-Connect/issues/1925 finishOnKey = "#"; } } } else { //https://github.com/RestComm/Restcomm-Connect/issues/1925 finishOnKey = "#"; } } boolean playBeep = true; attribute = verb.attribute("playBeep"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { playBeep = Boolean.parseBoolean(value); } } int maxLength = 3600; attribute = verb.attribute("maxLength"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { maxLength = Integer.parseInt(value); } catch (final NumberFormatException exception) { final Notification notification = notification(WARNING_NOTIFICATION, 13612, maxLength + " is not a valid maxLength value"); notifications.addNotification(notification); } } } int timeout = 5; attribute = verb.attribute(GatherAttributes.ATTRIBUTE_TIME_OUT); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { timeout = Integer.parseInt(value); } catch (final NumberFormatException exception) { final Notification notification = notification(WARNING_NOTIFICATION, 13612, timeout + " is not a valid timeout value"); notifications.addNotification(notification); } } } recordingMediaType = MediaAttributes.MediaType.AUDIO_ONLY; attribute = verb.attribute("media"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { recordingMediaType = MediaAttributes.MediaType.getValueOf(value); } catch (final IllegalArgumentException exception) { final Notification notification = notification(WARNING_NOTIFICATION, 13612, value + " is not a valid media value"); notifications.addNotification(notification); } } } // Start recording. recordingSid = Sid.generate(Sid.Type.RECORDING); String path = configuration.subset("runtime-settings").getString("recordings-path"); String httpRecordingUri = configuration.subset("runtime-settings").getString("recordings-uri"); if (!path.endsWith("/")) { path += "/"; } if (!httpRecordingUri.endsWith("/")) { httpRecordingUri += "/"; } String fileExtension = recordingMediaType.equals(MediaAttributes.MediaType.AUDIO_ONLY) ? ".wav" : ".mp4"; path += recordingSid.toString() + fileExtension; httpRecordingUri += recordingSid.toString() + fileExtension; recordingUri = URI.create(path); try { publicRecordingUri = uriUtils.resolve(new URI(httpRecordingUri)); } catch (URISyntaxException e) { logger.error("URISyntaxException when trying to resolve Recording URI: "+e); } Record record = null; if (playBeep) { final List<URI> prompts = new ArrayList<URI>(1); path = configuration.subset("runtime-settings").getString("prompts-uri"); if (!path.endsWith("/")) { path += "/"; } path += "beep.wav"; try { prompts.add(uriUtils.resolve(new URI(path))); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 12400, exception.getMessage()); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } record = new Record(recordingUri, prompts, timeout, maxLength, finishOnKey, recordingMediaType); } else { record = new Record(recordingUri, timeout, maxLength, finishOnKey, recordingMediaType); } call.tell(record, source); } } final class FinishRecording extends AbstractAction { public FinishRecording(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { if (logger.isInfoEnabled()) { logger.info("##### At FinishRecording, message: " + message.getClass()); } boolean amazonS3Enabled = configuration.subset("amazon-s3").getBoolean("enabled"); final Class<?> klass = message.getClass(); if (CallStateChanged.class.equals(klass)) { final CallStateChanged event = (CallStateChanged) message; // Update the interpreter state. callState = event.state(); // Update the storage. callRecord = callRecord.setStatus(callState.toString()); final DateTime end = DateTime.now(); callRecord = callRecord.setEndTime(end); recordingDuration = (int) (end.getMillis() - callRecord.getStartTime().getMillis()) / 1000; callRecord = callRecord.setDuration(recordingDuration); final CallDetailRecordsDao records = storage.getCallDetailRecordsDao(); records.updateCallDetailRecord(callRecord); // Update the application. // callback(); } Recording recording = null; final NotificationsDao notifications = storage.getNotificationsDao(); // Create a record of the recording. Double duration = WavUtils.getAudioDuration(recordingUri); if (duration.equals(0.0)) { if (logger.isInfoEnabled()) { String msg = String.format("Recording file %s, duration is 0 and will return",recordingUri); logger.info(msg); } } else { if (logger.isDebugEnabled()) { logger.debug("Recording File exists, length: " + (new File(recordingUri).length())); logger.debug("Recording duration: " + duration); } final Recording.Builder builder = Recording.builder(); builder.setSid(recordingSid); builder.setAccountSid(accountId); builder.setCallSid(callInfo.sid()); builder.setDuration(duration); builder.setApiVersion(version); StringBuilder buffer = new StringBuilder(); buffer.append("/").append(version).append("/Accounts/").append(accountId.toString()); buffer.append("/Recordings/").append(recordingSid.toString()); builder.setUri(URI.create(buffer.toString())); builder.setFileUri(RestcommConnectServiceProvider.getInstance().recordingService() .prepareFileUrl(version, 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); } recording = builder.build(); final RecordingsDao recordings = storage.getRecordingsDao(); recordings.addRecording(recording); getContext().system().eventStream().publish(recording); Attribute attribute = null; if (checkAsrService()) { // ASR service is enabled. Start transcription. URI transcribeCallback = null; attribute = verb.attribute("transcribeCallback"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { try { transcribeCallback = URI.create(value); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, transcribeCallback + " is an invalid URI."); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } } boolean transcribe = false; if (transcribeCallback != null) { transcribe = true; } else { attribute = verb.attribute("transcribe"); if (attribute != null) { final String value = attribute.value(); if (value != null && !value.isEmpty()) { transcribe = Boolean.parseBoolean(value); } } } if (transcribe && checkAsrService()) { final Sid sid = Sid.generate(Sid.Type.TRANSCRIPTION); final Transcription.Builder otherBuilder = Transcription.builder(); otherBuilder.setSid(sid); otherBuilder.setAccountSid(accountId); otherBuilder.setStatus(Transcription.Status.IN_PROGRESS); otherBuilder.setRecordingSid(recordingSid); otherBuilder.setTranscriptionText("Transcription Text not available"); otherBuilder.setDuration(duration); otherBuilder.setPrice(new BigDecimal("0.00")); buffer = new StringBuilder(); buffer.append("/").append(version).append("/Accounts/").append(accountId.toString()); buffer.append("/Transcriptions/").append(sid.toString()); final URI uri = URI.create(buffer.toString()); otherBuilder.setUri(uri); final Transcription transcription = otherBuilder.build(); final TranscriptionsDao transcriptions = storage.getTranscriptionsDao(); transcriptions.addTranscription(transcription); try { final Map<String, Object> attributes = new HashMap<String, Object>(); attributes.put("callback", transcribeCallback); attributes.put("transcription", transcription); getAsrService().tell(new AsrRequest(new File(recordingUri), "en", attributes), source); outstandingAsrRequests++; } catch (final Exception exception) { logger.error(exception.getMessage(), exception); } } } else { if (logger.isDebugEnabled()) { logger.debug("AsrService is not enabled"); } } } // If action is present redirect to the action URI. String action = null; Attribute attribute = verb.attribute(GatherAttributes.ATTRIBUTE_ACTION); if (attribute != null) { action = attribute.value(); if (action != null && !action.isEmpty()) { URI target = null; try { target = URI.create(action); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, action + " 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 = verb.attribute(GatherAttributes.ATTRIBUTE_METHOD); if (attribute != null) { method = attribute.value(); if (method != null && !method.isEmpty()) { if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) { final Notification notification = notification(WARNING_NOTIFICATION, 13610, method + " is not a valid HTTP method for <Record>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } final List<NameValuePair> parameters = parameters(); if (recording != null) { if (amazonS3Enabled) { //If Amazon S3 is enabled the Recordings DAO uploaded the wav file to S3 and changed the URI parameters.add(new BasicNameValuePair("RecordingUrl", recording.getFileUri().toURL().toString())); parameters.add(new BasicNameValuePair("PublicRecordingUrl", recording.getFileUri().toURL().toString())); } else { // Redirect to the action url. String httpRecordingUri = configuration.subset("runtime-settings").getString("recordings-uri"); if (!httpRecordingUri.endsWith("/")) { httpRecordingUri += "/"; } String fileExtension = recordingMediaType.equals(MediaAttributes.MediaType.AUDIO_ONLY) ? ".wav" : ".mp4"; httpRecordingUri += recordingSid.toString() + fileExtension; URI publicRecordingUri = uriUtils.resolve(new URI(httpRecordingUri)); parameters.add(new BasicNameValuePair("RecordingUrl", recordingUri.toString())); parameters.add(new BasicNameValuePair("PublicRecordingUrl", publicRecordingUri.toString())); } } parameters.add(new BasicNameValuePair("RecordingDuration", Double.toString(duration))); if (MediaGroupResponse.class.equals(klass)) { final MediaGroupResponse response = (MediaGroupResponse) message; Object data = response.get(); if (data instanceof CollectedResult) { parameters.add(new BasicNameValuePair("Digits", ((CollectedResult)data).getResult())); } else if(data instanceof String) { parameters.add(new BasicNameValuePair("Digits", (String)data)); } else { logger.error("unidentified response recived in MediaGroupResponse: "+response); } request = new HttpRequestDescriptor(uri, method, parameters); if (logger.isInfoEnabled()){ logger.info("About to execute Record action to: "+uri); } downloader.tell(request, self()); } else if (CallStateChanged.class.equals(klass)) { parameters.add(new BasicNameValuePair("Digits", "hangup")); request = new HttpRequestDescriptor(uri, method, parameters); if (logger.isInfoEnabled()) { logger.info("About to execute Record action to: "+uri); } downloader.tell(request, self()); } // final StopInterpreter stop = new StopInterpreter(); // source.tell(stop, source); } } else { //Action is null here final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } // A little clean up. recordingSid = null; recordingUri = null; recordingMediaType = null; } } final class CreatingSmsSession extends AbstractAction { public CreatingSmsSession(final ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Save <Sms> verb. final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } // Create a new sms session to handle the <Sms> verb. smsService.tell(new CreateSmsSession(callInfo.from(), callInfo.to(), accountId.toString(), false), source); } } final class SendingSms extends AbstractAction { public SendingSms(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { final SmsServiceResponse<ActorRef> response = (SmsServiceResponse<ActorRef>) message; final ActorRef session = response.get(); final NotificationsDao notifications = storage.getNotificationsDao(); // Parse "from". String from = callInfo.to(); Attribute attribute = verb.attribute("from"); if (attribute != null) { from = attribute.value(); if (from != null && !from.isEmpty()) { from = e164(from); if (from == null) { from = verb.attribute("from").value(); final Notification notification = notification(ERROR_NOTIFICATION, 14102, from + " is an invalid 'from' phone number."); notifications.addNotification(notification); sendMail(notification); smsService.tell(new DestroySmsSession(session), source); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } } // Parse "to". String to = callInfo.from(); attribute = verb.attribute("to"); if (attribute != null) { to = attribute.value(); if (to != null && !to.isEmpty()) { to = e164(to); if (to == null) { to = verb.attribute("to").value(); final Notification notification = notification(ERROR_NOTIFICATION, 14101, to + " is an invalid 'to' phone number."); notifications.addNotification(notification); sendMail(notification); smsService.tell(new DestroySmsSession(session), source); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } } // Parse <Sms> text. String body = verb.text(); if (body == null || body.isEmpty()) { final Notification notification = notification(ERROR_NOTIFICATION, 14103, body + " is an invalid SMS body."); notifications.addNotification(notification); sendMail(notification); smsService.tell(new DestroySmsSession(session), source); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } else { // Start observing events from the sms session. session.tell(new Observe(source), source); // Create an SMS detail record. final Sid sid = Sid.generate(Sid.Type.SMS_MESSAGE); final SmsMessage.Builder builder = SmsMessage.builder(); builder.setSid(sid); builder.setAccountSid(accountId); builder.setApiVersion(version); builder.setRecipient(to); builder.setSender(from); builder.setBody(body); builder.setDirection(Direction.OUTBOUND_REPLY); builder.setStatus(Status.SENDING); builder.setPrice(new BigDecimal("0.00")); final StringBuilder buffer = new StringBuilder(); buffer.append("/").append(version).append("/Accounts/"); buffer.append(accountId.toString()).append("/SMS/Messages/"); buffer.append(sid.toString()); final URI uri = URI.create(buffer.toString()); builder.setUri(uri); SmsVerb.populateAttributes(verb, builder); final SmsMessage record = builder.build(); final SmsMessagesDao messages = storage.getSmsMessagesDao(); messages.addSmsMessage(record); // Store the sms record in the sms session. session.tell(new SmsSessionAttribute("record", record), source); // Send the SMS. final SmsSessionRequest sms = new SmsSessionRequest(from, to, body, null); session.tell(sms, source); smsSessions.put(sid, session); } // Parses "action". attribute = verb.attribute("action"); if (attribute != null) { String action = attribute.value(); if (action != null && !action.isEmpty()) { URI target = null; try { target = URI.create(action); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, action + " 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 = verb.attribute("method"); 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 <Sms>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } // Redirect to the action url. final List<NameValuePair> parameters = parameters(); final String status = Status.SENDING.toString(); parameters.add(new BasicNameValuePair("SmsStatus", status)); request = new HttpRequestDescriptor(uri, method, parameters); downloader.tell(request, source); return; } } // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } }
110,193
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmsInterpreter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/SmsInterpreter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; 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 com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import org.apache.commons.configuration.Configuration; import org.apache.http.Header; 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.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.dao.DaoManager; import org.restcomm.connect.dao.NotificationsDao; import org.restcomm.connect.dao.SmsMessagesDao; import org.restcomm.connect.dao.entities.Notification; import org.restcomm.connect.dao.entities.SmsMessage; import org.restcomm.connect.dao.entities.SmsMessage.Direction; import org.restcomm.connect.dao.entities.SmsMessage.Status; import org.restcomm.connect.email.EmailService; import org.restcomm.connect.email.api.EmailRequest; import org.restcomm.connect.email.api.EmailResponse; 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.rcml.Attribute; 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.interpreter.rcml.Verbs; import org.restcomm.connect.sms.api.CreateSmsSession; import org.restcomm.connect.sms.api.DestroySmsSession; import org.restcomm.connect.sms.api.GetLastSmsRequest; import org.restcomm.connect.sms.api.SmsServiceResponse; import org.restcomm.connect.sms.api.SmsSessionAttribute; import org.restcomm.connect.sms.api.SmsSessionInfo; import org.restcomm.connect.sms.api.SmsSessionRequest; import org.restcomm.connect.sms.api.SmsSessionResponse; import org.restcomm.connect.telephony.api.FeatureAccessRequest; 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.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.restcomm.connect.interpreter.rcml.SmsVerb; /** * @author [email protected] (Thomas Quintana) */ public final class SmsInterpreter extends RestcommUntypedActor { private static final int ERROR_NOTIFICATION = 0; private static final int WARNING_NOTIFICATION = 1; static String EMAIL_SENDER; // Logger private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // States for the FSM. private final State uninitialized; private final State acquiringLastSmsRequest; private final State downloadingRcml; private final State downloadingFallbackRcml; private final State ready; private final State redirecting; private final State creatingSmsSession; private final State sendingEmail; private final State sendingSms; private final State waitingForSmsResponses; private final State finished; // FSM. private final FiniteStateMachine fsm; // SMS Stuff. private final ActorRef service; private final Map<Sid, ActorRef> sessions; private Sid initialSessionSid; private ActorRef initialSession; private ActorRef mailerService; private SmsSessionRequest initialSessionRequest; // HTTP Stuff. private final ActorRef downloader; // The storage engine. private final DaoManager storage; //Email configuration private final Configuration emailconfiguration; //Runtime configuration private final Configuration runtime; // User specific configuration. private final Configuration configuration; // Information to reach the application that will be executed // by this interpreter. private final Sid accountId; private final String version; private final URI url; private final String method; private final URI fallbackUrl; private final String fallbackMethod; // application data. private HttpRequestDescriptor request; private HttpResponseDescriptor response; // The RCML parser. private ActorRef parser; private Tag verb; private boolean normalizeNumber; private ConcurrentHashMap<String, String> customHttpHeaderMap = new ConcurrentHashMap<String, String>(); private ConcurrentHashMap<String, String> customRequestHeaderMap; //List of extensions for SmsInterpreter List<RestcommExtensionGeneric> extensions; public SmsInterpreter (final SmsInterpreterParams params) { super(); final ActorRef source = self(); uninitialized = new State("uninitialized", null, null); acquiringLastSmsRequest = new State("acquiring last sms event", new AcquiringLastSmsEvent(source), null); downloadingRcml = new State("downloading rcml", new DownloadingRcml(source), null); downloadingFallbackRcml = new State("downloading fallback rcml", new DownloadingFallbackRcml(source), null); ready = new State("ready", new Ready(source), null); redirecting = new State("redirecting", new Redirecting(source), null); creatingSmsSession = new State("creating sms session", new CreatingSmsSession(source), null); sendingSms = new State("sending sms", new SendingSms(source), null); waitingForSmsResponses = new State("waiting for sms responses", new WaitingForSmsResponses(source), null); sendingEmail = new State("sending Email", new SendingEmail(source), null); finished = new State("finished", new Finished(source), null); // Initialize the transitions for the FSM. final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(uninitialized, acquiringLastSmsRequest)); transitions.add(new Transition(acquiringLastSmsRequest, downloadingRcml)); transitions.add(new Transition(acquiringLastSmsRequest, finished)); transitions.add(new Transition(acquiringLastSmsRequest, sendingEmail)); transitions.add(new Transition(downloadingRcml, ready)); transitions.add(new Transition(downloadingRcml, downloadingFallbackRcml)); transitions.add(new Transition(downloadingRcml, finished)); transitions.add(new Transition(downloadingRcml, sendingEmail)); transitions.add(new Transition(downloadingFallbackRcml, ready)); transitions.add(new Transition(downloadingFallbackRcml, finished)); transitions.add(new Transition(downloadingFallbackRcml, sendingEmail)); transitions.add(new Transition(ready, redirecting)); transitions.add(new Transition(ready, creatingSmsSession)); transitions.add(new Transition(ready, waitingForSmsResponses)); transitions.add(new Transition(ready, sendingEmail)); transitions.add(new Transition(ready, finished)); transitions.add(new Transition(redirecting, ready)); transitions.add(new Transition(redirecting, creatingSmsSession)); transitions.add(new Transition(redirecting, finished)); transitions.add(new Transition(redirecting, sendingEmail)); transitions.add(new Transition(redirecting, waitingForSmsResponses)); transitions.add(new Transition(creatingSmsSession, sendingSms)); transitions.add(new Transition(creatingSmsSession, waitingForSmsResponses)); transitions.add(new Transition(creatingSmsSession, sendingEmail)); transitions.add(new Transition(creatingSmsSession, finished)); transitions.add(new Transition(sendingSms, ready)); transitions.add(new Transition(sendingSms, redirecting)); transitions.add(new Transition(sendingSms, creatingSmsSession)); transitions.add(new Transition(sendingSms, waitingForSmsResponses)); transitions.add(new Transition(sendingSms, sendingEmail)); transitions.add(new Transition(sendingSms, finished)); transitions.add(new Transition(waitingForSmsResponses, waitingForSmsResponses)); transitions.add(new Transition(waitingForSmsResponses, sendingEmail)); transitions.add(new Transition(waitingForSmsResponses, finished)); transitions.add(new Transition(sendingEmail, ready)); transitions.add(new Transition(sendingEmail, redirecting)); transitions.add(new Transition(sendingEmail, creatingSmsSession)); transitions.add(new Transition(sendingEmail, waitingForSmsResponses)); transitions.add(new Transition(sendingEmail, finished)); // Initialize the FSM. this.fsm = new FiniteStateMachine(uninitialized, transitions); // Initialize the runtime stuff. this.service = params.getSmsService(); this.downloader = downloader(); this.storage = params.getStorage(); this.emailconfiguration = params.getConfiguration().subset("smtp-service"); this.runtime = params.getConfiguration().subset("runtime-settings"); this.configuration = params.getConfiguration().subset("sms-aggregator"); this.accountId = params.getAccountId(); this.version = params.getVersion(); this.url = params.getUrl(); this.method = params.getMethod(); this.fallbackUrl = params.getFallbackUrl(); this.fallbackMethod = params.getFallbackMethod(); this.sessions = new HashMap<Sid, ActorRef>(); this.normalizeNumber = runtime.getBoolean("normalize-numbers-for-outbound-calls"); extensions = ExtensionController.getInstance().getExtensions(ExtensionType.FeatureAccessControl); } public static Props props (final SmsInterpreterParams params) { return new Props(new UntypedActorFactory() { @Override public Actor create () throws Exception { return new SmsInterpreter(params); } }); } private 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 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); } protected String format (final String number) { if (normalizeNumber) { final PhoneNumberUtil numbersUtil = PhoneNumberUtil.getInstance(); try { final PhoneNumber result = numbersUtil.parse(number, "US"); return numbersUtil.format(result, PhoneNumberFormat.E164); } catch (final NumberParseException ignored) { return null; } } else { return number; } } protected void invalidVerb (final Tag verb) { final ActorRef self = self(); final Notification notification = notification(WARNING_NOTIFICATION, 14110, "Invalid Verb for SMS Reply"); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); // Get the next verb. final GetNextVerb next = new GetNextVerb(); parser.tell(next, self); } protected 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.setApiVersion(version); builder.setLog(log); builder.setErrorCode(error); final String base = runtime.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 != null && (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(); } @SuppressWarnings("unchecked") @Override public void onReceive (final Object message) throws Exception { final Class<?> klass = message.getClass(); final State state = fsm.state(); if (StartInterpreter.class.equals(klass)) { fsm.transition(message, acquiringLastSmsRequest); } else if (SmsSessionRequest.class.equals(klass)) { customRequestHeaderMap = ((SmsSessionRequest) message).headers(); fsm.transition(message, downloadingRcml); } else if (DownloaderResponse.class.equals(klass)) { final DownloaderResponse response = (DownloaderResponse) message; if (response.succeeded()) { final HttpResponseDescriptor descriptor = response.get(); if (HttpStatus.SC_OK == descriptor.getStatusCode()) { fsm.transition(message, ready); } else { if (downloadingRcml.equals(state)) { if (fallbackUrl != null) { fsm.transition(message, downloadingFallbackRcml); } } else { if (sessions.size() > 0) { fsm.transition(message, waitingForSmsResponses); } else { fsm.transition(message, finished); } } } } else { if (downloadingRcml.equals(state)) { if (fallbackUrl != null) { fsm.transition(message, downloadingFallbackRcml); } } else { if (sessions.size() > 0) { fsm.transition(message, waitingForSmsResponses); } else { fsm.transition(message, finished); } } } } else if (ParserFailed.class.equals(klass)) { if (logger.isInfoEnabled()) { logger.info("ParserFailed received. Will stop the call"); } fsm.transition(message, finished); } else if (Tag.class.equals(klass)) { final Tag verb = (Tag) message; if (Verbs.redirect.equals(verb.name())) { fsm.transition(message, redirecting); } else if (Verbs.sms.equals(verb.name())) { //Check if Outbound SMS is allowed ExtensionController ec = ExtensionController.getInstance(); final IExtensionFeatureAccessRequest far = new FeatureAccessRequest(FeatureAccessRequest.Feature.OUTBOUND_SMS, accountId); ExtensionResponse er = ec.executePreOutboundAction(far, this.extensions); if (er.isAllowed()) { fsm.transition(message, creatingSmsSession); ec.executePostOutboundAction(far, extensions); } else { if (logger.isDebugEnabled()) { final String errMsg = "Outbound SMS is not Allowed"; logger.debug(errMsg); } final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 11001, "Outbound SMS is now allowed"); notifications.addNotification(notification); fsm.transition(message, finished); ec.executePostOutboundAction(far, extensions); return; } } else if (Verbs.email.equals(verb.name())) { fsm.transition(message, sendingEmail); } else { invalidVerb(verb); } } else if (SmsServiceResponse.class.equals(klass)) { final SmsServiceResponse<ActorRef> response = (SmsServiceResponse<ActorRef>) message; if (response.succeeded()) { if (creatingSmsSession.equals(state)) { fsm.transition(message, sendingSms); } } else { if (sessions.size() > 0) { fsm.transition(message, waitingForSmsResponses); } else { fsm.transition(message, finished); } } } else if (SmsSessionResponse.class.equals(klass)) { response(message); } else if (StopInterpreter.class.equals(klass)) { if (sessions.size() > 0) { fsm.transition(message, waitingForSmsResponses); } else { fsm.transition(message, finished); } } else if (EmailResponse.class.equals(klass)) { final EmailResponse response = (EmailResponse) message; if (!response.succeeded()) { logger.error( "There was an error while sending an email :" + response.error(), response.cause()); } fsm.transition(message, ready); } } protected List<NameValuePair> parameters() { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); final String smsSessionSid = initialSessionSid.toString(); parameters.add(new BasicNameValuePair("SmsSid", smsSessionSid)); final String accountSid = accountId.toString(); parameters.add(new BasicNameValuePair("AccountSid", accountSid)); final String from = format(initialSessionRequest.from()); parameters.add(new BasicNameValuePair("From", from)); final String to = format(initialSessionRequest.to()); parameters.add(new BasicNameValuePair("To", to)); final String body = initialSessionRequest.body(); parameters.add(new BasicNameValuePair("Body", body)); //Issue https://telestax.atlassian.net/browse/RESTCOMM-517. If Request contains custom headers pass them to the HTTP server. if(customRequestHeaderMap != null && !customRequestHeaderMap.isEmpty()){ Iterator<String> iter = customRequestHeaderMap.keySet().iterator(); while(iter.hasNext()){ String headerName = iter.next(); parameters.add(new BasicNameValuePair("SipHeader_" + headerName, customRequestHeaderMap.remove(headerName))); } } return parameters; } private 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); } private void response(final Object message) { final Class<?> klass = message.getClass(); final ActorRef self = self(); if (SmsSessionResponse.class.equals(klass)) { final SmsSessionResponse response = (SmsSessionResponse) message; final SmsSessionInfo info = response.info(); SmsMessage record = (SmsMessage) info.attributes().get("record"); final SmsMessagesDao messages = storage.getSmsMessagesDao(); messages.updateSmsMessage(record); // Notify the callback listener. final Object attribute = info.attributes().get("callback"); if (attribute != null) { final URI callback = (URI) attribute; final List<NameValuePair> parameters = parameters(); request = new HttpRequestDescriptor(callback, "POST", parameters); downloader.tell(request, null); } // Destroy the sms session. final ActorRef session = sessions.remove(record.getSid()); final DestroySmsSession destroy = new DestroySmsSession(session); service.tell(destroy, self); // Try to stop the interpreter. final State state = fsm.state(); if (waitingForSmsResponses.equals(state)) { final StopInterpreter stop = new StopInterpreter(); self.tell(stop, self); } } } protected URI resolve(final URI base, final URI uri) { if (base.equals(uri)) { return uri; } else { if (!uri.isAbsolute()) { return base.resolve(uri); } else { return uri; } } } private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } } private final class AcquiringLastSmsEvent extends AbstractAction { public AcquiringLastSmsEvent(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final StartInterpreter request = (StartInterpreter) message; initialSession = request.resource(); initialSession.tell(new Observe(source), source); initialSession.tell(new GetLastSmsRequest(), source); } } private final class DownloadingRcml extends AbstractAction { public DownloadingRcml(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { initialSessionRequest = (SmsSessionRequest) message; initialSessionSid = Sid.generate(Sid.Type.SMS_MESSAGE); final SmsMessage.Builder builder = SmsMessage.builder(); builder.setSid(initialSessionSid); builder.setAccountSid(accountId); builder.setApiVersion(version); builder.setRecipient(initialSessionRequest.to()); builder.setSender(initialSessionRequest.from()); builder.setBody(initialSessionRequest.body()); builder.setDirection(Direction.INBOUND); builder.setStatus(Status.RECEIVED); 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("/SMS/Messages/"); buffer.append(initialSessionSid.toString()); final URI uri = URI.create(buffer.toString()); builder.setUri(uri); final SmsMessage record = builder.build(); final SmsMessagesDao messages = storage.getSmsMessagesDao(); messages.addSmsMessage(record); getContext().system().eventStream().publish(record); // Destroy the initial session. service.tell(new DestroySmsSession(initialSession), source); initialSession = null; // 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 { 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); } } // 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 { final UntypedActorContext context = getContext(); final State state = fsm.state(); // Make sure we create a new parser if necessary. if (downloadingRcml.equals(state) || downloadingFallbackRcml.equals(state) || redirecting.equals(state) || sendingSms.equals(state)) { response = ((DownloaderResponse) message).get(); if (parser != null) { context.stop(parser); parser = null; } try{ final String type = response.getContentType(); final String content = response.getContentAsString(); if ((type != null && content != null) && (type.contains("text/xml") || type.contains("application/xml") || type.contains("text/html"))) { parser = parser(content); } else { if(logger.isInfoEnabled()) { logger.info("DownloaderResponse getContentType is null: "+response); } final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 12300, "Invalide content-type."); notifications.addNotification(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } catch (Exception e) { final NotificationsDao notifications = storage.getNotificationsDao(); final Notification notification = notification(WARNING_NOTIFICATION, 12300, "Invalide content-type."); notifications.addNotification(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } // Ask the parser for the next action to take. Header[] headers = response.getHeaders(); for(Header header: headers) { if (header.getName().startsWith("X-")) { customHttpHeaderMap.put(header.getName(), header.getValue()); } } final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } private final class Redirecting extends AbstractAction { public Redirecting(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { verb = (Tag) message; final NotificationsDao notifications = storage.getNotificationsDao(); String method = "POST"; Attribute attribute = verb.attribute("method"); if (attribute != null) { method = attribute.value(); if (method != null && !method.isEmpty()) { if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) { final Notification notification = notification(WARNING_NOTIFICATION, 13710, method + " is not a valid HTTP method for <Redirect>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } final String text = verb.text(); if (text != null && !text.isEmpty()) { // Try to redirect. URI target = null; try { target = URI.create(text); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, text + " is an invalid URI."); notifications.addNotification(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } final URI base = request.getUri(); final URI uri = resolve(base, target); final List<NameValuePair> parameters = parameters(); request = new HttpRequestDescriptor(uri, method, parameters); downloader.tell(request, source); } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } } private final class CreatingSmsSession extends AbstractAction { public CreatingSmsSession(final ActorRef source) { super(source); } @Override public void execute(Object message) throws Exception { // Save <Sms> verb. verb = (Tag) message; // Create a new sms session to handle the <Sms> verb. service.tell(new CreateSmsSession(initialSessionRequest.from(), initialSessionRequest.to(), accountId.toString(), false), source); } } private final class SendingSms extends AbstractAction { public SendingSms(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { final SmsServiceResponse<ActorRef> response = (SmsServiceResponse<ActorRef>) message; final ActorRef session = response.get(); final NotificationsDao notifications = storage.getNotificationsDao(); // Parse "from". String from = initialSessionRequest.to(); Attribute attribute = verb.attribute("from"); if (attribute != null) { from = attribute.value(); if (from != null && !from.isEmpty()) { from = format(from); if (from == null) { from = verb.attribute("from").value(); final Notification notification = notification(ERROR_NOTIFICATION, 14102, from + " is an invalid 'from' phone number."); notifications.addNotification(notification); service.tell(new DestroySmsSession(session), source); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } else { from = initialSessionRequest.to(); } } // Parse "to". String to = initialSessionRequest.from(); attribute = verb.attribute("to"); if (attribute != null) { to = attribute.value(); if (to == null) { to = initialSessionRequest.from(); } // if (to != null && !to.isEmpty()) { // to = format(to); // if (to == null) { // to = verb.attribute("to").value(); // final Notification notification = notification(ERROR_NOTIFICATION, 14101, to // + " is an invalid 'to' phone number."); // notifications.addNotification(notification); // service.tell(new DestroySmsSession(session), source); // final StopInterpreter stop = StopInterpreter.instance(); // source.tell(stop, source); // return; // } // } else { // to = initialSessionRequest.from(); // } } // Parse <Sms> text. String body = verb.text(); if (body == null || body.isEmpty()) { final Notification notification = notification(ERROR_NOTIFICATION, 14103, body + " is an invalid SMS body."); notifications.addNotification(notification); service.tell(new DestroySmsSession(session), source); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } else { // Start observing events from the sms session. session.tell(new Observe(source), source); // Create an SMS detail record. final Sid sid = Sid.generate(Sid.Type.SMS_MESSAGE); final SmsMessage.Builder builder = SmsMessage.builder(); builder.setSid(sid); builder.setAccountSid(accountId); builder.setApiVersion(version); builder.setRecipient(to); builder.setSender(from); builder.setBody(body); builder.setDirection(Direction.OUTBOUND_REPLY); builder.setStatus(Status.SENDING); 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("/SMS/Messages/"); buffer.append(sid.toString()); final URI uri = URI.create(buffer.toString()); builder.setUri(uri); SmsVerb.populateAttributes(verb, builder); final SmsMessage record = builder.build(); final SmsMessagesDao messages = storage.getSmsMessagesDao(); messages.addSmsMessage(record); // Store the sms record in the sms session. session.tell(new SmsSessionAttribute("record", record), source); // Send the SMS. final SmsSessionRequest sms = new SmsSessionRequest(from, to, body, customHttpHeaderMap); session.tell(sms, source); sessions.put(sid, session); } // Parses "action". attribute = verb.attribute("action"); if (attribute != null) { String action = attribute.value(); if (action != null && !action.isEmpty()) { URI target = null; try { target = URI.create(action); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, action + " is an invalid URI."); notifications.addNotification(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } final URI base = request.getUri(); final URI uri = resolve(base, target); // Parse "method". String method = "POST"; attribute = verb.attribute("method"); 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 <Sms>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } // Redirect to the action url. final List<NameValuePair> parameters = parameters(); final String status = Status.SENDING.toString(); parameters.add(new BasicNameValuePair("SmsStatus", status)); request = new HttpRequestDescriptor(uri, method, parameters); downloader.tell(request, source); return; } } // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } private final class WaitingForSmsResponses extends AbstractAction { public WaitingForSmsResponses(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { response(message); } } private final class Finished extends AbstractAction { public Finished(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final UntypedActorContext context = getContext(); context.stop(source); } } private final class SendingEmail extends AbstractAction { public SendingEmail(final ActorRef source){ super(source); } @Override public void execute( final Object message) throws Exception { final Tag verb = (Tag)message; // Parse "from". String from; Attribute attribute = verb.attribute("from"); if (attribute != null) { from = attribute.value(); }else{ Exception error = new Exception("From attribute was not defined"); source.tell(new EmailResponse(error,error.getMessage()), source); return; } // Parse "to". String to; attribute = verb.attribute("to"); if (attribute != null) { to = attribute.value(); }else{ Exception error = new Exception("To attribute was not defined"); source.tell(new EmailResponse(error,error.getMessage()), source); return; } // Parse "cc". String cc=""; attribute = verb.attribute("cc"); if (attribute != null) { cc = attribute.value(); } // Parse "bcc". String bcc=""; attribute = verb.attribute("bcc"); if (attribute != null) { bcc = attribute.value(); } // Parse "subject" String subject; attribute = verb.attribute("subject"); if (attribute != null) { subject = attribute.value(); }else{ subject="Restcomm Email Service"; } // Send the email. final Mail emailMsg = new Mail(from, to, subject, verb.text(),cc,bcc); if (mailerService == null){ mailerService = mailer(emailconfiguration); } mailerService.tell(new EmailRequest(emailMsg), self()); } } }
44,996
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SubVoiceInterpreter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/SubVoiceInterpreter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.ReceiveTimeout; 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.message.BasicNameValuePair; import org.joda.time.DateTime; import org.restcomm.connect.asr.AsrResponse; import org.restcomm.connect.commons.cache.DiskCacheResponse; 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.telephony.CreateCallType; import org.restcomm.connect.dao.CallDetailRecordsDao; import org.restcomm.connect.dao.NotificationsDao; import org.restcomm.connect.dao.entities.Notification; import org.restcomm.connect.fax.FaxResponse; import org.restcomm.connect.http.client.DownloaderResponse; import org.restcomm.connect.http.client.HttpRequestDescriptor; 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.Tag; import org.restcomm.connect.interpreter.rcml.Verbs; import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup; import org.restcomm.connect.sms.api.SmsServiceResponse; import org.restcomm.connect.sms.api.SmsSessionResponse; 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.Cancel; import org.restcomm.connect.telephony.api.DestroyCall; import org.restcomm.connect.telephony.api.Reject; import org.restcomm.connect.tts.api.SpeechSynthesizerResponse; import javax.servlet.sip.SipServletResponse; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * @author [email protected] * @author [email protected] * @author [email protected] */ public final class SubVoiceInterpreter extends BaseVoiceInterpreter { // Logger. private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // States for the FSM. private final State downloadingRcml; private final State ready; private final State notFound; private final State rejecting; private final State finished; // application data. private DownloaderResponse downloaderResponse; private ActorRef source; private Boolean hangupOnEnd = false; private ActorRef originalInterpreter; public SubVoiceInterpreter(SubVoiceInterpreterParams params) { super(); source = self(); downloadingRcml = new State("downloading rcml", new DownloadingRcml(source), null); ready = new State("ready", new Ready(source), null); notFound = new State("notFound", new NotFound(source), null); rejecting = new State("rejecting", new Rejecting(source), null); finished = new State("finished", new Finished(source), null); transitions.add(new Transition(acquiringAsrInfo, finished)); transitions.add(new Transition(acquiringSynthesizerInfo, finished)); transitions.add(new Transition(acquiringCallInfo, downloadingRcml)); transitions.add(new Transition(acquiringCallInfo, finished)); transitions.add(new Transition(downloadingRcml, ready)); transitions.add(new Transition(downloadingRcml, notFound)); transitions.add(new Transition(downloadingRcml, hangingUp)); transitions.add(new Transition(downloadingRcml, finished)); transitions.add(new Transition(ready, faxing)); transitions.add(new Transition(ready, pausing)); transitions.add(new Transition(ready, checkingCache)); transitions.add(new Transition(ready, caching)); transitions.add(new Transition(ready, synthesizing)); transitions.add(new Transition(ready, rejecting)); transitions.add(new Transition(ready, redirecting)); transitions.add(new Transition(ready, processingGatherChildren)); transitions.add(new Transition(ready, creatingRecording)); transitions.add(new Transition(ready, creatingSmsSession)); transitions.add(new Transition(ready, hangingUp)); transitions.add(new Transition(ready, finished)); transitions.add(new Transition(pausing, ready)); transitions.add(new Transition(pausing, finished)); transitions.add(new Transition(rejecting, finished)); transitions.add(new Transition(faxing, ready)); transitions.add(new Transition(faxing, finished)); transitions.add(new Transition(caching, finished)); transitions.add(new Transition(playing, ready)); transitions.add(new Transition(playing, finished)); transitions.add(new Transition(synthesizing, finished)); transitions.add(new Transition(redirecting, ready)); transitions.add(new Transition(redirecting, finished)); transitions.add(new Transition(creatingRecording, finished)); transitions.add(new Transition(finishRecording, ready)); transitions.add(new Transition(finishRecording, finished)); transitions.add(new Transition(processingGatherChildren, finished)); transitions.add(new Transition(gathering, finished)); transitions.add(new Transition(finishGathering, finished)); transitions.add(new Transition(creatingSmsSession, finished)); transitions.add(new Transition(sendingSms, ready)); transitions.add(new Transition(sendingSms, finished)); transitions.add(new Transition(hangingUp, 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.viStatusCallback = params.getStatusCallback(); this.viStatusCallbackMethod = params.getStatusCallbackMethod(); this.emailAddress = params.getEmailAddress(); this.configuration = params.getConfiguration(); this.callManager = params.getCallManager(); // this.asrService = asr(configuration.subset("speech-recognizer")); // this.faxService = fax(configuration.subset("fax-service")); this.smsService = params.getSmsService(); this.smsSessions = new HashMap<Sid, ActorRef>(); this.storage = params.getStorage(); // this.synthesizer = tts(configuration.subset("speech-synthesizer")); final Configuration runtime = configuration.subset("runtime-settings"); // String path = runtime.getString("cache-path"); // if (!path.endsWith("/")) { // path = path + "/"; // } // path = path + accountId.toString(); // cachePath = path; // String uri = runtime.getString("cache-uri"); // if (!uri.endsWith("/")) { // uri = uri + "/"; // } // try { // uri = UriUtils.resolve(new URI(uri)).toString(); // } catch (URISyntaxException e) { // logger.error("URISyntaxException while trying to resolve Cache URI: "+e); // } // uri = uri + accountId.toString(); // this.cache = cache(path, uri); this.downloader = downloader(); this.hangupOnEnd = params.getHangupOnEnd(); } public static Props props(final SubVoiceInterpreterParams params) { return new Props(new UntypedActorFactory() { @Override public Actor create() throws Exception { return new SubVoiceInterpreter(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(); } @SuppressWarnings("unchecked") @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(" ********** SubVoiceInterpreter's Current State: " + state.toString()); logger.info(" ********** SubVoiceInterpreter's Processing Message: " + klass.getName()); } if (StartInterpreter.class.equals(klass)) { final StartInterpreter request = (StartInterpreter) message; call = request.resource(); originalInterpreter = sender; fsm.transition(message, acquiringAsrInfo); } else if (AsrResponse.class.equals(klass)) { if (outstandingAsrRequests > 0) { asrResponse(message); } else { fsm.transition(message, acquiringSynthesizerInfo); } } else if (SpeechSynthesizerResponse.class.equals(klass)) { if (acquiringSynthesizerInfo.equals(state)) { fsm.transition(message, acquiringCallInfo); } else if (synthesizing.equals(state)) { final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message; if (response.succeeded()) { fsm.transition(message, caching); } else { fsm.transition(message, hangingUp); } } else if (processingGatherChildren.equals(state)) { final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message; if (response.succeeded()) { fsm.transition(message, processingGatherChildren); } else { fsm.transition(message, hangingUp); } } } else if (CallResponse.class.equals(klass)) { if (acquiringCallInfo.equals(state)) { final CallResponse<CallInfo> response = (CallResponse<CallInfo>) message; callInfo = response.get(); fsm.transition(message, downloadingRcml); } } else if (DownloaderResponse.class.equals(klass)) { downloaderResponse = (DownloaderResponse) message; if (logger.isDebugEnabled()) { logger.debug("response succeeded " + downloaderResponse.succeeded() + ", statusCode " + downloaderResponse.get().getStatusCode()); } if (downloaderResponse.succeeded() && HttpStatus.SC_OK == downloaderResponse.get().getStatusCode()) { fsm.transition(message, ready); } else if (downloaderResponse.succeeded() && HttpStatus.SC_NOT_FOUND == downloaderResponse.get().getStatusCode()) { originalInterpreter.tell(new Exception("Downloader Response Exception"), source); fsm.transition(message, notFound); } } else if (DiskCacheResponse.class.equals(klass)) { final DiskCacheResponse response = (DiskCacheResponse) message; if (response.succeeded()) { if (caching.equals(state) || checkingCache.equals(state)) { if (Verbs.play.equals(verb.name()) || Verbs.say.equals(verb.name())) { fsm.transition(message, playing); } else if (Verbs.fax.equals(verb.name())) { fsm.transition(message, faxing); } } else if (processingGatherChildren.equals(state)) { fsm.transition(message, processingGatherChildren); } } else { if (checkingCache.equals(state)) { fsm.transition(message, synthesizing); } else { fsm.transition(message, hangingUp); } } } else if (Tag.class.equals(klass)) { verb = (Tag) message; if (Verbs.dial.equals(verb.name())) originalInterpreter.tell(new Exception("Dial verb not supported"), source); if (Verbs.reject.equals(verb.name())) { fsm.transition(message, rejecting); } else if (Verbs.pause.equals(verb.name())) { fsm.transition(message, pausing); } else if (Verbs.fax.equals(verb.name())) { fsm.transition(message, caching); } else if (Verbs.play.equals(verb.name())) { fsm.transition(message, caching); } else if (Verbs.say.equals(verb.name())) { fsm.transition(message, checkingCache); } else if (Verbs.gather.equals(verb.name())) { fsm.transition(message, processingGatherChildren); } else if (Verbs.pause.equals(verb.name())) { fsm.transition(message, pausing); } else if (Verbs.hangup.equals(verb.name())) { originalInterpreter.tell(message, source); fsm.transition(message, hangingUp); } else if (Verbs.redirect.equals(verb.name())) { fsm.transition(message, redirecting); } else if (Verbs.record.equals(verb.name())) { fsm.transition(message, creatingRecording); } else if (Verbs.sms.equals(verb.name())) { fsm.transition(message, creatingSmsSession); } else { invalidVerb(verb); } } else if (End.class.equals(klass)) { if (!hangupOnEnd) { originalInterpreter.tell(message, source); } else { fsm.transition(message, hangingUp); } } else if (StartGathering.class.equals(klass)) { fsm.transition(message, gathering); } else if (CallStateChanged.class.equals(klass)) { final CallStateChanged event = (CallStateChanged) message; if (CallStateChanged.State.NO_ANSWER == event.state() || CallStateChanged.State.COMPLETED == event.state() || CallStateChanged.State.FAILED == event.state() || CallStateChanged.State.BUSY == event.state()) { originalInterpreter.tell(new Cancel(), source); } } else if (MediaGroupResponse.class.equals(klass)) { final MediaGroupResponse<String> response = (MediaGroupResponse<String>) message; if (response.succeeded()) { if (playingRejectionPrompt.equals(state)) { originalInterpreter.tell(message, source); } else if (playing.equals(state)) { fsm.transition(message, ready); } else if (creatingRecording.equals(state)) { fsm.transition(message, finishRecording); } else if (gathering.equals(state)) { fsm.transition(message, finishGathering); } } else { originalInterpreter.tell(message, source); } } else if (SmsServiceResponse.class.equals(klass)) { final SmsServiceResponse<ActorRef> response = (SmsServiceResponse<ActorRef>) message; if (response.succeeded()) { if (creatingSmsSession.equals(state)) { fsm.transition(message, sendingSms); } } else { fsm.transition(message, hangingUp); } } else if (SmsSessionResponse.class.equals(klass)) { smsResponse(message); } else if (FaxResponse.class.equals(klass)) { fsm.transition(message, ready); } else if (StopInterpreter.class.equals(klass)) { if (CallStateChanged.State.IN_PROGRESS == callState) { fsm.transition(message, hangingUp); } else { fsm.transition(message, finished); } } else if (message instanceof ReceiveTimeout) { if (pausing.equals(state)) { fsm.transition(message, ready); } } } @Override List<NameValuePair> parameters() { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); final String callSid = callInfo.sid().toString(); parameters.add(new BasicNameValuePair("CallSid", callSid)); final String accountSid = accountId.toString(); parameters.add(new BasicNameValuePair("AccountSid", accountSid)); final String from = e164(callInfo.from()); parameters.add(new BasicNameValuePair("From", from)); final String to = e164(callInfo.to()); parameters.add(new BasicNameValuePair("To", to)); final String state = callState.toString(); parameters.add(new BasicNameValuePair("CallStatus", state)); parameters.add(new BasicNameValuePair("ApiVersion", version)); final String direction = callInfo.direction(); parameters.add(new BasicNameValuePair("Direction", direction)); final String callerName = callInfo.fromName(); parameters.add(new BasicNameValuePair("CallerName", callerName)); final String forwardedFrom = callInfo.forwardedFrom(); parameters.add(new BasicNameValuePair("ForwardedFrom", forwardedFrom)); // Adding SIP OUT Headers and SipCallId for // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out if (CreateCallType.SIP == callInfo.type()) { SipServletResponse lastResponse = callInfo.lastResponse(); if (lastResponse != null) { final int statusCode = lastResponse.getStatus(); final String method = lastResponse.getMethod(); // See https://www.twilio.com/docs/sip/receiving-sip-headers // On a successful call setup (when a 200 OK SIP response is returned) any X-headers on the 200 OK message are // posted to the call screening URL if (statusCode >= 200 && statusCode < 300 && "INVITE".equalsIgnoreCase(method)) { final String sipCallId = lastResponse.getCallId(); parameters.add(new BasicNameValuePair("SipCallId", sipCallId)); Iterator<String> headerIt = lastResponse.getHeaderNames(); while (headerIt.hasNext()) { String headerName = headerIt.next(); if (headerName.startsWith("X-")) { parameters .add(new BasicNameValuePair("SipHeader_" + headerName, lastResponse.getHeader(headerName))); } } } } } return parameters; } private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = 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 { final Class<?> klass = message.getClass(); if (CallResponse.class.equals(klass)) { final CallResponse<CallInfo> response = (CallResponse<CallInfo>) message; callInfo = response.get(); callState = callInfo.state(); // 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 Ready extends AbstractAction { public Ready(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (parser == null) { response = downloaderResponse.get(); 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("audio/wav") || type.contains("audio/wave") || type.contains("audio/x-wav")) { parser = parser("<Play>" + request.getUri() + "</Play>"); } else if (type.contains("text/plain")) { parser = parser("<Say>" + response.getContentAsString() + "</Say>"); } else { final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } // Ask the parser for the next action to take. 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 { 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. call.tell(new org.restcomm.connect.telephony.api.NotFound(), source); } } private final class Rejecting extends AbstractAction { public Rejecting(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } String reason = "rejected"; Attribute attribute = verb.attribute("reason"); if (attribute != null) { reason = attribute.value(); if (reason != null && !reason.isEmpty()) { if ("rejected".equalsIgnoreCase(reason)) { reason = "rejected"; } else if ("busy".equalsIgnoreCase(reason)) { reason = "busy"; } else { reason = "rejected"; } } else { reason = "rejected"; } } // Reject the call. call.tell(new Reject(reason), source); } } private final class Finished extends AbstractAction { public Finished(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { 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(); } // Stop the media group(s). if (call != null) { final StopMediaGroup stop = new StopMediaGroup(); call.tell(stop, source); } // Destroy the Call(s). callManager.tell(new DestroyCall(call), source); // Stop the dependencies. final UntypedActorContext context = getContext(); if (mailerNotify != null) context.stop(mailerNotify); context.stop(downloader); context.stop(getAsrService()); context.stop(getFaxService()); context.stop(getCache()); context.stop(getSynthesizer()); // Stop the interpreter. postCleanup(); } } }
28,591
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmsInterpreterParams.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/SmsInterpreterParams.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; 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 SmsInterpreterParams { private Configuration configuration; private ActorRef smsService; private DaoManager storage; private Sid accountId; private String version; private URI url; private String method; private URI fallbackUrl; private String fallbackMethod; private SmsInterpreterParams(Configuration configuration, ActorRef smsService, DaoManager storage, Sid accountId, String version, URI url, String method, URI fallbackUrl, String fallbackMethod) { this.configuration = configuration; this.smsService = smsService; this.storage = storage; this.accountId = accountId; this.version = version; this.url = url; this.method = method; this.fallbackUrl = fallbackUrl; this.fallbackMethod = fallbackMethod; } public Configuration getConfiguration() { return configuration; } public ActorRef getSmsService() { return smsService; } public DaoManager getStorage() { return storage; } public Sid getAccountId() { return accountId; } 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 static final class Builder { private Configuration configuration; private ActorRef smsService; private DaoManager storage; private Sid accountId; private String version; private URI url; private String method; private URI fallbackUrl; private String fallbackMethod; public Builder setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } public Builder setSmsService(ActorRef smsService) { this.smsService = smsService; return this; } public Builder setStorage(DaoManager storage) { this.storage = storage; return this; } public Builder setAccountId(Sid accountId) { this.accountId = accountId; 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 SmsInterpreterParams build() { return new SmsInterpreterParams(configuration, smsService, storage, accountId, version, url, method, fallbackUrl, fallbackMethod); } } }
4,317
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StartGathering.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/StartGathering.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class StartGathering { private static final class Singleton { private static final StartGathering instance = new StartGathering(); } private StartGathering() { super(); } public static StartGathering instance() { return Singleton.instance; } }
1,307
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConfVoiceInterpreter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/ConfVoiceInterpreter.java
package org.restcomm.connect.interpreter; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.Props; import akka.actor.ReceiveTimeout; import akka.actor.UntypedActor; import akka.actor.UntypedActorContext; import akka.actor.UntypedActorFactory; import akka.event.Logging; import akka.event.LoggingAdapter; import com.google.i18n.phonenumbers.NumberParseException; import com.google.i18n.phonenumbers.PhoneNumberUtil; import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat; import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber; import org.apache.commons.configuration.Configuration; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.joda.time.DateTime; import org.restcomm.connect.commons.cache.DiskCacheFactory; 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.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.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.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.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.Tag; import org.restcomm.connect.interpreter.rcml.Verbs; import org.restcomm.connect.mscontrol.api.messages.CreateMediaGroup; import org.restcomm.connect.mscontrol.api.messages.MediaGroupResponse; import org.restcomm.connect.mscontrol.api.messages.MediaGroupStateChanged; import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerResponse; import org.restcomm.connect.mscontrol.api.messages.Play; import org.restcomm.connect.mscontrol.api.messages.StartMediaGroup; import org.restcomm.connect.mscontrol.api.messages.StopMediaGroup; import org.restcomm.connect.telephony.api.CallInfo; import org.restcomm.connect.telephony.api.CallStateChanged; import org.restcomm.connect.telephony.api.DestroyWaitUrlConfMediaGroup; 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 java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import static org.restcomm.connect.interpreter.rcml.Verbs.play; import static org.restcomm.connect.interpreter.rcml.Verbs.say; public class ConfVoiceInterpreter extends RestcommUntypedActor { private static final int ERROR_NOTIFICATION = 0; private static final int WARNING_NOTIFICATION = 1; static String EMAIL_SENDER; // Logger. private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); // States for the FSM. private final State uninitialized; private final State acquiringSynthesizerInfo; private final State downloadingRcml; private final State initializingConfMediaGroup; private final State acquiringConfMediaGroup; private final State ready; private final State notFound; private final State caching; private final State checkingCache; private final State playing; private final State synthesizing; private final State redirecting; private final State finished; // FSM. private final FiniteStateMachine fsm; // The user specific configuration. private final Configuration configuration; // The block storage cache. private final ActorRef cache; private final String cachePath; // The downloader will fetch resources for us using HTTP. private final ActorRef downloader; // The mail man that will deliver e-mail. private ActorRef mailerNotify = null; // The storage engine. private final DaoManager storage; // The text to speech synthesizer service. private final ActorRef synthesizer; // The languages supported by the text to speech synthesizer service. private SpeechSynthesizerInfo synthesizerInfo; // The conference being handled by this interpreter. private ActorRef conference; private ActorRef conferenceMediaGroup; // The information for this call. private CallInfo callInfo; // The call state. private CallStateChanged.State callState; // A call detail record. private CallDetailRecord callRecord; // Information to reach the application that will be executed // by this interpreter. private final Sid accountId; private final String version; private final URI url; private final String method; private final String emailAddress; // application data. private HttpRequestDescriptor request; private HttpResponseDescriptor response; private DownloaderResponse downloaderResponse; // The RCML parser. private ActorRef parser; private ActorRef source; private Tag verb; private ActorRef originalInterpreter; public ConfVoiceInterpreter(final ConfVoiceInterpreterParams params) { super(); source = self(); uninitialized = new State("uninitialized", null, null); acquiringSynthesizerInfo = new State("acquiring tts info", new AcquiringSpeechSynthesizerInfo(source), null); acquiringConfMediaGroup = new State("acquiring call media group", new AcquiringConferenceMediaGroup(source), null); downloadingRcml = new State("downloading rcml", new DownloadingRcml(source), null); initializingConfMediaGroup = new State("initializing call media group", new InitializingConferenceMediaGroup(source), null); ready = new State("ready", new Ready(source), null); notFound = new State("notFound", new NotFound(source), null); caching = new State("caching", new Caching(source), null); checkingCache = new State("checkingCache", new CheckCache(source), null); playing = new State("playing", new Playing(source), null); synthesizing = new State("synthesizing", new Synthesizing(source), null); redirecting = new State("redirecting", new Redirecting(source), null); finished = new State("finished", new Finished(source), null); // Initialize the transitions for the FSM. final Set<Transition> transitions = new HashSet<Transition>(); transitions.add(new Transition(uninitialized, acquiringSynthesizerInfo)); transitions.add(new Transition(uninitialized, finished)); transitions.add(new Transition(acquiringSynthesizerInfo, finished)); transitions.add(new Transition(acquiringSynthesizerInfo, downloadingRcml)); transitions.add(new Transition(acquiringConfMediaGroup, initializingConfMediaGroup)); transitions.add(new Transition(acquiringConfMediaGroup, finished)); transitions.add(new Transition(initializingConfMediaGroup, downloadingRcml)); transitions.add(new Transition(initializingConfMediaGroup, checkingCache)); transitions.add(new Transition(initializingConfMediaGroup, caching)); transitions.add(new Transition(initializingConfMediaGroup, synthesizing)); transitions.add(new Transition(initializingConfMediaGroup, redirecting)); transitions.add(new Transition(initializingConfMediaGroup, finished)); transitions.add(new Transition(initializingConfMediaGroup, ready)); transitions.add(new Transition(downloadingRcml, ready)); transitions.add(new Transition(downloadingRcml, notFound)); transitions.add(new Transition(downloadingRcml, finished)); transitions.add(new Transition(downloadingRcml, acquiringConfMediaGroup)); transitions.add(new Transition(ready, checkingCache)); transitions.add(new Transition(ready, caching)); transitions.add(new Transition(ready, synthesizing)); transitions.add(new Transition(ready, redirecting)); transitions.add(new Transition(ready, finished)); transitions.add(new Transition(caching, playing)); transitions.add(new Transition(caching, caching)); transitions.add(new Transition(caching, redirecting)); transitions.add(new Transition(caching, synthesizing)); transitions.add(new Transition(caching, finished)); transitions.add(new Transition(checkingCache, synthesizing)); transitions.add(new Transition(checkingCache, playing)); transitions.add(new Transition(checkingCache, checkingCache)); transitions.add(new Transition(playing, ready)); transitions.add(new Transition(playing, finished)); transitions.add(new Transition(synthesizing, checkingCache)); transitions.add(new Transition(synthesizing, caching)); transitions.add(new Transition(synthesizing, redirecting)); transitions.add(new Transition(synthesizing, synthesizing)); transitions.add(new Transition(synthesizing, finished)); transitions.add(new Transition(redirecting, ready)); transitions.add(new Transition(redirecting, checkingCache)); transitions.add(new Transition(redirecting, caching)); transitions.add(new Transition(redirecting, synthesizing)); transitions.add(new Transition(redirecting, redirecting)); transitions.add(new Transition(redirecting, finished)); // Initialize the FSM. this.fsm = new FiniteStateMachine(uninitialized, transitions); // Initialize the runtime stuff. this.accountId = params.getAccount(); this.version = params.getVersion(); this.url = params.getUrl(); this.method = params.getMethod(); this.emailAddress = params.getEmailAddress(); this.configuration = params.getConfiguration(); this.storage = params.getStorage(); this.synthesizer = tts(configuration.subset("speech-synthesizer")); final Configuration runtime = configuration.subset("runtime-settings"); String path = runtime.getString("cache-path"); if (!path.endsWith("/")) { path = path + "/"; } path = path + accountId.toString(); cachePath = path; String uri = runtime.getString("cache-uri"); if (!uri.endsWith("/")) { uri = uri + "/"; } uri = uri + accountId.toString(); this.cache = cache(path, uri); this.downloader = downloader(); this.callInfo = params.getCallInfo(); this.conference = params.getConference(); } public static Props props(final ConfVoiceInterpreterParams params) { return new Props(new UntypedActorFactory() { @Override public Actor create() throws Exception { return new ConfVoiceInterpreter(params); } }); } private ActorRef cache(final String path, final String uri) { final Props props = new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public UntypedActor create() throws Exception { return new DiskCacheFactory(configuration).getDiskCache(path, uri); } }); return getContext().actorOf(props); } private 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); } private String e164(final String number) { final PhoneNumberUtil numbersUtil = PhoneNumberUtil.getInstance(); try { final PhoneNumber result = numbersUtil.parse(number, "US"); return numbersUtil.format(result, PhoneNumberFormat.E164); } catch (final NumberParseException ignored) { return number; } } private void invalidVerb(final Tag verb) { final ActorRef self = self(); // Get the next verb. final GetNextVerb next = new GetNextVerb(); parser.tell(next, self); } 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); } 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(); } @SuppressWarnings("unchecked") @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(" ********** ConfVoiceInterpreter's Current State: " + state.toString()); logger.info(" ********** ConfVoiceInterpreter's Processing Message: " + klass.getName()); } if (StartInterpreter.class.equals(klass)) { originalInterpreter = sender; fsm.transition(message, acquiringSynthesizerInfo); } else if (SpeechSynthesizerResponse.class.equals(klass)) { if (acquiringSynthesizerInfo.equals(state)) { fsm.transition(message, downloadingRcml); } else if (synthesizing.equals(state)) { final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message; if (response.succeeded()) { fsm.transition(message, caching); } else { fsm.transition(message, finished); } } } else if (MediaServerControllerResponse.class.equals(klass)) { if (acquiringConfMediaGroup.equals(state)) { fsm.transition(message, initializingConfMediaGroup); } } else if (DownloaderResponse.class.equals(klass)) { downloaderResponse = (DownloaderResponse) message; if (logger.isDebugEnabled()){ logger.debug("response succeeded " + downloaderResponse.succeeded() + ", statusCode " + downloaderResponse.get().getStatusCode()); } if (downloaderResponse.succeeded() && HttpStatus.SC_OK == downloaderResponse.get().getStatusCode()) { fsm.transition(message, acquiringConfMediaGroup); } else if (downloaderResponse.succeeded() && HttpStatus.SC_NOT_FOUND == downloaderResponse.get().getStatusCode()) { fsm.transition(message, notFound); } } else if (MediaGroupStateChanged.class.equals(klass)) { final MediaGroupStateChanged event = (MediaGroupStateChanged) message; if (MediaGroupStateChanged.State.ACTIVE == event.state()) { if (initializingConfMediaGroup.equals(state)) { fsm.transition(message, ready); } else if (ready.equals(state)) { if (play.equals(verb.name())) { fsm.transition(message, caching); } else if (say.equals(verb.name())) { fsm.transition(message, checkingCache); } else { invalidVerb(verb); } } } else if (MediaGroupStateChanged.State.INACTIVE == event.state()) { if (acquiringConfMediaGroup.equals(state)) { fsm.transition(message, initializingConfMediaGroup); } else if (!finished.equals(state)) { fsm.transition(message, finished); } } } else if (DiskCacheResponse.class.equals(klass)) { final DiskCacheResponse response = (DiskCacheResponse) message; if(logger.isInfoEnabled()){ logger.info("DiskCacheResponse " + response.succeeded() + " error=" + response.error()); } if (response.succeeded()) { if (caching.equals(state) || checkingCache.equals(state)) { if (play.equals(verb.name()) || say.equals(verb.name())) { fsm.transition(message, playing); } } } else { if (checkingCache.equals(state)) { fsm.transition(message, synthesizing); } else { fsm.transition(message, finished); } } } else if (Tag.class.equals(klass)) { verb = (Tag) message; if(logger.isInfoEnabled()) { logger.info("ConfVoiceInterpreter verb = " + verb.name()); } if (Verbs.dial.equals(verb.name())) originalInterpreter.tell(new Exception("Dial verb not supported"), source); if (play.equals(verb.name())) { fsm.transition(message, caching); } else if (say.equals(verb.name())) { fsm.transition(message, checkingCache); } else { invalidVerb(verb); } } else if (End.class.equals(klass)) { // TODO kill this interpreter and also the MediaGroup fsm.transition(message, finished); // originalInterpreter.tell(message, source); } else if (MediaGroupResponse.class.equals(klass)) { final MediaGroupResponse<String> response = (MediaGroupResponse<String>) message; if (response.succeeded()) { if (playing.equals(state)) { fsm.transition(message, ready); } } else { originalInterpreter.tell(message, source); } } else if (StopInterpreter.class.equals(klass)) { fsm.transition(message, finished); } else if (message instanceof ReceiveTimeout) { // TODO? } } private List<NameValuePair> parameters() { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); final String callSid = callInfo.sid().toString(); parameters.add(new BasicNameValuePair("CallSid", callSid)); final String accountSid = accountId.toString(); parameters.add(new BasicNameValuePair("AccountSid", accountSid)); final String from = e164(callInfo.from()); parameters.add(new BasicNameValuePair("From", from)); final String to = e164(callInfo.to()); parameters.add(new BasicNameValuePair("To", to)); // final String state = callState.toString(); // parameters.add(new BasicNameValuePair("CallStatus", state)); parameters.add(new BasicNameValuePair("ApiVersion", version)); final String direction = callInfo.direction(); parameters.add(new BasicNameValuePair("Direction", direction)); final String callerName = callInfo.fromName(); parameters.add(new BasicNameValuePair("CallerName", callerName)); final String forwardedFrom = callInfo.forwardedFrom(); parameters.add(new BasicNameValuePair("ForwardedFrom", forwardedFrom)); return parameters; } private 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); } private void postCleanup() { final ActorRef self = self(); final UntypedActorContext context = getContext(); context.stop(self); } private URI resolve(final URI base, final URI uri) { if (base.equals(uri)) { return uri; } else { if (!uri.isAbsolute()) { return base.resolve(uri); } else { return uri; } } } private 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()); } private ActorRef tts(final Configuration configuration) { final String classpath = configuration.getString("[@class]"); final Props props = 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); } }); return getContext().actorOf(props); } private abstract class AbstractAction implements Action { protected final ActorRef source; public AbstractAction(final ActorRef source) { super(); this.source = source; } } private final class AcquiringSpeechSynthesizerInfo extends AbstractAction { public AcquiringSpeechSynthesizerInfo(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final StartInterpreter request = (StartInterpreter) message; conference = request.resource(); synthesizer.tell(new GetSpeechSynthesizerInfo(), source); } } private final class AcquiringConferenceMediaGroup extends AbstractAction { public AcquiringConferenceMediaGroup(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { conference.tell(new CreateMediaGroup(), source); } } private final class InitializingConferenceMediaGroup extends AbstractAction { public InitializingConferenceMediaGroup(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { final MediaServerControllerResponse<ActorRef> response = (MediaServerControllerResponse<ActorRef>) message; conferenceMediaGroup = response.get(); conferenceMediaGroup.tell(new Observe(source), source); final StartMediaGroup request = new StartMediaGroup(); conferenceMediaGroup.tell(request, 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 { final Class<?> klass = message.getClass(); if (SpeechSynthesizerResponse.class.equals(klass)) { final SpeechSynthesizerResponse<SpeechSynthesizerInfo> response = (SpeechSynthesizerResponse<SpeechSynthesizerInfo>) message; synthesizerInfo = response.get(); // 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 Ready extends AbstractAction { public Ready(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { if (parser == null) { response = downloaderResponse.get(); 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("audio/wav") || type.contains("audio/wave") || type.contains("audio/x-wav")) { parser = parser("<Play>" + request.getUri() + "</Play>"); } else if (type.contains("text/plain")) { parser = parser("<Say>" + response.getContentAsString() + "</Say>"); } else { final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } } // Ask the parser for the next action to take. 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 { 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. conference.tell(new org.restcomm.connect.telephony.api.NotFound(), source); } } private final class CheckCache extends AbstractAction { public CheckCache(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } String hash = hash(verb); DiskCacheRequest request = new DiskCacheRequest(hash); if (logger.isInfoEnabled()) { logger.info("Checking cache for hash: " + hash); } cache.tell(request, source); } } private final class Caching extends AbstractAction { public Caching(final ActorRef source) { super(source); } @SuppressWarnings("unchecked") @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (SpeechSynthesizerResponse.class.equals(klass)) { final SpeechSynthesizerResponse<URI> response = (SpeechSynthesizerResponse<URI>) message; final DiskCacheRequest request = new DiskCacheRequest(response.get()); cache.tell(request, source); } else if (Tag.class.equals(klass) || MediaGroupStateChanged.class.equals(klass)) { if (Tag.class.equals(klass)) { verb = (Tag) message; } // Parse the URL. final String text = verb.text(); if (text != null && !text.isEmpty()) { // Try to cache the media. URI target = null; try { target = URI.create(text); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, text + " is an invalid URI."); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); sendMail(notification); final StopInterpreter stop = new StopInterpreter(); source.tell(stop, source); return; } final URI base = request.getUri(); final URI uri = resolve(base, target); final DiskCacheRequest request = new DiskCacheRequest(uri); cache.tell(request, source); } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } } } private final class Playing extends AbstractAction { public Playing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (DiskCacheResponse.class.equals(klass)) { // Issue 202: https://bitbucket.org/telestax/telscale-restcomm/issue/202 // Parse the loop attribute. int loop = Integer.MAX_VALUE; final Attribute attribute = verb.attribute("loop"); if (attribute != null) { final String number = attribute.value(); if (number != null && !number.isEmpty()) { try { loop = Integer.parseInt(number); } catch (final NumberFormatException ignored) { final NotificationsDao notifications = storage.getNotificationsDao(); Notification notification = null; if (say.equals(verb.name())) { notification = notification(WARNING_NOTIFICATION, 13510, loop + " is an invalid loop value."); notifications.addNotification(notification); } else if (play.equals(verb.name())) { notification = notification(WARNING_NOTIFICATION, 13410, loop + " is an invalid loop value."); notifications.addNotification(notification); } } } } final DiskCacheResponse response = (DiskCacheResponse) message; final Play play = new Play(response.get(), loop); conferenceMediaGroup.tell(play, source); } } } private String hash(Object message) { Map<String, String> details = getSynthesizeDetails(message); if (details == null) { if (logger.isInfoEnabled()) { logger.info("Cannot generate hash, details are null"); } return null; } String voice = details.get("voice"); String language = details.get("language"); String text = details.get("text"); return HashGenerator.hashMessage(voice, language, text); } private Map<String, String> getSynthesizeDetails(final Object message) { final Class<?> klass = message.getClass(); Map<String, String> details = new HashMap<String, String>(); if (Tag.class.equals(klass)) { verb = (Tag) message; } else { return null; } if (!say.equals(verb.name())) return null; // Parse the voice attribute. String voice = "man"; Attribute attribute = verb.attribute("voice"); if (attribute != null) { voice = attribute.value(); if (voice != null && !voice.isEmpty()) { if (!"man".equals(voice) && !"woman".equals(voice)) { final Notification notification = notification(WARNING_NOTIFICATION, 13511, voice + " is an invalid voice value."); final NotificationsDao notifications = storage.getNotificationsDao(); notifications.addNotification(notification); voice = "man"; } } else { voice = "man"; } } // Parse the language attribute. String language = "en"; attribute = verb.attribute("language"); if (attribute != null) { language = attribute.value(); if (language != null && !language.isEmpty()) { if (!synthesizerInfo.languages().contains(language)) { language = "en"; } } else { language = "en"; } } // Synthesize. String text = verb.text(); details.put("voice", voice); details.put("language", language); details.put("text", text); return details; } private final class Synthesizing extends AbstractAction { public Synthesizing(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } Map<String, String> details = getSynthesizeDetails(verb); if (details != null && !details.isEmpty()) { String voice = details.get("voice"); String language = details.get("language"); String text = details.get("text"); final SpeechSynthesizerRequest synthesize = new SpeechSynthesizerRequest(voice, language, text); synthesizer.tell(synthesize, source); } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } } private final class Redirecting extends AbstractAction { public Redirecting(final ActorRef source) { super(source); } @Override public void execute(final Object message) throws Exception { final Class<?> klass = message.getClass(); if (Tag.class.equals(klass)) { verb = (Tag) message; } final NotificationsDao notifications = storage.getNotificationsDao(); String method = "POST"; Attribute attribute = verb.attribute("method"); if (attribute != null) { method = attribute.value(); if (method != null && !method.isEmpty()) { if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) { final Notification notification = notification(WARNING_NOTIFICATION, 13710, method + " is not a valid HTTP method for <Redirect>"); notifications.addNotification(notification); method = "POST"; } } else { method = "POST"; } } final String text = verb.text(); if (text != null && !text.isEmpty()) { // Try to redirect. URI target = null; try { target = URI.create(text); } catch (final Exception exception) { final Notification notification = notification(ERROR_NOTIFICATION, 11100, text + " 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 = resolve(base, target); final List<NameValuePair> parameters = parameters(); request = new HttpRequestDescriptor(uri, method, parameters); downloader.tell(request, source); } else { // Ask the parser for the next action to take. final GetNextVerb next = new GetNextVerb(); parser.tell(next, source); } } } 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("Finished called for ConfVoiceInterpreter"); } final StopMediaGroup stop = new StopMediaGroup(); // Destroy the media group(s). if (conferenceMediaGroup != null) { conferenceMediaGroup.tell(stop, source); final DestroyWaitUrlConfMediaGroup destroy = new DestroyWaitUrlConfMediaGroup(conferenceMediaGroup); conference.tell(destroy, source); // conferenceMediaGroup = null; } // TODO should the dependencies be stopped here? // Stop the dependencies. final UntypedActorContext context = getContext(); if (mailerNotify != null) context.stop(mailerNotify); context.stop(downloader); context.stop(cache); context.stop(synthesizer); // Stop the interpreter. postCleanup(); } } @Override public void postStop() { // final StopMediaGroup stop = new StopMediaGroup(); // Destroy the media group(s). // if (conferenceMediaGroup != null) { // conferenceMediaGroup.tell(stop, source); // } // if (conference != null && !conference.isTerminated()) { // final DestroyWaitUrlConfMediaGroup destroy = new DestroyWaitUrlConfMediaGroup(conferenceMediaGroup); // conference.tell(destroy, source); // } // // if (conferenceMediaGroup != null && !conferenceMediaGroup.isTerminated()) // getContext().stop(conferenceMediaGroup); // // conferenceMediaGroup = null; super.postStop(); } }
44,298
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConfVoiceInterpreterParams.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/ConfVoiceInterpreterParams.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import akka.actor.ActorRef; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.DaoManager; import org.restcomm.connect.telephony.api.CallInfo; import java.net.URI; /** * @author [email protected] (Oleg Agafonov) */ public final class ConfVoiceInterpreterParams { private Configuration configuration; private Sid account; private String version; private URI url; private String method; private String emailAddress; private ActorRef conference; private DaoManager storage; private CallInfo callInfo; private ConfVoiceInterpreterParams(Configuration configuration, Sid account, String version, URI url, String method, String emailAddress, ActorRef conference, DaoManager storage, CallInfo callInfo) { this.configuration = configuration; this.account = account; this.version = version; this.url = url; this.method = method; this.emailAddress = emailAddress; this.conference = conference; this.storage = storage; this.callInfo = callInfo; } public Configuration getConfiguration() { return configuration; } public Sid getAccount() { return account; } public String getVersion() { return version; } public URI getUrl() { return url; } public String getMethod() { return method; } public String getEmailAddress() { return emailAddress; } public ActorRef getConference() { return conference; } public DaoManager getStorage() { return storage; } public CallInfo getCallInfo() { return callInfo; } public static class ConfVoiceInterpreterParamsBuilder { private Configuration configuration; private Sid account; private String version; private URI url; private String method; private String emailAddress; private ActorRef conference; private DaoManager storage; private CallInfo callInfo; public ConfVoiceInterpreterParamsBuilder setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } public ConfVoiceInterpreterParamsBuilder setAccount(Sid account) { this.account = account; return this; } public ConfVoiceInterpreterParamsBuilder setVersion(String version) { this.version = version; return this; } public ConfVoiceInterpreterParamsBuilder setUrl(URI url) { this.url = url; return this; } public ConfVoiceInterpreterParamsBuilder setMethod(String method) { this.method = method; return this; } public ConfVoiceInterpreterParamsBuilder setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; return this; } public ConfVoiceInterpreterParamsBuilder setConference(ActorRef conference) { this.conference = conference; return this; } public ConfVoiceInterpreterParamsBuilder setStorage(DaoManager storage) { this.storage = storage; return this; } public ConfVoiceInterpreterParamsBuilder setCallInfo(CallInfo callInfo) { this.callInfo = callInfo; return this; } public ConfVoiceInterpreterParams biuld() { return new ConfVoiceInterpreterParams(configuration, account, version, url, method, emailAddress, conference, storage, callInfo); } } }
4,588
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Fork.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/Fork.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class Fork { public Fork() { super(); } }
1,071
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StopInterpreter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/StopInterpreter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class StopInterpreter { private final boolean liveCallModification; public StopInterpreter(boolean liveCallModification) { this.liveCallModification = liveCallModification; } public StopInterpreter() { this(false); } public boolean isLiveCallModification() { return liveCallModification; } }
1,362
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StartInterpreter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/StartInterpreter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import akka.actor.ActorRef; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class StartInterpreter { private final ActorRef resource; public StartInterpreter(final ActorRef resource) { super(); this.resource = resource; } public ActorRef resource() { return resource; } }
1,287
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SIPOrganizationUtil.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/SIPOrganizationUtil.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import javax.servlet.sip.Address; import javax.servlet.sip.ServletParseException; import javax.servlet.sip.SipServletRequest; import javax.servlet.sip.SipURI; import org.apache.log4j.Logger; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.Organization; import org.restcomm.connect.dao.OrganizationsDao; public class SIPOrganizationUtil { private static Logger logger = Logger.getLogger(SIPOrganizationUtil.class); public static Sid getOrganizationSidBySipURIHost(OrganizationsDao orgDao, final SipURI sipURI) { if (logger.isDebugEnabled()) { logger.debug(String.format("getOrganizationSidBySipURIHost sipURI = %s", sipURI)); } final String organizationDomainName = sipURI.getHost(); Organization organization = orgDao.getOrganizationByDomainName(organizationDomainName); if (logger.isDebugEnabled()) { logger.debug(String.format("Org found = %s", organization)); } return organization == null ? null : organization.getSid(); } public static Sid searchOrganizationBySIPRequest(OrganizationsDao orgDao, SipServletRequest request) { //first try with requetURI Sid destinationOrganizationSid = getOrganizationSidBySipURIHost(orgDao, (SipURI) request.getRequestURI()); if (destinationOrganizationSid == null) { // try to get destinationOrganizationSid from toUri destinationOrganizationSid = getOrganizationSidBySipURIHost(orgDao, (SipURI) request.getTo().getURI()); } if (destinationOrganizationSid == null) { // try to get destinationOrganizationSid from Refer-To Address referAddress; try { referAddress = request.getAddressHeader("Refer-To"); if(referAddress != null){ destinationOrganizationSid = getOrganizationSidBySipURIHost(orgDao, (SipURI) referAddress.getURI()); } } catch (ServletParseException e) { logger.error(e); } } return destinationOrganizationSid; } }
3,003
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoiceInterpreterParams.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/VoiceInterpreterParams.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; 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 VoiceInterpreterParams { private Configuration configuration; private DaoManager storage; private ActorRef callManager; private ActorRef conferenceCenter; private ActorRef bridgeManager; private ActorRef smsService; 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 referTarget; private String emailAddress; private ActorRef monitoring; private String rcml; private long timeout; // IMS authentication private boolean asImsUa; private String imsUaLogin; private String imsUaPassword; private String transferor; private String transferee; private VoiceInterpreterParams(Configuration configuration, DaoManager storage, ActorRef callManager, ActorRef conferences, ActorRef bridgeManager, ActorRef smsService, Sid account, Sid phone, String version, URI url, String method, URI fallbackUrl, String fallbackMethod, URI statusCallback, String statusCallbackMethod, String referTarget, String emailAddress, ActorRef monitoring, String rcml, boolean asImsUa, String imsUaLogin, String imsUaPassword, String transferor, String transferee, long timeout) { this.configuration = configuration; this.storage = storage; this.callManager = callManager; this.conferenceCenter = conferences; this.bridgeManager = bridgeManager; this.smsService = smsService; 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.referTarget = referTarget; this.emailAddress = emailAddress; this.monitoring = monitoring; this.rcml = rcml; this.asImsUa = asImsUa; this.imsUaLogin = imsUaLogin; this.imsUaPassword = imsUaPassword; this.transferor = transferor; this.transferee = transferee; this.timeout = timeout; } public Configuration getConfiguration() { return configuration; } public DaoManager getStorage() { return storage; } public ActorRef getCallManager() { return callManager; } public ActorRef getConferenceCenter() { return conferenceCenter; } public ActorRef getBridgeManager() { return bridgeManager; } public ActorRef getSmsService() { return smsService; } 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 getReferTarget() { return referTarget; } public String getEmailAddress() { return emailAddress; } public ActorRef getMonitoring() { return monitoring; } public String getRcml() { return rcml; } public boolean isAsImsUa() { return asImsUa; } public String getImsUaLogin() { return imsUaLogin; } public String getImsUaPassword() { return imsUaPassword; } public String getTransferor() { return transferor; } public String getTransferee() { return transferee; } public long getTimeout() { return timeout; } public static final class Builder { private Configuration configuration; private DaoManager storage; private ActorRef callManager; private ActorRef conferenceCenter; private ActorRef bridgeManager; private ActorRef smsService; 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 referTarget; private String emailAddress; private ActorRef monitoring; private String rcml; private boolean asImsUa; private String imsUaLogin; private String imsUaPassword; private String transferor; private String transferee; private long timeout; public Builder() { } public Builder setConfiguration(Configuration configuration) { this.configuration = configuration; return this; } public Builder setStorage(DaoManager storage) { this.storage = storage; return this; } public Builder setCallManager(ActorRef callManager) { this.callManager = callManager; return this; } public Builder setConferenceCenter(ActorRef conferenceCenter) { this.conferenceCenter = conferenceCenter; return this; } public Builder setBridgeManager(ActorRef bridgeManager) { this.bridgeManager = bridgeManager; return this; } public Builder setSmsService(ActorRef smsService) { this.smsService = smsService; 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 setReferTarget(String referTarget) { this.referTarget = referTarget; return this; } public Builder setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; return this; } public Builder setMonitoring(ActorRef monitoring) { this.monitoring = monitoring; return this; } public Builder setRcml(String rcml) { this.rcml = rcml; return this; } public Builder setAsImsUa(boolean asImsUa) { this.asImsUa = asImsUa; return this; } public Builder setImsUaLogin(String imsUaLogin) { this.imsUaLogin = imsUaLogin; return this; } public Builder setImsUaPassword(String imsUaPassword) { this.imsUaPassword = imsUaPassword; return this; } public Builder setTransferor(String transferor) { this.transferor = transferor; return this; } public Builder setTransferee(String transferee) { this.transferee = transferee; return this; } public Builder setTimeout(long timeout) { this.timeout = timeout; return this; } public VoiceInterpreterParams build() { return new VoiceInterpreterParams(configuration, storage, callManager, conferenceCenter, bridgeManager, smsService, account, phone, version, url, method, fallbackUrl, fallbackMethod, statusCallback, statusCallbackMethod, referTarget, emailAddress, monitoring, rcml, asImsUa, imsUaLogin, imsUaPassword, transferor, transferee, timeout); } } }
9,972
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AudioPlayerInterpreter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/AudioPlayerInterpreter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; /** * @author [email protected] (Thomas Quintana) */ public final class AudioPlayerInterpreter extends RestcommUntypedActor { public AudioPlayerInterpreter() { super(); } @Override public void onReceive(final Object message) throws Exception { } }
1,216
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Nouns.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/Nouns.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Jean Deruelle) */ @Immutable public final class Nouns { public static final String client = "Client"; public static final String conference = "Conference"; public static final String number = "Number"; public static final String queue = "Queue"; public static final String uri = "Uri"; // https://bitbucket.org/telestax/telscale-restcomm/issue/132/implement-twilio-sip-out public static final String SIP = "Sip"; public static final String video = "Video"; public Nouns() { super(); } public static boolean isNoun(final String name) { if (client.equals(name)) return true; if (conference.equals(name)) return true; if (number.equals(name)) return true; if (queue.equals(name)) return true; if (uri.equals(name)) return true; if (SIP.equals(name)) return true; if (video.equals(name)) return true; return false; } }
2,051
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Attribute.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/Attribute.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class Attribute { private final String name; private final String value; public Attribute(final String name, final String value) { super(); this.name = name; this.value = value; } public String name() { return name; } public String value() { return value; } @Override public String toString() { return "Attribute{" + "name='" + name + '\'' + ", value='" + value + '\'' + '}'; } }
1,542
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ParserFailed.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/ParserFailed.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; /** * Created by gvagenas on 02/12/15. */ public class ParserFailed { private final Exception exception; private final String xml; public ParserFailed(final Exception exception, final String xml) { this.exception = exception; this.xml = xml; } public Exception getException() { return exception; } public String getXml() { return xml; } }
1,268
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TagPrinter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/TagPrinter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class TagPrinter { private static final int TAB_SPACES = 2; private TagPrinter() { super(); } public static String print(final Tag tag) { final StringBuilder buffer = new StringBuilder(); final Iterator<Tag> iterator = tag.iterator(); final Stack<Tag> parents = new Stack<Tag>(); // Use an iterator to print the tag and its children. while (iterator.hasNext()) { final Tag current = iterator.next(); // Close the previous tag's parent if the current tag doesn't share the same parent. if (!parents.isEmpty() && parents.peek() != current.parent()) { final Tag parent = parents.pop(); final int depth = getTagDepth(parent); appendClosingTag(buffer, depth, parent); } // Append the current tag to the buffer. final int depth = getTagDepth(current); appendOpeningTag(buffer, depth, current); if (!current.hasChildren()) { appendText(buffer, depth, current); appendClosingTag(buffer, depth, current); } else { parents.push(current); continue; } } // Close the root tag if necessary. if (!parents.isEmpty()) { final Tag parent = parents.pop(); final int depth = getTagDepth(parent); appendClosingTag(buffer, depth, parent); } return buffer.toString(); } private static void appendAttributes(final StringBuilder buffer, final Tag tag) { final List<Attribute> attributes = tag.attributes(); for (int index = 0; index < attributes.size(); index++) { final Attribute attribute = attributes.get(index); buffer.append(attribute.name()).append("=\"").append(attribute.value()).append("\""); if (index < (attributes.size() - 1)) { buffer.append(" "); } } } private static void appendOpeningTag(final StringBuilder buffer, final int tabs, final Tag tag) { appendTabs(buffer, tabs); buffer.append("<").append(tag.name()); if (tag.hasAttributes()) { buffer.append(" "); appendAttributes(buffer, tag); } if (tag.hasChildren() || tag.text() != null) { buffer.append(">"); } else { buffer.append("/>"); } buffer.append("\n"); } private static void appendClosingTag(final StringBuilder buffer, final int tabs, final Tag tag) { if (tag.hasChildren() || tag.text() != null) { appendTabs(buffer, tabs); buffer.append("</").append(tag.name()).append(">"); buffer.append("\n"); } } private static void appendTabs(final StringBuilder buffer, final int tabs) { final int spaces = tabs * TAB_SPACES; for (int counter = 0; counter < spaces; counter++) { buffer.append(" "); } } private static void appendText(final StringBuilder buffer, final int tabs, final Tag tag) { final String text = tag.text(); if (text != null && !text.isEmpty()) { final ByteArrayInputStream input = new ByteArrayInputStream(text.getBytes()); final BufferedReader reader = new BufferedReader(new InputStreamReader(input)); try { String line = reader.readLine(); while (line != null) { appendTabs(buffer, tabs + 1); buffer.append(line); buffer.append("\n"); line = reader.readLine(); } } catch (final IOException ignored) { // Will never happen. } } } private static int getTagDepth(final Tag tag) { int depth = 0; Tag parent = tag.parent(); while (parent != null) { depth += 1; parent = parent.parent(); } return depth; } }
5,307
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GetNextVerb.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/GetNextVerb.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class GetNextVerb { public GetNextVerb() { super(); } }
1,090
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
End.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/End.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class End { public End() { super(); } }
1,074
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TagIterator.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/TagIterator.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @NotThreadSafe public final class TagIterator implements Iterator<Tag> { private final Stack<Tag> stack; public TagIterator(final Tag tag) { super(); stack = new Stack<Tag>(); stack.push(tag); } @Override public boolean hasNext() { return stack.isEmpty() ? false : true; } @Override public Tag next() { if (stack.isEmpty()) { return null; } final Tag tag = stack.pop(); if (tag.hasChildren()) { final List<Tag> children = tag.children(); for (int index = (children.size() - 1); index >= 0; index--) { stack.push(children.get(index)); } } return tag; } @Override public void remove() { throw new UnsupportedOperationException("remove() is not a supported operation."); } }
1,949
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Parser.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.interpreter/src/main/java/org/restcomm/connect/interpreter/rcml/Parser.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.interpreter.rcml; import akka.actor.ActorRef; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import org.restcomm.connect.interpreter.rcml.domain.GatherAttributes; import javax.naming.LimitExceededException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Stack; import static javax.xml.stream.XMLStreamConstants.*; /** * @author [email protected] (Thomas Quintana) */ public final class Parser extends RestcommUntypedActor { private static Logger logger = Logger.getLogger(Parser.class); private Tag document; private Iterator<Tag> iterator; private String xml; private ActorRef sender; private Tag current; public Parser(final InputStream input, final String xml, final ActorRef sender) throws IOException { this(new InputStreamReader(input), xml, sender); } public Parser(final Reader reader, final String xml, final ActorRef sender) throws IOException { super(); if(logger.isDebugEnabled()){ logger.debug("About to create new Parser for xml: "+xml); } this.xml = xml; this.sender = sender; final XMLInputFactory inputs = XMLInputFactory.newInstance(); inputs.setProperty("javax.xml.stream.isCoalescing", true); XMLStreamReader stream = null; try { stream = inputs.createXMLStreamReader(reader); document = parse(stream); if (document == null) { throw new IOException("There was an error parsing the RCML."); } iterator = document.iterator(); } catch (final XMLStreamException exception) { if(logger.isInfoEnabled()) { logger.info("There was an error parsing the RCML for xml: "+xml+" excpetion: ", exception); } sender.tell(new ParserFailed(exception,xml), null); } finally { if (stream != null) { try { stream.close(); } catch (final XMLStreamException nested) { throw new IOException(nested); } } } } public Parser(final String xml, final ActorRef sender) throws IOException { this(new StringReader(xml.trim().replaceAll("&([^;]+(?!(?:\\w|;)))", "&amp;$1")), xml, sender); } private void end(final Stack<Tag.Builder> builders, final XMLStreamReader stream) { if (builders.size() > 1) { final Tag.Builder builder = builders.pop(); final Tag tag = builder.build(); builders.peek().addChild(tag); } } private void start(final Stack<Tag.Builder> builders, final XMLStreamReader stream) { final Tag.Builder builder = Tag.builder(); // Read the next tag. builder.setName(stream.getLocalName()); // Read the attributes. final int limit = stream.getAttributeCount(); for (int index = 0; index < limit; index++) { final String name = stream.getAttributeLocalName(index); final String value = stream.getAttributeValue(index).trim(); final Attribute attribute = new Attribute(name, value); builder.addAttribute(attribute); } builders.push(builder); } private Tag next() throws LimitExceededException{ if (iterator != null) { while (iterator.hasNext()) { final Tag tag = iterator.next(); if (Verbs.isVerb(tag)) { if (current != null && current.hasChildren()) { final List<Tag> children = current.children(); if (children.contains(tag)) { continue; } } if (tag.name().equals(Verbs.gather) && tag.hasAttribute(GatherAttributes.ATTRIBUTE_HINTS) && !StringUtils.isEmpty(tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value())) { String hotWords = tag.attribute(GatherAttributes.ATTRIBUTE_HINTS).value(); List<String> hintList = Arrays.asList(hotWords.split(",")); if (hintList.size() > 50) { throw new LimitExceededException("HotWords limit exceeded. There are more than 50 phrases"); } for (String hint : hintList) { if (hint.length() > 100) { throw new LimitExceededException("HotWords limit exceeded. Hint with more than 100 characters found"); } } } current = tag; return current; } } } else { if(logger.isInfoEnabled()){ logger.info("iterator is null"); } } return null; } private Tag parse(final XMLStreamReader stream) throws IOException, XMLStreamException { final Stack<Tag.Builder> builders = new Stack<Tag.Builder>(); while (stream.hasNext()) { switch (stream.next()) { case START_ELEMENT: { start(builders, stream); continue; } case CHARACTERS: { text(builders, stream); continue; } case END_ELEMENT: { end(builders, stream); continue; } case END_DOCUMENT: { if (!builders.isEmpty()) { return builders.pop().build(); } } } } return null; } @Override public void onReceive(final Object message) throws Exception { final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (GetNextVerb.class.equals(klass)) { try { final Tag verb = next(); if (verb != null) { sender.tell(verb, self); if (logger.isDebugEnabled()) { logger.debug("Parser, next verb: " + verb.toString()); } } else { final End end = new End(); sender.tell(end, sender); if (logger.isDebugEnabled()) { logger.debug("Parser, next verb: " + end.toString()); } } } catch (LimitExceededException e) { logger.warn(e.getMessage()); sender.tell(new ParserFailed(e, xml), null); } } } private void text(final Stack<Tag.Builder> builders, final XMLStreamReader stream) { if (!stream.isWhiteSpace()) { // Read the text. final Tag.Builder builder = builders.peek(); final String text = stream.getText().trim(); builder.setText(text); } } }
8,367
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z