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 |
---|---|---|---|---|---|---|---|---|---|---|---|
MybatisRegistrationsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisRegistrationsDao.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.dao.mybatis;
import static org.restcomm.connect.dao.DaoUtils.readBoolean;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
import static org.restcomm.connect.dao.DaoUtils.readInteger;
import static org.restcomm.connect.dao.DaoUtils.readSid;
import static org.restcomm.connect.dao.DaoUtils.readString;
import static org.restcomm.connect.dao.DaoUtils.writeDateTime;
import static org.restcomm.connect.dao.DaoUtils.writeSid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.RegistrationsDao;
import org.restcomm.connect.dao.entities.Registration;
import org.restcomm.connect.commons.dao.Sid;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (Jean Deruelle)
*/
@ThreadSafe
public final class MybatisRegistrationsDao implements RegistrationsDao {
private static final Logger logger = Logger.getLogger(MybatisRegistrationsDao.class);
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.RegistrationsDao.";
private final SqlSessionFactory sessions;
public MybatisRegistrationsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addRegistration(final Registration registration) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addRegistration", toMap(registration));
session.commit();
} finally {
session.close();
}
}
@Override
public List<Registration> getRegistrationsByLocation(String user, String location) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("user_name", user);
map.put("location", location.concat("%"));
final List<Map<String, Object>> results = session.selectList(namespace + "getRegistrationsByLocation", map);
final List<Registration> records = new ArrayList<Registration>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
records.add(toPresenceRecord(result));
}
if (!records.isEmpty()) {
Collections.sort(records);
}
}
return records;
} finally {
session.close();
}
}
@Override
public Registration getRegistration(String user, Sid organizationSid) {
final SqlSession session = sessions.openSession();
try {
// https://bitbucket.org/telestax/telscale-restcomm/issue/107/dial-fails-to-call-a-client-registered
// we get all registrations and sort them by latest updated date so that we target the device where the user last
// updated the registration
final Map<String, Object> map = new HashMap<String, Object>();
map.put("user_name", user);
map.put("organization_sid", writeSid(organizationSid));
final List<Map<String, Object>> results = session.selectList(namespace + "getRegistration", map);
final List<Registration> records = new ArrayList<Registration>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
records.add(toPresenceRecord(result));
}
if (records.isEmpty()) {
return null;
} else {
Collections.sort(records);
return records.get(0);
}
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public Registration getRegistrationByInstanceId(String user, String instanceId) {
final SqlSession session = sessions.openSession();
try {
// https://bitbucket.org/telestax/telscale-restcomm/issue/107/dial-fails-to-call-a-client-registered
// we get all registrations and sort them by latest updated date so that we target the device where the user last
// updated the registration
final Map<String, Object> map = new HashMap<String, Object>();
map.put("user_name", user);
map.put("instanceid", instanceId);
final List<Map<String, Object>> results = session.selectList(namespace + "getRegistrationByInstanceId", map);
final List<Registration> records = new ArrayList<Registration>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
records.add(toPresenceRecord(result));
}
if (records.isEmpty()) {
return null;
} else {
Collections.sort(records);
return records.get(0);
}
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Registration> getRegistrationsByInstanceId(String instanceId) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getRegistrationsByInstanceId", instanceId);
final List<Registration> records = new ArrayList<Registration>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
records.add(toPresenceRecord(result));
}
if (!records.isEmpty()) {
Collections.sort(records);
}
}
return records;
} finally {
session.close();
}
}
@Override
public List<Registration> getRegistrations(String user, Sid organizationSid) {
final SqlSession session = sessions.openSession();
try {
// https://bitbucket.org/telestax/telscale-restcomm/issue/107/dial-fails-to-call-a-client-registered
// we get all registrations and sort them by latest updated date so that we target the device where the user last
// updated the registration
final Map<String, Object> map = new HashMap<String, Object>();
map.put("user_name", user);
map.put("organization_sid", writeSid(organizationSid));
final List<Map<String, Object>> results = session.selectList(namespace + "getRegistration", map);
final List<Registration> records = new ArrayList<Registration>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
records.add(toPresenceRecord(result));
}
if (records.isEmpty()) {
return null;
} else {
Collections.sort(records);
return records;
}
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Registration> getRegistrations() {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getRegistrations");
final List<Registration> records = new ArrayList<Registration>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
records.add(toPresenceRecord(result));
}
}
return records;
} finally {
session.close();
}
}
@Override
public boolean hasRegistration(final Registration registration) {
final SqlSession session = sessions.openSession();
try {
final Integer result = (Integer) session.selectOne(namespace + "hasRegistration", toMap(registration));
return result != null && result > 0;
} finally {
session.close();
}
}
@Override
public void removeRegistration(final Registration registration) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "removeRegistration", toMap(registration));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateRegistration(final Registration registration) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateRegistration", toMap(registration));
session.commit();
} finally {
session.close();
}
}
private Map<String, Object> toMap(final Registration registration) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", writeSid(registration.getSid()));
map.put("instanceid", registration.getInstanceId());
map.put("date_created", writeDateTime(registration.getDateCreated()));
map.put("date_updated", writeDateTime(registration.getDateUpdated()));
map.put("date_expires", writeDateTime(registration.getDateExpires()));
map.put("address_of_record", registration.getAddressOfRecord());
map.put("display_name", registration.getDisplayName());
map.put("user_name", registration.getUserName());
map.put("location", registration.getLocation());
map.put("user_agent", registration.getUserAgent());
map.put("ttl", registration.getTimeToLive());
map.put("webrtc", registration.isWebRTC());
map.put("isLBPresent", registration.isLBPresent());
map.put("organization_sid", DaoUtils.writeSid(registration.getOrganizationSid()));
return map;
}
private Registration toPresenceRecord(final Map<String, Object> map) {
final Sid sid = readSid(map.get("sid"));
final String instanceId = readString(map.get("instanceid"));
final DateTime dateCreated = readDateTime(map.get("date_created"));
final DateTime dateUpdated = readDateTime(map.get("date_updated"));
final DateTime dateExpires = readDateTime(map.get("date_expires"));
final String addressOfRecord = readString(map.get("address_of_record"));
final String dislplayName = readString(map.get("display_name"));
final String userName = readString(map.get("user_name"));
final String location = readString(map.get("location"));
final String userAgent = readString(map.get("user_agent"));
final Integer timeToLive = readInteger(map.get("ttl"));
final Boolean webRTC = readBoolean(map.get("webrtc"));
Boolean isLBPresent = false;
if (readBoolean(map.get("isLBPresent")) != null) {
isLBPresent = readBoolean(map.get("isLBPresent"));
}
final Sid organizationSid = readSid(map.get("organization_sid"));
return new Registration(sid, instanceId, dateCreated, dateUpdated, dateExpires, addressOfRecord, dislplayName, userName, userAgent,
timeToLive, location, webRTC, isLBPresent, organizationSid);
}
}
| 12,695 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisAnnouncementsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisAnnouncementsDao.java | package org.restcomm.connect.dao.mybatis;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.AnnouncementsDao;
import org.restcomm.connect.dao.entities.Announcement;
import org.restcomm.connect.commons.dao.Sid;
/**
* @author <a href="mailto:[email protected]">George Vagenas</a>
*/
public final class MybatisAnnouncementsDao implements AnnouncementsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.AnnouncementsDao.";
private final SqlSessionFactory sessions;
public MybatisAnnouncementsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addAnnouncement(Announcement announcement) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addAnnouncement", toMap(announcement));
session.commit();
} finally {
session.close();
}
}
@Override
public Announcement getAnnouncement(Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getAnnouncement", sid.toString());
if (result != null) {
return toAnnouncement(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Announcement> getAnnouncements(Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getAnnouncements", accountSid.toString());
final List<Announcement> announcements = new ArrayList<Announcement>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
announcements.add(toAnnouncement(result));
}
}
return announcements;
} finally {
session.close();
}
}
@Override
public void removeAnnouncement(Sid sid) {
deleteAnnouncement(namespace + "removeAnnouncement", sid);
}
@Override
public void removeAnnouncements(Sid accountSid) {
deleteAnnouncement(namespace + "removeAnnouncements", accountSid);
}
private void deleteAnnouncement(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
private Map<String, Object> toMap(final Announcement announcement) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(announcement.getSid()));
map.put("date_created", DaoUtils.writeDateTime(announcement.getDateCreated()));
map.put("account_sid", DaoUtils.writeSid(announcement.getAccountSid()));
map.put("gender", announcement.getGender());
map.put("language", announcement.getLanguage());
map.put("text", announcement.getText());
map.put("uri", DaoUtils.writeUri(announcement.getUri()));
return map;
}
private Announcement toAnnouncement(final Map<String, Object> map) {
final Sid sid = DaoUtils.readSid(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final Sid accountSid = DaoUtils.readSid(map.get("account_sid"));
final String gender = DaoUtils.readString(map.get("gender"));
final String language = DaoUtils.readString(map.get("language"));
final String text = DaoUtils.readString(map.get("text"));
final URI uri = DaoUtils.readUri(map.get("uri"));
return new Announcement(sid, dateCreated, accountSid, gender, language, text, uri);
}
}
| 4,258 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisGeolocationDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisGeolocationDao.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.dao.mybatis;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
import static org.restcomm.connect.dao.DaoUtils.readInteger;
import static org.restcomm.connect.dao.DaoUtils.readSid;
import static org.restcomm.connect.dao.DaoUtils.readString;
import static org.restcomm.connect.dao.DaoUtils.readUri;
import static org.restcomm.connect.dao.DaoUtils.writeDateTime;
import static org.restcomm.connect.dao.DaoUtils.writeSid;
import static org.restcomm.connect.dao.DaoUtils.writeUri;
import static org.restcomm.connect.dao.DaoUtils.readGeolocationType;
import static org.restcomm.connect.dao.DaoUtils.readLong;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.dao.GeolocationDao;
import org.restcomm.connect.dao.entities.Geolocation;
import org.restcomm.connect.commons.dao.Sid;
/**
* @author <a href="mailto:[email protected]"> Fernando Mendioroz </a>
*
*/
public class MybatisGeolocationDao implements GeolocationDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.GeolocationDao.";
private final SqlSessionFactory sessions;
public MybatisGeolocationDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addGeolocation(Geolocation gl) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addGeolocation", toMap(gl));
session.commit();
} finally {
session.close();
}
}
@Override
public Geolocation getGeolocation(Sid sid) {
return getGeolocation(namespace + "getGeolocation", sid.toString());
}
private Geolocation getGeolocation(final String selector, final String parameter) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(selector, parameter);
if (result != null) {
return toGeolocation(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Geolocation> getGeolocations(Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getGeolocations", accountSid.toString());
final List<Geolocation> geolocations = new ArrayList<Geolocation>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
geolocations.add(toGeolocation(result));
}
}
return geolocations;
} finally {
session.close();
}
}
@Override
public void removeGeolocation(Sid sid) {
removeGeolocations(namespace + "removeGeolocation", sid);
}
@Override
public void removeGeolocations(final Sid accountSid) {
removeGeolocations(namespace + "removeGeolocations", accountSid);
}
private void removeGeolocations(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateGeolocation(Geolocation gl) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateGeolocation", toMap(gl));
session.commit();
} finally {
session.close();
}
}
private Map<String, Object> toMap(Geolocation gl) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", writeSid(gl.getSid()));
map.put("date_created", writeDateTime(gl.getDateCreated()));
map.put("date_updated", writeDateTime(gl.getDateUpdated()));
map.put("date_executed", writeDateTime(gl.getDateExecuted()));
map.put("account_sid", writeSid(gl.getAccountSid()));
map.put("source", gl.getSource());
map.put("device_identifier", gl.getDeviceIdentifier());
map.put("geolocation_type", gl.getGeolocationType());
map.put("response_status", gl.getResponseStatus());
map.put("cell_id", gl.getCellId());
map.put("location_area_code", gl.getLocationAreaCode());
map.put("mobile_country_code", gl.getMobileCountryCode());
map.put("mobile_network_code", gl.getMobileNetworkCode());
map.put("network_entity_address", gl.getNetworkEntityAddress());
map.put("age_of_location_info", gl.getAgeOfLocationInfo());
map.put("device_latitude", gl.getDeviceLatitude());
map.put("device_longitude", gl.getDeviceLongitude());
map.put("accuracy", gl.getAccuracy());
map.put("physical_address", gl.getPhysicalAddress());
map.put("internet_address", gl.getInternetAddress());
map.put("formatted_address", gl.getFormattedAddress());
map.put("location_timestamp", writeDateTime(gl.getLocationTimestamp()));
map.put("event_geofence_latitude", gl.getEventGeofenceLatitude());
map.put("event_geofence_longitude", gl.getEventGeofenceLongitude());
map.put("radius", gl.getRadius());
map.put("geolocation_positioning_type", gl.getGeolocationPositioningType());
map.put("last_geolocation_response", gl.getLastGeolocationResponse());
map.put("cause", gl.getCause());
map.put("api_version", gl.getApiVersion());
map.put("uri", writeUri(gl.getUri()));
return map;
}
private Geolocation toGeolocation(final Map<String, Object> map) {
final Sid sid = readSid(map.get("sid"));
final DateTime date_created = readDateTime(map.get("date_created"));
final DateTime date_updated = readDateTime(map.get("date_updated"));
final DateTime date_executed = readDateTime(map.get("date_executed"));
final Sid account_sid = readSid(map.get("account_sid"));
final String source = readString(map.get("source"));
final String device_identifier = readString(map.get("device_identifier"));
final Geolocation.GeolocationType geolocation_type = readGeolocationType(map.get("geolocation_type"));
final String response_status = readString(map.get("response_status"));
final String cell_id = readString(map.get("cell_id"));
final String location_area_code = readString(map.get("location_area_code"));
final Integer mobile_country_code = readInteger(map.get("mobile_country_code"));
final String mobile_network_code = readString(map.get("mobile_network_code"));
final Long network_entity_address = readLong(map.get("network_entity_address"));
final Integer age_of_location_info = readInteger(map.get("age_of_location_info"));
final String device_latitude = readString(map.get("device_latitude"));
final String device_longitude = readString(map.get("device_longitude"));
final Long accuracy = readLong(map.get("accuracy"));
final String physical_address = readString(map.get("physical_address"));
final String internet_address = readString(map.get("internet_address"));
final String formatted_address = readString(map.get("formatted_address"));
final DateTime location_timestamp = readDateTime(map.get("location_timestamp"));
final String event_geofence_latitude = readString(map.get("event_geofence_latitude"));
final String event_geofence_longitude = readString(map.get("event_geofence_longitude"));
final Long radius = readLong(map.get("radius"));
final String geolocation_positioning_type = readString(map.get("geolocation_positioning_type"));
final String last_geolocation_response = readString(map.get("last_geolocation_response"));
final String cause = readString(map.get("cause"));
final String api_version = readString(map.get("api_version"));
final URI uri = readUri(map.get("uri"));
return new Geolocation(sid, date_created, date_updated, date_executed, account_sid, source, device_identifier,
geolocation_type, response_status, cell_id, location_area_code, mobile_country_code, mobile_network_code,
network_entity_address, age_of_location_info, device_latitude, device_longitude, accuracy, physical_address,
internet_address, formatted_address, location_timestamp, event_geofence_latitude, event_geofence_longitude, radius,
geolocation_positioning_type, last_geolocation_response, cause, api_version, uri);
}
}
| 9,927 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisHttpCookiesDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisHttpCookiesDao.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.dao.mybatis;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.HttpCookiesDao;
import org.restcomm.connect.commons.dao.Sid;
/**
* @author [email protected] (Thomas Quintana)
*/
public final class MybatisHttpCookiesDao implements HttpCookiesDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.HttpCookiesDao.";
private final SqlSessionFactory sessions;
public MybatisHttpCookiesDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addCookie(final Sid sid, final Cookie cookie) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addCookie", toMap(sid, cookie));
session.commit();
} finally {
session.close();
}
}
@Override
public List<Cookie> getCookies(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getCookies", sid.toString());
final List<Cookie> cookies = new ArrayList<Cookie>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cookies.add(toCookie(result));
}
}
return cookies;
} finally {
session.close();
}
}
@Override
public boolean hasCookie(final Sid sid, final Cookie cookie) {
final SqlSession session = sessions.openSession();
try {
final Integer result = session.selectOne(namespace + "hasCookie", toMap(sid, cookie));
if (result > 0) {
return true;
} else {
return false;
}
} finally {
session.close();
}
}
@Override
public boolean hasExpiredCookies(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Integer result = session.selectOne(namespace + "hasExpiredCookies", sid.toString());
if (result > 0) {
return true;
} else {
return false;
}
} finally {
session.close();
}
}
@Override
public void removeCookies(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "removeCookies", sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void removeExpiredCookies(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "removeExpiredCookies", sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateCookie(final Sid sid, final Cookie cookie) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateCookie", toMap(sid, cookie));
session.commit();
} finally {
session.close();
}
}
private Cookie toCookie(final Map<String, Object> map) {
final String comment = DaoUtils.readString(map.get("comment"));
final String domain = DaoUtils.readString(map.get("domain"));
final Date expirationDate = (Date) map.get("expiration_date");
final String name = DaoUtils.readString(map.get("name"));
final String path = DaoUtils.readString(map.get("path"));
final String value = DaoUtils.readString(map.get("value"));
final int version = DaoUtils.readInteger(map.get("version"));
final BasicClientCookie cookie = new BasicClientCookie(name, value);
cookie.setComment(comment);
cookie.setDomain(domain);
cookie.setExpiryDate(expirationDate);
cookie.setPath(path);
cookie.setVersion(version);
return cookie;
}
private Map<String, Object> toMap(final Sid sid, final Cookie cookie) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(sid));
map.put("comment", cookie.getComment());
map.put("domain", cookie.getDomain());
map.put("expiration_date", cookie.getExpiryDate());
map.put("name", cookie.getName());
map.put("path", cookie.getPath());
map.put("value", cookie.getValue());
map.put("version", cookie.getVersion());
return map;
}
}
| 5,869 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisCallDetailRecordsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisCallDetailRecordsDao.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.dao.mybatis;
import java.math.BigDecimal;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.entities.CallDetailRecord;
import org.restcomm.connect.dao.entities.CallDetailRecordFilter;
/**
* @author [email protected] (Thomas Quintana)
*/
@ThreadSafe
public final class MybatisCallDetailRecordsDao implements CallDetailRecordsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.CallDetailRecordsDao.";
private final SqlSessionFactory sessions;
public MybatisCallDetailRecordsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addCallDetailRecord(final CallDetailRecord cdr) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addCallDetailRecord", toMap(cdr));
session.commit();
} finally {
session.close();
}
}
@Override
public CallDetailRecord getCallDetailRecord(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getCallDetailRecord", sid.toString());
if (result != null) {
return toCallDetailRecord(result);
} else {
return null;
}
} finally {
session.close();
}
}
// Issue 110
@Override
public Integer getTotalCallDetailRecords(CallDetailRecordFilter filter) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getTotalCallDetailRecordByUsingFilters", filter);
return total;
} finally {
session.close();
}
}
@Override
public Integer getInProgressCallsByClientName(String client) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getInProgressCallsByClientName", client);
return total;
} finally {
session.close();
}
}
@Override
public Integer getInProgressCallsByAccountSid(String accountSid) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getInProgressCallsByAccountSid", accountSid);
return total;
} finally {
session.close();
}
}
@Override
public Integer getTotalRunningCallDetailRecordsByConferenceSid(Sid conferenceSid){
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getTotalRunningCallDetailRecordsByConferenceSid", conferenceSid.toString());
return total;
} finally {
session.close();
}
}
// Issue 153: https://bitbucket.org/telestax/telscale-restcomm/issue/153
// Issue 110: https://bitbucket.org/telestax/telscale-restcomm/issue/110
@Override
public List<CallDetailRecord> getCallDetailRecords(CallDetailRecordFilter filter) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getCallDetailRecordByUsingFilters",
filter);
final List<CallDetailRecord> cdrs = new ArrayList<CallDetailRecord>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cdrs.add(toCallDetailRecord(result));
}
}
return cdrs;
} finally {
session.close();
}
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByAccountSid(final Sid accountSid) {
return getCallDetailRecords(namespace + "getCallDetailRecords", accountSid.toString());
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByRecipient(final String recipient) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByRecipient", recipient);
}
@Override
public List<CallDetailRecord> getCallDetailRecordsBySender(final String sender) {
return getCallDetailRecords(namespace + "getCallDetailRecordsBySender", sender);
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByStatus(final String status) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByStatus", status);
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByStartTime(final DateTime startTime) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByStartTime", startTime.toDate());
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByEndTime(final DateTime endTime) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByEndTime", endTime.toDate());
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByStarTimeAndEndTime(final DateTime endTime) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByStarTimeAndEndTime", endTime.toDate());
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByParentCall(final Sid parentCallSid) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByParentCall", parentCallSid.toString());
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByConferenceSid(final Sid conferenceSid) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByConferenceSid", conferenceSid.toString());
}
@Override
public List<CallDetailRecord> getRunningCallDetailRecordsByConferenceSid(final Sid conferenceSid) {
return getCallDetailRecords(namespace + "getRunningCallDetailRecordsByConferenceSid", conferenceSid.toString());
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByInstanceId(final Sid instanceId) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByInstanceId", instanceId.toString());
}
@Override
public List<CallDetailRecord> getInCompleteCallDetailRecordsByInstanceId(Sid instanceId) {
return getCallDetailRecords(namespace + "getInCompleteCallDetailRecordsByInstanceId", instanceId.toString());
}
@Override
public List<CallDetailRecord> getCallDetailRecordsByMsId(String msId) {
return getCallDetailRecords(namespace + "getCallDetailRecordsByMsId", msId);
}
@Override
public Double getAverageCallDurationLast24Hours(Sid instanceId) throws ParseException {
DateTime now = DateTime.now();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd");
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
Date today = formatter.parse(now.toString(fmt));
Map<String, Object> params = new HashMap<String, Object>();
params.put("instanceid", instanceId.toString());
params.put("startTime", today);
final SqlSession session = sessions.openSession();
try {
final Double total = session.selectOne(namespace + "getAverageCallDurationLast24Hours", params);
return total;
} finally {
session.close();
}
}
@Override
public Double getAverageCallDurationLastHour(Sid instanceId) throws ParseException {
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:00:00");
String hour = formatter.format(Calendar.getInstance().getTime());
Date lastHour = formatter.parse(hour);
Map<String, Object> params = new HashMap<String, Object>();
params.put("instanceid", instanceId.toString());
params.put("startTime", lastHour);
final SqlSession session = sessions.openSession();
try {
final Double total = session.selectOne(namespace + "getAverageCallDurationLastHour", params);
return total;
} finally {
session.close();
}
}
private List<CallDetailRecord> getCallDetailRecords(final String selector, Object input) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(selector, input);
final List<CallDetailRecord> cdrs = new ArrayList<CallDetailRecord>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cdrs.add(toCallDetailRecord(result));
}
}
return cdrs;
} finally {
session.close();
}
}
@Override
public void removeCallDetailRecord(final Sid sid) {
removeCallDetailRecords(namespace + "removeCallDetailRecord", sid);
}
@Override
public void removeCallDetailRecords(final Sid accountSid) {
removeCallDetailRecords(namespace + "removeCallDetailRecords", accountSid);
}
private void removeCallDetailRecords(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateCallDetailRecord(final CallDetailRecord cdr) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateCallDetailRecord", toMap(cdr));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateInCompleteCallDetailRecordsToCompletedByInstanceId(Sid instanceId) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateInCompleteCallDetailRecordsToCompletedByInstanceId", instanceId.toString());
session.commit();
} finally {
session.close();
}
}
private CallDetailRecord toCallDetailRecord(final Map<String, Object> map) {
final String msId = DaoUtils.readString(map.get("ms_id"));
final Sid sid = DaoUtils.readSid(map.get("sid"));
final String instanceId = DaoUtils.readString(map.get("instanceid"));
final Sid parentCallSid = DaoUtils.readSid(map.get("parent_call_sid"));
final Sid conferenceSid = DaoUtils.readSid(map.get("conference_sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final Sid accountSid = DaoUtils.readSid(map.get("account_sid"));
final String to = DaoUtils.readString(map.get("recipient"));
final String from = DaoUtils.readString(map.get("sender"));
final Sid phoneNumberSid = DaoUtils.readSid(map.get("phone_number_sid"));
final String status = DaoUtils.readString(map.get("status"));
final DateTime startTime = DaoUtils.readDateTime(map.get("start_time"));
final DateTime endTime = DaoUtils.readDateTime(map.get("end_time"));
final Integer duration = DaoUtils.readInteger(map.get("duration"));
final Integer ringDuration = DaoUtils.readInteger(map.get("ring_duration"));
final BigDecimal price = DaoUtils.readBigDecimal(map.get("price"));
final Currency priceUnit = DaoUtils.readCurrency(map.get("price_unit"));
final String direction = DaoUtils.readString(map.get("direction"));
final String answeredBy = DaoUtils.readString(map.get("answered_by"));
final String apiVersion = DaoUtils.readString(map.get("api_version"));
final String forwardedFrom = DaoUtils.readString(map.get("forwarded_from"));
final String callerName = DaoUtils.readString(map.get("caller_name"));
final URI uri = DaoUtils.readUri(map.get("uri"));
final String callPath = DaoUtils.readString(map.get("call_path"));
final Boolean muted = DaoUtils.readBoolean(map.get("muted"));
final Boolean startConferenceOnEnter = DaoUtils.readBoolean(map.get("start_conference_on_enter"));
final Boolean endConferenceOnExit = DaoUtils.readBoolean(map.get("end_conference_on_exit"));
final Boolean onHold = DaoUtils.readBoolean(map.get("on_hold"));
return new CallDetailRecord(sid, instanceId, parentCallSid, conferenceSid, dateCreated, dateUpdated, accountSid, to, from, phoneNumberSid, status,
startTime, endTime, duration, price, priceUnit, direction, answeredBy, apiVersion, forwardedFrom, callerName,
uri, callPath, ringDuration, muted, startConferenceOnEnter, endConferenceOnExit, onHold, msId);
}
private Map<String, Object> toMap(final CallDetailRecord cdr) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(cdr.getSid()));
map.put("instanceid", cdr.getInstanceId());
map.put("parent_call_sid", DaoUtils.writeSid(cdr.getParentCallSid()));
map.put("conference_sid", DaoUtils.writeSid(cdr.getConferenceSid()));
map.put("date_created", DaoUtils.writeDateTime(cdr.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(cdr.getDateUpdated()));
map.put("account_sid", DaoUtils.writeSid(cdr.getAccountSid()));
map.put("to", cdr.getTo());
map.put("from", cdr.getFrom());
map.put("phone_number_sid", DaoUtils.writeSid(cdr.getPhoneNumberSid()));
map.put("status", cdr.getStatus());
map.put("start_time", DaoUtils.writeDateTime(cdr.getStartTime()));
map.put("end_time", DaoUtils.writeDateTime(cdr.getEndTime()));
map.put("duration", cdr.getDuration());
map.put("ring_duration", cdr.getRingDuration());
map.put("price", DaoUtils.writeBigDecimal(cdr.getPrice()));
map.put("direction", cdr.getDirection());
map.put("answered_by", cdr.getAnsweredBy());
map.put("api_version", cdr.getApiVersion());
map.put("forwarded_from", cdr.getForwardedFrom());
map.put("caller_name", cdr.getCallerName());
map.put("uri", DaoUtils.writeUri(cdr.getUri()));
map.put("call_path", cdr.getCallPath());
map.put("muted", cdr.isMuted());
map.put("start_conference_on_enter", cdr.isStartConferenceOnEnter());
map.put("end_conference_on_exit", cdr.isEndConferenceOnExit());
map.put("on_hold", cdr.isOnHold());
map.put("ms_id", cdr.getMsId());
return map;
}
}
| 16,254 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisInstanceIdDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisInstanceIdDao.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.dao.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.InstanceIdDao;
import org.restcomm.connect.dao.entities.InstanceId;
import org.restcomm.connect.commons.dao.Sid;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
import static org.restcomm.connect.dao.DaoUtils.readSid;
import static org.restcomm.connect.dao.DaoUtils.readString;
import static org.restcomm.connect.dao.DaoUtils.writeDateTime;
import static org.restcomm.connect.dao.DaoUtils.writeSid;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
@ThreadSafe
public class MybatisInstanceIdDao implements InstanceIdDao{
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.InstanceIdDao.";
private final SqlSessionFactory sessions;
public MybatisInstanceIdDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public InstanceId getInstanceId() {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace+"getInstanceId");
if (result != null) {
return toInstanceId(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public InstanceId getInstanceIdByHost(String host) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace+"getInstanceIdByHost", host);
if (result != null) {
return toInstanceId(result);
} else {
return null;
}
} catch (Exception e) {
session.close();
return getInstanceId();
} finally {
session.close();
}
}
@Override
public void addInstancecId(InstanceId instanceId) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addInstanceId", toMap(instanceId));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateInstanceId(InstanceId instanceId) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateInstanceId", toMap(instanceId));
session.commit();
} finally {
session.close();
}
}
private InstanceId toInstanceId(Map<String, Object> map) {
final Sid sid = readSid(map.get("instance_id"));
String host = readString(map.get("host"));
if (host == null || host.isEmpty()) {
try {
host = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {}
}
final DateTime dateCreated = readDateTime(map.get("date_created"));
final DateTime dateUpdated = readDateTime(map.get("date_updated"));
return new InstanceId(sid, host, dateCreated, dateUpdated);
}
private Map<String, Object> toMap(final InstanceId instanceId) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("instance_id", writeSid(instanceId.getId()));
String host = instanceId.getHost();
if (host == null || host.isEmpty()) {
try {
host = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {}
}
map.put("host", host);
map.put("date_created", writeDateTime(instanceId.getDateCreated()));
map.put("date_updated", writeDateTime(instanceId.getDateUpdated()));
return map;
}
}
| 4,983 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisUsageDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisUsageDao.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.dao.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.UsageDao;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.entities.Usage;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import java.math.BigDecimal;
import java.net.URI;
import java.sql.Date;
import java.util.Currency;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* @author [email protected] (Alexandre Mendonca)
*/
@ThreadSafe
public final class MybatisUsageDao implements UsageDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.UsageDao.";
private final SqlSessionFactory sessions;
public MybatisUsageDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public List<Usage> getUsage(final Sid accountSid, String uri) {
return getUsageCalls(accountSid, null, null, null, uri, "getAllTimeCalls");
}
@Override
public List<Usage> getUsageDaily(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate, String uri) {
return getUsageCalls(accountSid, category, startDate, endDate, uri, "getDailyCalls");
}
@Override
public List<Usage> getUsageMonthly(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate, String uri) {
return getUsageCalls(accountSid, category, startDate, endDate, uri, "getMonthlyCalls");
}
@Override
public List<Usage> getUsageYearly(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate, String uri) {
return getUsageCalls(accountSid, category, startDate, endDate, uri, "getYearlyCalls");
}
@Override
public List<Usage> getUsageAllTime(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate, String uri) {
return getUsageCalls(accountSid, category, startDate, endDate, uri, "getAllTimeCalls");
}
@Override
public List<Usage> getUsage(final Sid accountSid) {
return getUsage(accountSid, "");
}
@Override
public List<Usage> getUsageDaily(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) {
return getUsageDaily(accountSid, category, startDate, endDate, "");
}
@Override
public List<Usage> getUsageMonthly(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) {
return getUsageMonthly(accountSid, category, startDate, endDate, "");
}
@Override
public List<Usage> getUsageYearly(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) {
return getUsageYearly(accountSid, category, startDate, endDate, "");
}
@Override
public List<Usage> getUsageAllTime(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) {
return getUsageAllTime(accountSid, category, startDate, endDate, "");
}
/*
@Override
public List<Usage> getUsageToday(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) {
return getUsageCalls(accountSid, category, startDate, endDate, "getTodayCalls");
}
@Override
public List<Usage> getUsageYesterday(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) {
return getUsageCalls(accountSid, category, startDate, endDate, "getYesterdayCalls");
}
@Override
public List<Usage> getUsageThisMonth(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) {
return getUsageCalls(accountSid, category, startDate, endDate, "getThisMonthCalls");
}
@Override
public List<Usage> getUsageLastMonth(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate) {
return getUsageCalls(accountSid, category, startDate, endDate, "getLastMonthCalls");
}
*/
private List<Usage> getUsageCalls(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate, final String queryName) {
return getUsageCalls(accountSid, category, startDate, endDate, "", queryName);
}
private List<Usage> getUsageCalls(final Sid accountSid, Usage.Category category, DateTime startDate, DateTime endDate, String uri, final String queryName) {
long startTime = System.currentTimeMillis();
final SqlSession session = sessions.openSession();
Map<String, Object> params = new HashMap<String, Object>();
params.put("sid", accountSid.toString());
params.put("startDate", new Date(startDate.getMillis()));
params.put("endDate", new Date(endDate.getMillis()));
params.put("uri", uri);
fillParametersByCategory(category, params);
try {
final List<Map<String, Object>> results = session.selectList(namespace + queryName, params);
final List<Usage> usageRecords = new ArrayList<Usage>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
usageRecords.add(toUsageRecord(accountSid, result));
}
}
return usageRecords;
} finally {
session.close();
}
}
private Usage toUsageRecord(final Sid accountSid, final Map<String, Object> map) {
final Usage.Category category = Usage.Category.CALLS;
final String description = "Total Calls";
final DateTime startDate = DateTimeFormat.forPattern("yyyyy-MM-dd").parseDateTime(map.get("start_date").toString());
final DateTime endDate = DateTimeFormat.forPattern("yyyyy-MM-dd").parseDateTime(map.get("end_date").toString());
final Long usage = DaoUtils.readLong(map.get("usage"));
final String usageUnit = "minutes";
final Long count = DaoUtils.readLong(map.get("count"));
final String countUnit = "calls";
/* FIXME: readBigDecimal should take Double instead of String ? */
final BigDecimal price = DaoUtils.readBigDecimal(map.get("price").toString());
final Currency priceUnit = Currency.getInstance(Locale.US);
final URI uri = DaoUtils.readUri(map.get("uri"));
return new Usage(category, description, accountSid, startDate, endDate, usage, usageUnit, count, countUnit, price, priceUnit, uri);
}
private Map<String, Object> fillParametersByCategory(Usage.Category category, Map<String, Object> params) {
// FIXME: handle no category, meaning all
if (category == null) category = Usage.Category.CALLS;
params.put("category", category.toString());
switch (category) {
case CALLS:
case CALLS_INBOUND:
case CALLS_INBOUND_LOCAL:
case CALLS_INBOUND_TOLLFREE:
case CALLS_OUTBOUND:
case CALLS_CLIENT:
case CALLS_SIP:
params.put("tableName", "restcomm_call_detail_records");
//NB: #1690 display duration as minutes rounded up
params.put("usageExprPre", "COALESCE( CEIL(SUM(");
params.put("usageExprCol", "duration");
params.put("usageExprSuf", ") /60),0) ");
break;
case SMS:
case SMS_INBOUND:
case SMS_INBOUND_SHORTCODE:
case SMS_INBOUND_LONGCODE:
case SMS_OUTBOUND:
case SMS_OUTBOUND_SHORTCODE:
case SMS_OUTBOUND_LONGCODE:
params.put("tableName", "restcomm_sms_messages");
params.put("usageExprPre", "COUNT(");
params.put("usageExprCol", "sid");
params.put("usageExprSuf", ")");
break;
case PHONENUMBERS:
case PHONENUMBERS_TOLLFREE:
case PHONENUMBERS_LOCAL:
case SHORTCODES:
case SHORTCODES_VANITY:
case SHORTCODES_RANDOM:
case SHORTCODES_CUSTOMEROWNED:
case CALLERIDLOOKUPS:
case RECORDINGS:
case TRANSCRIPTIONS:
case RECORDINGSTORAGE:
case TOTALPRICE:
default:
params.put("tableName", "restcomm_call_detail_records");
//NB: #1690 display duration as minutes rounded up
params.put("usageExprPre", "COALESCE( CEIL(SUM(");
params.put("usageExprCol", "duration");
params.put("usageExprSuf", ") /60),0)");
break;
}
return params;
}
}
| 9,047 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisApplicationsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisApplicationsDao.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.dao.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.ApplicationsDao;
import org.restcomm.connect.dao.entities.Application;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.entities.ApplicationNumberSummary;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.restcomm.connect.dao.DaoUtils.readApplicationKind;
import static org.restcomm.connect.dao.DaoUtils.readBoolean;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
import static org.restcomm.connect.dao.DaoUtils.readSid;
import static org.restcomm.connect.dao.DaoUtils.readString;
import static org.restcomm.connect.dao.DaoUtils.readUri;
import static org.restcomm.connect.dao.DaoUtils.writeApplicationKind;
import static org.restcomm.connect.dao.DaoUtils.writeDateTime;
import static org.restcomm.connect.dao.DaoUtils.writeSid;
import static org.restcomm.connect.dao.DaoUtils.writeUri;
/**
* @author [email protected] (Thomas Quintana)
*/
@ThreadSafe
public final class MybatisApplicationsDao implements ApplicationsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.ApplicationsDao.";
private final SqlSessionFactory sessions;
public MybatisApplicationsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addApplication(final Application application) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addApplication", toMap(application));
session.commit();
} finally {
session.close();
}
}
@Override
public Application getApplication(final Sid sid) {
Application application = getApplication(namespace + "getApplication", sid.toString());
return application;
}
@Override
public Application getApplication(final String friendlyName) {
return getApplication(namespace + "getApplicationByFriendlyName", friendlyName);
}
private Application getApplication(final String selector, final String parameter) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(selector, parameter);
if (result != null) {
return toApplication(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Application> getApplicationsWithNumbers(Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getApplicationsAndNumbers", accountSid.toString());
final List<Application> applications = new ArrayList<Application>();
if (results != null && !results.isEmpty()) {
Application previousApp = null;
Application app = null;
for (final Map<String, Object> result : results) {
app = toApplication(result);
if (previousApp != null && previousApp.getSid().equals(app.getSid()) )
app = previousApp;
// if there is a number bound to this application populate the latter with the number details
if (result.get("num_sid") != null) {
populateApplicationWithNumber(app, result, "num_");
}
if (previousApp == null || !previousApp.getSid().equals(app.getSid())) {
// is this is a new application in the result map add it to the list. Remember, the same app can be returned many times if it's related to many numbers
applications.add(app);
}
previousApp = app;
}
}
return applications;
} finally {
session.close();
}
}
@Override
public List<Application> getApplications(final Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getApplications", accountSid.toString());
final List<Application> applications = new ArrayList<Application>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
applications.add(toApplication(result));
}
}
return applications;
} finally {
session.close();
}
}
@Override
public void removeApplication(final Sid sid) {
removeApplications("removeApplication", sid);
}
@Override
public void removeApplications(final Sid accountSid) {
removeApplications("removeApplications", accountSid);
}
private void removeApplications(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateApplication(final Application application) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateApplication", toMap(application));
session.commit();
} finally {
session.close();
}
}
private Application toApplication(final Map<String, Object> map) {
final Sid sid = readSid(map.get("sid"));
final DateTime dateCreated = readDateTime(map.get("date_created"));
final DateTime dateUpdated = readDateTime(map.get("date_updated"));
final String friendlyName = readString(map.get("friendly_name"));
final Sid accountSid = readSid(map.get("account_sid"));
final String apiVersion = readString(map.get("api_version"));
final Boolean hasVoiceCallerIdLookup = readBoolean(map.get("voice_caller_id_lookup"));
final URI uri = readUri(map.get("uri"));
final URI rcmlUrl = readUri(map.get("rcml_url"));
final Application.Kind kind = readApplicationKind(map.get("kind"));
return new Application(sid, dateCreated, dateUpdated, friendlyName, accountSid, apiVersion, hasVoiceCallerIdLookup,
uri, rcmlUrl, kind);
}
/**
* Populates application.numbers field with information of one or more numbers. The 'numbers' list is created if
* already null and an IncomingPhoneNumber is added into it based on information from the map. Invoking the same method
* several times to add more numbers to the same list is possible.
*
* @param application
* @param map
* @param field_prefix
* @return
*/
private void populateApplicationWithNumber(Application application, final Map<String, Object> map, String field_prefix) {
// first create the number
ApplicationNumberSummary number = new ApplicationNumberSummary(
readString(map.get(field_prefix + "sid")),
readString(map.get(field_prefix + "friendly_name")),
readString(map.get(field_prefix + "phone_number")),
readString(map.get(field_prefix + "voice_application_sid")),
readString(map.get(field_prefix + "sms_application_sid")),
readString(map.get(field_prefix + "ussd_application_sid")),
readString(map.get(field_prefix + "refer_application_sid"))
);
List<ApplicationNumberSummary> numbers = application.getNumbers();
if (numbers == null) {
numbers = new ArrayList<ApplicationNumberSummary>();
application.setNumbers(numbers);
}
numbers.add(number);
}
private Map<String, Object> toMap(final Application application) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", writeSid(application.getSid()));
map.put("date_created", writeDateTime(application.getDateCreated()));
map.put("date_updated", writeDateTime(application.getDateUpdated()));
map.put("friendly_name", application.getFriendlyName());
map.put("account_sid", writeSid(application.getAccountSid()));
map.put("api_version", application.getApiVersion());
map.put("voice_caller_id_lookup", application.hasVoiceCallerIdLookup());
map.put("uri", writeUri(application.getUri()));
map.put("rcml_url", writeUri(application.getRcmlUrl()));
map.put("kind", writeApplicationKind(application.getKind()));
return map;
}
}
| 9,938 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisOutgoingCallerIdsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisOutgoingCallerIdsDao.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.dao.mybatis;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.OutgoingCallerIdsDao;
import org.restcomm.connect.dao.entities.OutgoingCallerId;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
/**
* @author [email protected] (Thomas Quintana)
*/
@ThreadSafe
public final class MybatisOutgoingCallerIdsDao implements OutgoingCallerIdsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.OutgoingCallerIdsDao.";
private final SqlSessionFactory sessions;
public MybatisOutgoingCallerIdsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addOutgoingCallerId(final OutgoingCallerId outgoingCallerId) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addOutgoingCallerId", toMap(outgoingCallerId));
session.commit();
} finally {
session.close();
}
}
@Override
public OutgoingCallerId getOutgoingCallerId(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getOutgoingCallerId", sid.toString());
if (result != null) {
return toOutgoingCallerId(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<OutgoingCallerId> getOutgoingCallerIds(final Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getOutgoingCallerIds",
accountSid.toString());
final List<OutgoingCallerId> outgoingCallerIds = new ArrayList<OutgoingCallerId>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
outgoingCallerIds.add(toOutgoingCallerId(result));
}
}
return outgoingCallerIds;
} finally {
session.close();
}
}
@Override
public void removeOutgoingCallerId(final Sid sid) {
removeOutgoingCallerIds(namespace + "removeOutgoingCallerId", sid);
}
@Override
public void removeOutgoingCallerIds(final Sid accountSid) {
removeOutgoingCallerIds(namespace + "removeOutgoingCallerIds", accountSid);
}
private void removeOutgoingCallerIds(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateOutgoingCallerId(final OutgoingCallerId outgoingCallerId) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateOutgoingCallerId", toMap(outgoingCallerId));
session.commit();
} finally {
session.close();
}
}
private Map<String, Object> toMap(final OutgoingCallerId outgoingCallerId) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(outgoingCallerId.getSid()));
map.put("date_created", DaoUtils.writeDateTime(outgoingCallerId.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(outgoingCallerId.getDateUpdated()));
map.put("friendly_name", outgoingCallerId.getFriendlyName());
map.put("account_sid", DaoUtils.writeSid(outgoingCallerId.getAccountSid()));
map.put("phone_number", outgoingCallerId.getPhoneNumber());
map.put("uri", DaoUtils.writeUri(outgoingCallerId.getUri()));
return map;
}
private OutgoingCallerId toOutgoingCallerId(final Map<String, Object> map) {
final Sid sid = DaoUtils.readSid(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final String friendlyName = DaoUtils.readString(map.get("friendly_name"));
final Sid accountSid = DaoUtils.readSid(map.get("account_sid"));
final String phoneNumber = DaoUtils.readString(map.get("phone_number"));
final URI uri = DaoUtils.readUri(map.get("uri"));
return new OutgoingCallerId(sid, dateCreated, dateUpdated, friendlyName, accountSid, phoneNumber, uri);
}
}
| 5,834 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisDaoManager.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisDaoManager.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.dao.mybatis;
import org.apache.commons.configuration.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.AccountsDao;
import org.restcomm.connect.dao.AnnouncementsDao;
import org.restcomm.connect.dao.ApplicationsDao;
import org.restcomm.connect.dao.AvailablePhoneNumbersDao;
import org.restcomm.connect.dao.CallDetailRecordsDao;
import org.restcomm.connect.dao.ClientsDao;
import org.restcomm.connect.dao.ConferenceDetailRecordsDao;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.dao.ExtensionsConfigurationDao;
import org.restcomm.connect.dao.GatewaysDao;
import org.restcomm.connect.dao.GeolocationDao;
import org.restcomm.connect.dao.HttpCookiesDao;
import org.restcomm.connect.dao.IncomingPhoneNumbersDao;
import org.restcomm.connect.dao.InstanceIdDao;
import org.restcomm.connect.dao.MediaResourceBrokerDao;
import org.restcomm.connect.dao.MediaServersDao;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.OrganizationsDao;
import org.restcomm.connect.dao.OutgoingCallerIdsDao;
import org.restcomm.connect.dao.ProfileAssociationsDao;
import org.restcomm.connect.dao.ProfilesDao;
import org.restcomm.connect.dao.RecordingsDao;
import org.restcomm.connect.dao.RegistrationsDao;
import org.restcomm.connect.dao.ShortCodesDao;
import org.restcomm.connect.dao.SmsMessagesDao;
import org.restcomm.connect.dao.TranscriptionsDao;
import org.restcomm.connect.dao.UsageDao;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.util.Properties;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisDaoManager implements DaoManager {
private Configuration configuration;
private Configuration runtimeConfiguration;
private AccountsDao accountsDao;
private ApplicationsDao applicationsDao;
private AvailablePhoneNumbersDao availablePhoneNumbersDao;
private CallDetailRecordsDao callDetailRecordsDao;
private ConferenceDetailRecordsDao conferenceDetailRecordsDao;
private ClientsDao clientsDao;
private HttpCookiesDao httpCookiesDao;
private IncomingPhoneNumbersDao incomingPhoneNumbersDao;
private NotificationsDao notificationsDao;
private OutgoingCallerIdsDao outgoingCallerIdsDao;
private RegistrationsDao presenceRecordsDao;
private RecordingsDao recordingsDao;
private ShortCodesDao shortCodesDao;
private SmsMessagesDao smsMessagesDao;
private UsageDao usageDao;
private TranscriptionsDao transcriptionsDao;
private GatewaysDao gatewaysDao;
private AnnouncementsDao announcementsDao;
private InstanceIdDao instanceIdDao;
private MediaServersDao mediaServersDao;
private MediaResourceBrokerDao mediaResourceBrokerDao;
private ExtensionsConfigurationDao extensionsConfigurationDao;
private GeolocationDao geolocationDao;
private ProfileAssociationsDao profileAssociationsDao;
private OrganizationsDao organizationsDao;
private ProfilesDao profilesDao;
public MybatisDaoManager() {
super();
}
@Override
public void configure(final Configuration configuration, Configuration daoManagerConfiguration) {
this.configuration = daoManagerConfiguration.subset("dao-manager");
this.runtimeConfiguration = configuration.subset("runtime-settings");
}
@Override
public AccountsDao getAccountsDao() {
return accountsDao;
}
@Override
public ApplicationsDao getApplicationsDao() {
return applicationsDao;
}
@Override
public AnnouncementsDao getAnnouncementsDao() {
return announcementsDao;
}
@Override
public AvailablePhoneNumbersDao getAvailablePhoneNumbersDao() {
return availablePhoneNumbersDao;
}
@Override
public CallDetailRecordsDao getCallDetailRecordsDao() {
return callDetailRecordsDao;
}
@Override
public ConferenceDetailRecordsDao getConferenceDetailRecordsDao() {
return conferenceDetailRecordsDao;
}
@Override
public ClientsDao getClientsDao() {
return clientsDao;
}
@Override
public HttpCookiesDao getHttpCookiesDao() {
return httpCookiesDao;
}
@Override
public IncomingPhoneNumbersDao getIncomingPhoneNumbersDao() {
return incomingPhoneNumbersDao;
}
@Override
public NotificationsDao getNotificationsDao() {
return notificationsDao;
}
@Override
public RegistrationsDao getRegistrationsDao() {
return presenceRecordsDao;
}
@Override
public OutgoingCallerIdsDao getOutgoingCallerIdsDao() {
return outgoingCallerIdsDao;
}
@Override
public RecordingsDao getRecordingsDao() {
return recordingsDao;
}
@Override
public ShortCodesDao getShortCodesDao() {
return shortCodesDao;
}
@Override
public SmsMessagesDao getSmsMessagesDao() {
return smsMessagesDao;
}
@Override
public UsageDao getUsageDao() {
return usageDao;
}
@Override
public TranscriptionsDao getTranscriptionsDao() {
return transcriptionsDao;
}
@Override
public GatewaysDao getGatewaysDao() {
return gatewaysDao;
}
@Override
public InstanceIdDao getInstanceIdDao() {
return instanceIdDao;
}
@Override
public MediaServersDao getMediaServersDao() {
return mediaServersDao;
}
@Override
public MediaResourceBrokerDao getMediaResourceBrokerDao() {
return mediaResourceBrokerDao;
}
@Override
public ExtensionsConfigurationDao getExtensionsConfigurationDao() {
return extensionsConfigurationDao;
}
@Override
public GeolocationDao getGeolocationDao() {
return geolocationDao;
}
@Override
public ProfileAssociationsDao getProfileAssociationsDao() {
return profileAssociationsDao;
}
@Override
public OrganizationsDao getOrganizationsDao() {
return organizationsDao;
}
@Override
public ProfilesDao getProfilesDao() {
return profilesDao;
}
@Override
public void shutdown() {
// Nothing to do.
}
@Override
public void start() throws RuntimeException {
// This must be called before any other MyBatis methods.
org.apache.ibatis.logging.LogFactory.useSlf4jLogging();
// Load the configuration file.
final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
final String path = configuration.getString("configuration-file");
Reader reader = null;
try {
reader = new FileReader(path);
} catch (final FileNotFoundException exception) {
throw new RuntimeException(exception);
}
final Properties properties = new Properties();
final String dataFiles = configuration.getString("data-files");
final String sqlFiles = configuration.getString("sql-files");
properties.setProperty("data", dataFiles);
properties.setProperty("sql", sqlFiles);
final SqlSessionFactory sessions = builder.build(reader, properties);
start(sessions);
}
public void start(final SqlSessionFactory sessions) {
// Instantiate the DAO objects.
accountsDao = new MybatisAccountsDao(sessions);
applicationsDao = new MybatisApplicationsDao(sessions);
announcementsDao = new MybatisAnnouncementsDao(sessions);
availablePhoneNumbersDao = new MybatisAvailablePhoneNumbersDao(sessions);
callDetailRecordsDao = new MybatisCallDetailRecordsDao(sessions);
conferenceDetailRecordsDao = new MybatisConferenceDetailRecordsDao(sessions);
clientsDao = new MybatisClientsDao(sessions);
httpCookiesDao = new MybatisHttpCookiesDao(sessions);
incomingPhoneNumbersDao = new MybatisIncomingPhoneNumbersDao(sessions);
notificationsDao = new MybatisNotificationsDao(sessions);
outgoingCallerIdsDao = new MybatisOutgoingCallerIdsDao(sessions);
presenceRecordsDao = new MybatisRegistrationsDao(sessions);
recordingsDao = new MybatisRecordingsDao(sessions);
shortCodesDao = new MybatisShortCodesDao(sessions);
smsMessagesDao = new MybatisSmsMessagesDao(sessions);
usageDao = new MybatisUsageDao(sessions);
transcriptionsDao = new MybatisTranscriptionsDao(sessions);
gatewaysDao = new MybatisGatewaysDao(sessions);
instanceIdDao = new MybatisInstanceIdDao(sessions);
mediaServersDao = new MybatisMediaServerDao(sessions);
mediaResourceBrokerDao = new MybatisMediaResourceBrokerDao(sessions);
extensionsConfigurationDao = new MybatisExtensionsConfigurationDao(sessions);
geolocationDao = new MybatisGeolocationDao(sessions);
profileAssociationsDao = new MybatisProfileAssociationsDao(sessions);
organizationsDao = new MybatisOrganizationDao(sessions);
profilesDao = new MybatisProfilesDao(sessions);
}
}
| 10,127 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisMediaServerDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisMediaServerDao.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.dao.mybatis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.MediaServersDao;
import org.restcomm.connect.dao.entities.MediaServerEntity;
/**
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisMediaServerDao implements MediaServersDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.MediaServersDao.";
private final SqlSessionFactory sessions;
public MybatisMediaServerDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addMediaServer(final MediaServerEntity ms) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addMediaServer", toMap(ms));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateMediaServer(final MediaServerEntity ms) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "updateMediaServer", toMap(ms));
session.commit();
} finally {
session.close();
}
}
@Override
public List<MediaServerEntity> getMediaServerEntityByIP(final String msIPAddress) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getMediaServerEntityByIP", msIPAddress);
final List<MediaServerEntity> msList = new ArrayList<MediaServerEntity>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
msList.add(toMediaServer(result));
}
}
return msList;
} finally {
session.close();
}
}
@Override
public List<MediaServerEntity> getMediaServers() {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getMediaServers");
final List<MediaServerEntity> msList = new ArrayList<MediaServerEntity>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
msList.add(toMediaServer(result));
}
}
return msList;
} finally {
session.close();
}
}
@Override
public MediaServerEntity getMediaServer(String msId) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getMediaServer", msId);
if (result != null) {
return toMediaServer(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public void removeMediaServerEntity(String msId) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "removeMediaServerEntity", msId);
session.commit();
} finally {
session.close();
}
}
private MediaServerEntity toMediaServer(final Map<String, Object> map) {
final int msId = DaoUtils.readInteger(map.get("ms_id"));
final String compatibility = DaoUtils.readString(map.get("compatibility"));
final String localIpAddress = DaoUtils.readString(map.get("local_ip"));
final int localPort = DaoUtils.readInteger(map.get("local_port"));
final String remoteIpAddress = DaoUtils.readString(map.get("remote_ip"));
final int remotePort = DaoUtils.readInteger(map.get("remote_port"));
final String responseTimeout = DaoUtils.readString(map.get("response_timeout"));
final String externalAddress = DaoUtils.readString(map.get("external_address"));
return new MediaServerEntity(msId, compatibility, localIpAddress, localPort, remoteIpAddress, remotePort, responseTimeout, externalAddress);
}
private Map<String, Object> toMap(final MediaServerEntity ms) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("ms_id", ms.getMsId());
map.put("compatibility", ms.getCompatibility());
map.put("local_ip", ms.getLocalIpAddress());
map.put("local_port", ms.getLocalPort());
map.put("remote_ip", ms.getRemoteIpAddress());
map.put("remote_port", ms.getRemotePort());
map.put("response_timeout", ms.getResponseTimeout());
map.put("external_address", ms.getExternalAddress());
return map;
}
}
| 5,899 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisAccountsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisAccountsDao.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.dao.mybatis;
import static org.restcomm.connect.dao.DaoUtils.readAccountStatus;
import static org.restcomm.connect.dao.DaoUtils.readAccountType;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
import static org.restcomm.connect.dao.DaoUtils.readSid;
import static org.restcomm.connect.dao.DaoUtils.readString;
import static org.restcomm.connect.dao.DaoUtils.readUri;
import static org.restcomm.connect.dao.DaoUtils.writeAccountStatus;
import static org.restcomm.connect.dao.DaoUtils.writeAccountType;
import static org.restcomm.connect.dao.DaoUtils.writeDateTime;
import static org.restcomm.connect.dao.DaoUtils.writeSid;
import static org.restcomm.connect.dao.DaoUtils.writeUri;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.AccountsDao;
import org.restcomm.connect.dao.entities.Account;
import org.restcomm.connect.dao.exceptions.AccountHierarchyDepthCrossed;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisAccountsDao implements AccountsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.AccountsDao.";
private Integer accountRecursionDepth = 3; // maximum value for recursive account queries
private final SqlSessionFactory sessions;
public MybatisAccountsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
public void setAccountRecursionDepth(Integer accountRecursionDepth) {
this.accountRecursionDepth = accountRecursionDepth;
}
@Override
public void addAccount(final Account account) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addAccount", toMap(account));
session.commit();
} finally {
session.close();
}
}
@Override
public Account getAccount(final Sid sid) {
return getAccount(namespace + "getAccount", sid.toString());
}
@Override
public Account getAccount(final String name) {
Account account = null;
account = getAccount(namespace + "getAccountByFriendlyName", name);
if (account == null) {
account = getAccount(namespace + "getAccountByEmail", name);
}
if (account == null) {
account = getAccount(namespace + "getAccount", name);
}
return account;
}
@Override
public Account getAccountToAuthenticate(final String name) {
Account account = null;
account = getAccount(namespace + "getAccountByEmail", name);
if (account == null) {
account = getAccount(namespace + "getAccount", name);
}
return account;
}
private Account getAccount(final String selector, final Object parameters) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(selector, parameters);
if (result != null) {
return toAccount(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Account> getChildAccounts(final Sid parentSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getChildAccounts", parentSid.toString());
final List<Account> accounts = new ArrayList<Account>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
accounts.add(toAccount(result));
}
}
return accounts;
} finally {
session.close();
}
}
@Override
public void removeAccount(final Sid sid) {
removeAccount(namespace + "removeAccount", sid);
}
private void removeAccount(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateAccount(final Account account) {
updateAccount(namespace + "updateAccount", account);
}
@Override
public List<String> getSubAccountSidsRecursive(Sid parentAccountSid) {
List<String> parentList = new ArrayList<String>();
parentList.add(parentAccountSid.toString());
List<String> allChildren = new ArrayList<String>();
int depth = 1;
List<String> childrenList = getSubAccountsSids(parentList);
while (childrenList != null && !childrenList.isEmpty() && depth <= accountRecursionDepth) {
allChildren.addAll(childrenList);
childrenList = getSubAccountsSids(childrenList); // retrieve children's children
depth ++;
}
return allChildren;
}
@Override
public List<String> getAccountLineage(Sid accountSid) throws AccountHierarchyDepthCrossed {
if (accountSid == null)
return null;
List<String> ancestorList = new ArrayList<String>();
Sid sid = accountSid;
Account account = getAccount(sid);
if (account == null)
throw new IllegalArgumentException("Wrong accountSid is given to search for ancestor on it. This account does not even exist");
int depth = 1; // already having one-level of accounts
while ( true ) {
Sid parentSid = account.getParentSid();
if (parentSid != null) {
depth ++;
if (depth > accountRecursionDepth)
throw new AccountHierarchyDepthCrossed();
ancestorList.add(parentSid.toString());
Account parentAccount = getAccount(parentSid);
if (parentAccount == null)
throw new IllegalStateException("Parent account " + parentSid.toString() + " does not exist although its child does " + account.getSid().toString());
account = parentAccount;
} else
break;
}
return ancestorList;
}
@Override
public List<String> getAccountLineage(Account account) throws AccountHierarchyDepthCrossed {
if (account == null)
return null;
List<String> lineage = new ArrayList<String>();
Sid parentSid = account.getParentSid();
if (parentSid != null) {
lineage.add(parentSid.toString());
lineage.addAll(getAccountLineage(parentSid));
}
return lineage;
}
private List<String> getSubAccountsSids(List<String> parentAccountSidList) {
final SqlSession session = sessions.openSession();
try {
final List<String> results = session.selectList(namespace + "getSubAccountSids", parentAccountSidList);
return results;
} finally {
session.close();
}
}
private void updateAccount(final String selector, final Account account) {
final SqlSession session = sessions.openSession();
try {
session.update(selector, toMap(account));
session.commit();
} finally {
session.close();
}
}
@Override
public List<Account> getAccountsByOrganization(final Sid organizationSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getAccountsByOrganization", organizationSid.toString());
final List<Account> accounts = new ArrayList<Account>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
accounts.add(toAccount(result));
}
}
return accounts;
} finally {
session.close();
}
}
private Account toAccount(final Map<String, Object> map) {
final Sid sid = readSid(map.get("sid"));
final DateTime dateCreated = readDateTime(map.get("date_created"));
final DateTime dateUpdated = readDateTime(map.get("date_updated"));
final String emailAddress = readString(map.get("email_address"));
final String friendlyName = readString(map.get("friendly_name"));
final Sid parentSid = readSid(map.get("parent_sid"));
final Account.Type type = readAccountType(map.get("type"));
final Account.Status status = readAccountStatus(map.get("status"));
final String authToken = readString(map.get("auth_token"));
final String role = readString(map.get("role"));
final URI uri = readUri(map.get("uri"));
final Sid organizationSid = readSid(map.get("organization_sid"));
return new Account(sid, dateCreated, dateUpdated, emailAddress, friendlyName, parentSid, type, status, authToken,
role, uri, organizationSid);
}
private Map<String, Object> toMap(final Account account) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", writeSid(account.getSid()));
map.put("date_created", writeDateTime(account.getDateCreated()));
map.put("date_updated", writeDateTime(account.getDateUpdated()));
map.put("email_address", account.getEmailAddress());
map.put("friendly_name", account.getFriendlyName());
map.put("parent_sid", writeSid(account.getParentSid()));
map.put("type", writeAccountType(account.getType()));
map.put("status", writeAccountStatus(account.getStatus()));
map.put("auth_token", account.getAuthToken());
map.put("role", account.getRole());
map.put("uri", writeUri(account.getUri()));
map.put("organization_sid", writeSid(account.getOrganizationSid()));
return map;
}
}
| 11,260 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisMediaResourceBrokerDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisMediaResourceBrokerDao.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.dao.mybatis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.MediaResourceBrokerDao;
import org.restcomm.connect.dao.entities.MediaResourceBrokerEntity;
import org.restcomm.connect.dao.entities.MediaResourceBrokerEntityFilter;
/**
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisMediaResourceBrokerDao implements MediaResourceBrokerDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.MediaResourceBrokerDao.";
private final SqlSessionFactory sessions;
public MybatisMediaResourceBrokerDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addMediaResourceBrokerEntity(MediaResourceBrokerEntity ms) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addMediaResourceBrokerEntity", toMap(ms));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateMediaResource(MediaResourceBrokerEntity ms) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "updateMediaResource", toMap(ms));
session.commit();
} finally {
session.close();
}
}
@Override
public List<MediaResourceBrokerEntity> getMediaResourceBrokerEntities() {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getMediaServers");
final List<MediaResourceBrokerEntity> mList = new ArrayList<MediaResourceBrokerEntity>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
mList.add(toMRBEntity(result));
}
}
return mList;
} finally {
session.close();
}
}
@Override
public List<MediaResourceBrokerEntity> getConnectedSlaveEntitiesByConfSid(Sid conferenceSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getConnectedSlaveEntitiesByConfSid",
conferenceSid.toString());
final List<MediaResourceBrokerEntity> entities = new ArrayList<MediaResourceBrokerEntity>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
entities.add(toMRBEntity(result));
}
}
return entities;
} finally {
session.close();
}
}
@Override
public void removeMediaResourceBrokerEntity(MediaResourceBrokerEntityFilter filter) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "removeMediaResourceBrokerEntity", filter);
session.commit();
} finally {
session.close();
}
}
private MediaResourceBrokerEntity toMRBEntity(final Map<String, Object> map) {
final Sid conferenceSid = DaoUtils.readSid(map.get("conference_sid"));
final String slaveMsId = DaoUtils.readString(map.get("slave_ms_id"));
final String slaveMsBridgeEpId = DaoUtils.readString(map.get("slave_ms_bridge_ep_id"));
final String slaveMsCnfEpId = DaoUtils.readString(map.get("slave_ms_cnf_ep_id"));
final boolean isBridgedTogether = DaoUtils.readBoolean(map.get("is_bridged_together"));
return new MediaResourceBrokerEntity(conferenceSid, slaveMsId, slaveMsBridgeEpId, slaveMsCnfEpId, isBridgedTogether);
}
private Map<String, Object> toMap(final MediaResourceBrokerEntity ms) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("conference_sid", DaoUtils.writeSid(ms.getConferenceSid()));
map.put("slave_ms_id", ms.getSlaveMsId());
map.put("slave_ms_bridge_ep_id", ms.getSlaveMsBridgeEpId());
map.put("slave_ms_cnf_ep_id", ms.getSlaveMsCnfEpId());
map.put("is_bridged_together", ms.isBridgedTogether());
return map;
}
}
| 5,479 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisClientsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisClientsDao.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.dao.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe;
import org.restcomm.connect.commons.configuration.RestcommConfiguration;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.ClientsDao;
import org.restcomm.connect.dao.entities.Client;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
import static org.restcomm.connect.dao.DaoUtils.readInteger;
import static org.restcomm.connect.dao.DaoUtils.readSid;
import static org.restcomm.connect.dao.DaoUtils.readString;
import static org.restcomm.connect.dao.DaoUtils.readUri;
import static org.restcomm.connect.dao.DaoUtils.writeDateTime;
import static org.restcomm.connect.dao.DaoUtils.writeSid;
import static org.restcomm.connect.dao.DaoUtils.writeUri;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (Maria Farooq)
*/
@NotThreadSafe
public final class MybatisClientsDao implements ClientsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.ClientsDao.";
private final SqlSessionFactory sessions;
public MybatisClientsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addClient(final Client client) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addClient", toMap(client));
session.commit();
} finally {
session.close();
}
}
@Override
public Client getClient(final Sid sid) {
return getClient(namespace + "getClient", sid.toString());
}
@Override
public Client getClient(final String login, Sid organizationSid) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("login", login);
map.put("organization_sid", writeSid(organizationSid));
return getClient(namespace + "getClientByLogin", map);
}
private Client getClient(final String selector, final Object parameter) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(selector, parameter);
if (result != null) {
return toClient(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Client> getClients(final Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getClients", accountSid.toString());
final List<Client> clients = new ArrayList<Client>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
clients.add(toClient(result));
}
}
return clients;
} finally {
session.close();
}
}
@Override
public List<Client> getAllClients() {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getAllClients");
final List<Client> clients = new ArrayList<Client>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
clients.add(toClient(result));
}
}
return clients;
} finally {
session.close();
}
}
@Override
public List<Client> getClientsByOrg(final Sid organizationSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getAllClientsByOrg", organizationSid.toString());
final List<Client> clients = new ArrayList<Client>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
clients.add(toClient(result));
}
}
return clients;
} finally {
session.close();
}
}
@Override
public void removeClient(final Sid sid) {
removeClients(namespace + "removeClient", sid);
}
@Override
public void removeClients(final Sid accountSid) {
removeClients(namespace + "removeClients", accountSid);
}
private void removeClients(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateClient(final Client client) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateClient", toMap(client));
session.commit();
} finally {
session.close();
}
}
private Client toClient(final Map<String, Object> map) {
final Sid sid = readSid(map.get("sid"));
final DateTime dateCreated = readDateTime(map.get("date_created"));
final DateTime dateUpdated = readDateTime(map.get("date_updated"));
final Sid accountSid = readSid(map.get("account_sid"));
final String apiVersion = readString(map.get("api_version"));
final String friendlyName = readString(map.get("friendly_name"));
final String login = readString(map.get("login"));
final String password = readString(map.get("password"));
final int status = readInteger(map.get("status"));
final URI voiceUrl = readUri(map.get("voice_url"));
final String voiceMethod = readString(map.get("voice_method"));
final URI voiceFallbackUrl = readUri(map.get("voice_fallback_url"));
final String voiceFallbackMethod = readString(map.get("voice_fallback_method"));
final Sid voiceApplicationSid = readSid(map.get("voice_application_sid"));
final URI uri = readUri(map.get("uri"));
final String pushClientIdentity = readString(map.get("push_client_identity"));
String passwordAlgorithm = RestcommConfiguration.getInstance().getMain().getClearTextPasswordAlgorithm();
if (map.containsKey("password_algorithm")) {
passwordAlgorithm = readString(map.get("password_algorithm"));
}
return new Client(sid, dateCreated, dateUpdated, accountSid, apiVersion, friendlyName, login, password, status,
voiceUrl, voiceMethod, voiceFallbackUrl, voiceFallbackMethod, voiceApplicationSid, uri, pushClientIdentity, passwordAlgorithm);
}
private Map<String, Object> toMap(final Client client) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", writeSid(client.getSid()));
map.put("date_created", writeDateTime(client.getDateCreated()));
map.put("date_updated", writeDateTime(client.getDateUpdated()));
map.put("account_sid", writeSid(client.getAccountSid()));
map.put("api_version", client.getApiVersion());
map.put("friendly_name", client.getFriendlyName());
map.put("login", client.getLogin());
map.put("password", client.getPassword());
map.put("status", client.getStatus());
map.put("voice_url", writeUri(client.getVoiceUrl()));
map.put("voice_method", client.getVoiceMethod());
map.put("voice_fallback_url", writeUri(client.getVoiceFallbackUrl()));
map.put("voice_fallback_method", client.getVoiceFallbackMethod());
map.put("voice_application_sid", writeSid(client.getVoiceApplicationSid()));
map.put("uri", writeUri(client.getUri()));
map.put("push_client_identity", client.getPushClientIdentity());
map.put("password_algorithm", client.getPasswordAlgorithm());
return map;
}
}
| 9,207 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisNotificationsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisNotificationsDao.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.dao.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.NotificationsDao;
import org.restcomm.connect.dao.entities.Notification;
import org.restcomm.connect.commons.dao.Sid;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
import static org.restcomm.connect.dao.DaoUtils.readInteger;
import static org.restcomm.connect.dao.DaoUtils.readSid;
import static org.restcomm.connect.dao.DaoUtils.readString;
import static org.restcomm.connect.dao.DaoUtils.readUri;
import static org.restcomm.connect.dao.DaoUtils.writeDateTime;
import static org.restcomm.connect.dao.DaoUtils.writeSid;
import static org.restcomm.connect.dao.DaoUtils.writeUri;
import org.restcomm.connect.dao.entities.NotificationFilter;
/**
* @author [email protected] (Thomas Quintana)
*/
@ThreadSafe
public final class MybatisNotificationsDao implements NotificationsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.NotificationsDao.";
private final SqlSessionFactory sessions;
public MybatisNotificationsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addNotification(final Notification notification) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addNotification", toMap(notification));
session.commit();
} finally {
session.close();
}
}
@Override
public Notification getNotification(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getNotification", sid.toString());
if (result != null) {
return toNotification(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Notification> getNotifications(final Sid accountSid) {
return getNotifications(namespace + "getNotifications", accountSid.toString());
}
@Override
public List<Notification> getNotifications(NotificationFilter filter) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getNotificationsByUsingFilters",
filter);
final List<Notification> cdrs = new ArrayList<Notification>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cdrs.add(toNotification(result));
}
}
return cdrs;
} finally {
session.close();
}
}
@Override
public Integer getTotalNotification(NotificationFilter filter) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getTotalNotificationByUsingFilters", filter);
return total;
} finally {
session.close();
}
}
@Override
public List<Notification> getNotificationsByCall(final Sid callSid) {
return getNotifications(namespace + "getNotificationsByCall", callSid.toString());
}
@Override
public List<Notification> getNotificationsByLogLevel(final int logLevel) {
return getNotifications(namespace + "getNotificationsByLogLevel", logLevel);
}
@Override
public List<Notification> getNotificationsByMessageDate(final DateTime messageDate) {
final Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("start_date", messageDate.toDate());
parameters.put("end_date", messageDate.plusDays(1).toDate());
return getNotifications(namespace + "getNotificationsByMessageDate", parameters);
}
private List<Notification> getNotifications(final String selector, final Object input) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(selector, input);
final List<Notification> notifications = new ArrayList<Notification>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
notifications.add(toNotification(result));
}
}
return notifications;
} finally {
session.close();
}
}
@Override
public void removeNotification(final Sid sid) {
removeNotifications(namespace + "removeNotification", sid);
}
@Override
public void removeNotifications(final Sid accountSid) {
removeNotifications(namespace + "removeNotifications", accountSid);
}
@Override
public void removeNotificationsByCall(final Sid callSid) {
removeNotifications(namespace + "removeNotificationsByCall", callSid);
}
private void removeNotifications(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
private Map<String, Object> toMap(final Notification notification) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", writeSid(notification.getSid()));
map.put("date_created", writeDateTime(notification.getDateCreated()));
map.put("date_updated", writeDateTime(notification.getDateUpdated()));
map.put("account_sid", writeSid(notification.getAccountSid()));
map.put("call_sid", writeSid(notification.getCallSid()));
map.put("api_version", notification.getApiVersion());
map.put("log", notification.getLog());
map.put("error_code", notification.getErrorCode());
map.put("more_info", writeUri(notification.getMoreInfo()));
map.put("message_text", notification.getMessageText());
map.put("message_date", writeDateTime(notification.getMessageDate()));
map.put("request_url", writeUri(notification.getRequestUrl()));
map.put("request_method", notification.getRequestMethod());
map.put("request_variables", notification.getRequestVariables());
map.put("response_headers", notification.getResponseHeaders());
map.put("response_body", notification.getResponseBody());
map.put("uri", writeUri(notification.getUri()));
return map;
}
private Notification toNotification(final Map<String, Object> map) {
final Sid sid = readSid(map.get("sid"));
final DateTime dateCreated = readDateTime(map.get("date_created"));
final DateTime dateUpdated = readDateTime(map.get("date_updated"));
final Sid accountSid = readSid(map.get("account_sid"));
final Sid callSid = readSid(map.get("call_sid"));
final String apiVersion = readString(map.get("api_version"));
final Integer log = readInteger(map.get("log"));
final Integer errorCode = readInteger(map.get("error_code"));
final URI moreInfo = readUri(map.get("more_info"));
final String messageText = readString(map.get("message_text"));
final DateTime messageDate = readDateTime(map.get("message_date"));
final URI requestUrl = readUri(map.get("request_url"));
final String requestMethod = readString(map.get("request_method"));
final String requestVariables = readString(map.get("request_variables"));
final String responseHeaders = readString(map.get("response_headers"));
final String responseBody = readString(map.get("response_body"));
final URI uri = readUri(map.get("uri"));
return new Notification(sid, dateCreated, dateUpdated, accountSid, callSid, apiVersion, log, errorCode, moreInfo,
messageText, messageDate, requestUrl, requestMethod, requestVariables, responseHeaders, responseBody, uri);
}
}
| 9,313 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisShortCodesDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisShortCodesDao.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.dao.mybatis;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.ShortCodesDao;
import org.restcomm.connect.dao.entities.ShortCode;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
/**
* @author [email protected] (Thomas Quintana)
*/
@ThreadSafe
public final class MybatisShortCodesDao implements ShortCodesDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.ShortCodesDao.";
private final SqlSessionFactory sessions;
public MybatisShortCodesDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addShortCode(final ShortCode shortCode) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addShortCode", toMap(shortCode));
session.commit();
} finally {
session.close();
}
}
@Override
public ShortCode getShortCode(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getShortCode", sid.toString());
if (result != null) {
return toShortCode(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<ShortCode> getShortCodes(final Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getShortCodes", accountSid.toString());
final List<ShortCode> shortCodes = new ArrayList<ShortCode>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
shortCodes.add(toShortCode(result));
}
}
return shortCodes;
} finally {
session.close();
}
}
@Override
public void removeShortCode(final Sid sid) {
removeShortCodes(namespace + "removeShortCode", sid);
}
@Override
public void removeShortCodes(final Sid accountSid) {
removeShortCodes(namespace + "removeShortCodes", accountSid);
}
private void removeShortCodes(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateShortCode(final ShortCode shortCode) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateShortCode", toMap(shortCode));
session.commit();
} finally {
session.close();
}
}
private Map<String, Object> toMap(final ShortCode shortCode) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(shortCode.getSid()));
map.put("date_created", DaoUtils.writeDateTime(shortCode.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(shortCode.getDateUpdated()));
map.put("friendly_name", shortCode.getFriendlyName());
map.put("account_sid", DaoUtils.writeSid(shortCode.getAccountSid()));
map.put("short_code", shortCode.getShortCode());
map.put("api_version", shortCode.getApiVersion());
map.put("sms_url", DaoUtils.writeUri(shortCode.getSmsUrl()));
map.put("sms_method", shortCode.getSmsMethod());
map.put("sms_fallback_url", DaoUtils.writeUri(shortCode.getSmsFallbackUrl()));
map.put("sms_fallback_method", shortCode.getSmsFallbackMethod());
map.put("uri", DaoUtils.writeUri(shortCode.getUri()));
return map;
}
private ShortCode toShortCode(final Map<String, Object> map) {
final Sid sid = DaoUtils.readSid(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final String friendlyName = DaoUtils.readString(map.get("friendly_name"));
final Sid accountSid = DaoUtils.readSid(map.get("account_sid"));
final Integer shortCode = DaoUtils.readInteger(map.get("short_code"));
final String apiVersion = DaoUtils.readString(map.get("api_version"));
final URI smsUrl = DaoUtils.readUri(map.get("sms_url"));
final String smsMethod = DaoUtils.readString(map.get("sms_method"));
final URI smsFallbackUrl = DaoUtils.readUri(map.get("sms_fallback_url"));
final String smsFallbackMethod = DaoUtils.readString(map.get("sms_fallback_method"));
final URI uri = DaoUtils.readUri(map.get("uri"));
return new ShortCode(sid, dateCreated, dateUpdated, friendlyName, accountSid, shortCode, apiVersion, smsUrl, smsMethod,
smsFallbackUrl, smsFallbackMethod, uri);
}
}
| 6,296 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisRecordingsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisRecordingsDao.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.dao.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.RecordingsDao;
import org.restcomm.connect.dao.entities.Recording;
import org.restcomm.connect.dao.entities.RecordingFilter;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisRecordingsDao implements RecordingsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.RecordingsDao.";
private final SqlSessionFactory sessions;
public MybatisRecordingsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addRecording(Recording recording) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addRecording", toMap(recording));
session.commit();
} finally {
session.close();
}
}
@Override
public Recording getRecording(final Sid sid) {
return getRecording(namespace + "getRecording", sid);
}
@Override
public Recording getRecordingByCall(final Sid callSid) {
return getRecording(namespace + "getRecordingByCall", callSid);
}
@Override
public List<Recording> getRecordingsByCall(Sid callSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getRecordingsByCall", callSid.toString());
final List<Recording> recordings = new ArrayList<Recording>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
recordings.add(toRecording(result));
}
}
return recordings;
} finally {
session.close();
}
}
private Recording getRecording(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(selector, sid.toString());
if (result != null) {
return toRecording(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Recording> getRecordings(final Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getRecordings", accountSid.toString());
final List<Recording> recordings = new ArrayList<Recording>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
recordings.add(toRecording(result));
}
}
return recordings;
} finally {
session.close();
}
}
@Override
public List<Recording> getRecordings(RecordingFilter filter) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getRecordingsByUsingFilters",
filter);
final List<Recording> cdrs = new ArrayList<Recording>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cdrs.add(toRecording(result));
}
}
return cdrs;
} finally {
session.close();
}
}
@Override
public Integer getTotalRecording(RecordingFilter filter) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getTotalRecordingByUsingFilters", filter);
return total;
} finally {
session.close();
}
}
@Override
public void removeRecording(final Sid sid) {
removeRecording(namespace + "removeRecording", sid);
}
@Override
public void removeRecordings(final Sid accountSid) {
removeRecording(namespace + "removeRecordings", accountSid);
}
private void removeRecording(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateRecording(final Recording recording) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateRecording", toMap(recording));
session.commit();
} finally {
session.close();
}
}
private Map<String, Object> toMap(final Recording recording) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(recording.getSid()));
map.put("date_created", DaoUtils.writeDateTime(recording.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(recording.getDateUpdated()));
map.put("account_sid", DaoUtils.writeSid(recording.getAccountSid()));
map.put("call_sid", DaoUtils.writeSid(recording.getCallSid()));
map.put("duration", recording.getDuration());
map.put("api_version", recording.getApiVersion());
map.put("uri", DaoUtils.writeUri(recording.getUri()));
map.put("file_uri", DaoUtils.writeUri(recording.getFileUri()));
if (recording.getS3Uri() != null) {
map.put("s3_uri", DaoUtils.writeUri(recording.getS3Uri()));
} else {
map.put("s3_uri", null);
}
return map;
}
private Recording toRecording(final Map<String, Object> map) {
Recording recording = null;
boolean update = false;
final Sid sid = DaoUtils.readSid(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final Sid accountSid = DaoUtils.readSid(map.get("account_sid"));
final Sid callSid = DaoUtils.readSid(map.get("call_sid"));
final Double duration = DaoUtils.readDouble(map.get("duration"));
final String apiVersion = DaoUtils.readString(map.get("api_version"));
final URI uri = DaoUtils.readUri(map.get("uri"));
//For backward compatibility. For old an database that we upgraded to the latest schema, the file_uri will be null so we need
//to create the file_uri on the fly
String fileUri = (String) map.get("file_uri");
if (fileUri == null || fileUri.isEmpty()) {
fileUri = String.format("/restcomm/%s/Accounts/%s/Recordings/%s.wav",apiVersion,accountSid,sid);
}
// fileUri: http://192.168.1.190:8080/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Recordings/RE4c9c09908b60402c8c0a77e24313f27d.wav
// s3Uri: https://gvagrestcomm.s3.amazonaws.com/RE4c9c09908b60402c8c0a77e24313f27d.wav
// old S3URI: https://s3.amazonaws.com/restcomm-as-a-service/logs/RE7ddbd5b441574e4ab786a1fddf33eb47.wav?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20170209T103950Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604800&X-Amz-Credential=AKIAIRG5NINXKJAJM5DA%2F20170209%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=b3da2acc17ee9c6aca4cd151e154d94f530670850f0fcade2422f85d1c7cc992
String s3Uri = (String) map.get("s3_uri");
recording = new Recording(sid, dateCreated, dateUpdated, accountSid, callSid, duration, apiVersion, uri, DaoUtils.readUri(fileUri), DaoUtils.readUri(s3Uri));
return recording;
}
}
| 9,148 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisSmsMessagesDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisSmsMessagesDao.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.dao.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.dao.MessageError;
import org.restcomm.connect.dao.SmsMessagesDao;
import org.restcomm.connect.dao.entities.SmsMessage;
import org.restcomm.connect.dao.entities.SmsMessageFilter;
import java.math.BigDecimal;
import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Currency;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.restcomm.connect.dao.DaoUtils.readBigDecimal;
import static org.restcomm.connect.dao.DaoUtils.readInteger;
import static org.restcomm.connect.dao.DaoUtils.readCurrency;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
import static org.restcomm.connect.dao.DaoUtils.readSid;
import static org.restcomm.connect.dao.DaoUtils.readString;
import static org.restcomm.connect.dao.DaoUtils.readUri;
import static org.restcomm.connect.dao.DaoUtils.writeBigDecimal;
import static org.restcomm.connect.dao.DaoUtils.writeCurrency;
import static org.restcomm.connect.dao.DaoUtils.writeDateTime;
import static org.restcomm.connect.dao.DaoUtils.writeSid;
import static org.restcomm.connect.dao.DaoUtils.writeUri;
/**
* @author [email protected] (Thomas Quintana)
* @author mariafarooq
*/
@ThreadSafe
public final class MybatisSmsMessagesDao implements SmsMessagesDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.SmsMessagesDao.";
private final SqlSessionFactory sessions;
private static final String STATUS_CALLBACK_COL = "status_callback";
private static final String STATUS_CALLBACK_METHOD_COL = "status_callback_method";
public MybatisSmsMessagesDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addSmsMessage(final SmsMessage smsMessage) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addSmsMessage", toMap(smsMessage));
session.commit();
} finally {
session.close();
}
}
@Override
public SmsMessage getSmsMessage(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getSmsMessage", sid.toString());
if (result != null) {
return toSmsMessage(result);
} else {
return null;
}
} finally {
session.close();
}
}
/* (non-Javadoc)
* @see org.restcomm.connect.dao.SmsMessagesDao#getSmsMessageBySmppMessageId(java.lang.String)
*/
@Override
public SmsMessage getSmsMessageBySmppMessageId(final String smppMessageId) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getSmsMessageBySmppMessageId", smppMessageId);
if (result != null) {
return toSmsMessage(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<SmsMessage> getSmsMessages(final Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getSmsMessages", accountSid.toString());
final List<SmsMessage> smsMessages = new ArrayList<SmsMessage>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
smsMessages.add(toSmsMessage(result));
}
}
return smsMessages;
} finally {
session.close();
}
}
@Override
public List<SmsMessage> getSmsMessages(SmsMessageFilter filter) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getSmsMessagesByUsingFilters",
filter);
final List<SmsMessage> cdrs = new ArrayList<SmsMessage>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cdrs.add(toSmsMessage(result));
}
}
return cdrs;
} finally {
session.close();
}
}
@Override
public Integer getTotalSmsMessage(SmsMessageFilter filter) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getTotalSmsMessageByUsingFilters", filter);
return total;
} finally {
session.close();
}
}
@Override
public void removeSmsMessage(final Sid sid) {
deleteSmsMessage(namespace + "removeSmsMessage", sid);
}
@Override
public void removeSmsMessages(final Sid accountSid) {
deleteSmsMessage(namespace + "removeSmsMessages", accountSid);
}
private void deleteSmsMessage(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
public void updateSmsMessage(final SmsMessage smsMessage) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateSmsMessage", toMap(smsMessage));
session.commit();
} finally {
session.close();
}
}
@Override
public int getSmsMessagesPerAccountLastPerMinute(String accountSid) throws ParseException {
SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String date = formatter.format(DateTime.now().minusSeconds(60).toDate());
Map<String, Object> params = new HashMap<String, Object>();
params.put("start_time", date);
params.put("account_sid", accountSid);
final SqlSession session = sessions.openSession();
try {
final int total = session.selectOne(namespace + "getSmsMessagesPerAccountLastPerMinute", params);
return total;
} finally {
session.close();
}
}
@Override
public List<SmsMessage> findBySmppMessageId(String smppMessageId) {
final Map<String, Object> parameters = new HashMap<>(2);
parameters.put("smppMessageId", smppMessageId);
final SqlSession session = this.sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "findBySmppMessageId", parameters);
final List<SmsMessage> messages = new ArrayList<>(results.size());
for (Map<String, Object> result : results) {
messages.add(toSmsMessage(result));
}
return messages;
} finally {
session.close();
}
}
private Map<String, Object> toMap(final SmsMessage smsMessage) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", writeSid(smsMessage.getSid()));
map.put("date_created", writeDateTime(smsMessage.getDateCreated()));
map.put("date_updated", writeDateTime(smsMessage.getDateUpdated()));
map.put("date_sent", writeDateTime(smsMessage.getDateSent()));
map.put("account_sid", writeSid(smsMessage.getAccountSid()));
map.put("sender", smsMessage.getSender());
map.put("recipient", smsMessage.getRecipient());
map.put("body", smsMessage.getBody());
map.put("status", smsMessage.getStatus().toString());
map.put("direction", smsMessage.getDirection().toString());
map.put("price", writeBigDecimal(smsMessage.getPrice()));
map.put("price_unit", writeCurrency(smsMessage.getPriceUnit()));
map.put("api_version", smsMessage.getApiVersion());
map.put("uri", writeUri(smsMessage.getUri()));
map.put("smpp_message_id", smsMessage.getSmppMessageId());
map.put(STATUS_CALLBACK_COL, writeUri(smsMessage.getStatusCallback()));
map.put(STATUS_CALLBACK_METHOD_COL, smsMessage.getStatusCallbackMethod());
MessageError error = smsMessage.getError();
if(error != null) {
map.put("error_code", smsMessage.getError().getErrorCode());
}
return map;
}
private SmsMessage toSmsMessage(final Map<String, Object> map) {
final Sid sid = readSid(map.get("sid"));
final DateTime dateCreated = readDateTime(map.get("date_created"));
final DateTime dateUpdated = readDateTime(map.get("date_updated"));
final DateTime dateSent = readDateTime(map.get("date_sent"));
final Sid accountSid = readSid(map.get("account_sid"));
final String sender = readString(map.get("sender"));
final String recipient = readString(map.get("recipient"));
final String body = readString(map.get("body"));
final SmsMessage.Status status = SmsMessage.Status.getStatusValue(readString(map.get("status")));
final SmsMessage.Direction direction = SmsMessage.Direction.getDirectionValue(readString(map.get("direction")));
final BigDecimal price = readBigDecimal(map.get("price"));
final Currency priceUnit = readCurrency(map.get("price_unit"));
final String apiVersion = readString(map.get("api_version"));
final URI uri = readUri(map.get("uri"));
final String smppMessageId = readString(map.get("smpp_message_id"));
final URI statusCallback = readUri(map.get(STATUS_CALLBACK_COL));
final String statusCallbackMethod = readString(map.get(STATUS_CALLBACK_METHOD_COL));
final Integer errorCode = readInteger(map.get("error_code"));
MessageError error = null;
if(errorCode != null) {
error = MessageError.getErrorValue(errorCode);
}
return new SmsMessage(sid, dateCreated, dateUpdated, dateSent, accountSid,
sender, recipient, body, status, direction,
price, priceUnit, apiVersion, uri, smppMessageId, error,
statusCallback, statusCallbackMethod);
}
}
| 11,560 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisConferenceDetailRecordsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisConferenceDetailRecordsDao.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.dao.mybatis;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.ConferenceDetailRecordsDao;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.entities.ConferenceDetailRecord;
import org.restcomm.connect.dao.entities.ConferenceDetailRecordFilter;
import org.restcomm.connect.dao.entities.ConferenceRecordCountFilter;
/**
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisConferenceDetailRecordsDao implements ConferenceDetailRecordsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.ConferenceDetailRecordsDao.";
private final SqlSessionFactory sessions;
public MybatisConferenceDetailRecordsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public int addConferenceDetailRecord(ConferenceDetailRecord cdr) {
final SqlSession session = sessions.openSession();
int effectedRows = 0;
try {
effectedRows = session.insert(namespace + "addConferenceDetailRecord", toMap(cdr));
session.commit();
} finally {
session.close();
}
return effectedRows;
}
@Override
public ConferenceDetailRecord getConferenceDetailRecord(Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getConferenceDetailRecord", sid.toString());
if (result != null) {
return toConferenceDetailRecord(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public Integer getTotalConferenceDetailRecords(ConferenceDetailRecordFilter filter) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getTotalConferenceDetailRecordByUsingFilters", filter);
return total;
} finally {
session.close();
}
}
@Override
public Integer countByFilter(ConferenceRecordCountFilter filter) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "countByFilter", filter);
return total;
} finally {
session.close();
}
}
@Override
public List<ConferenceDetailRecord> getConferenceDetailRecords(ConferenceDetailRecordFilter filter) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getConferenceDetailRecordByUsingFilters",
filter);
final List<ConferenceDetailRecord> cdrs = new ArrayList<ConferenceDetailRecord>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cdrs.add(toConferenceDetailRecord(result));
}
}
return cdrs;
} finally {
session.close();
}
}
@Override
public List<ConferenceDetailRecord> getConferenceDetailRecords(final Sid accountSid) {
return getConferenceDetailRecords(namespace + "getConferenceDetailRecords", accountSid.toString());
}
@Override
public List<ConferenceDetailRecord> getConferenceDetailRecordsByStatus(String status) {
return getConferenceDetailRecords(namespace + "getConferenceDetailRecordsByStatus", status);
}
@Override
public List<ConferenceDetailRecord> getConferenceDetailRecordsByDateCreated(final DateTime dateCreated) {
return getConferenceDetailRecords(namespace + "getConferenceDetailRecordsByDateCreated", dateCreated.toDate());
}
@Override
public List<ConferenceDetailRecord> getConferenceDetailRecordsByDateUpdated(final DateTime dateUpdated) {
return getConferenceDetailRecords(namespace + "getConferenceDetailRecordsByDateUpdated", dateUpdated.toDate());
}
@Override
public void updateConferenceDetailRecordStatus(ConferenceDetailRecord cdr) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateConferenceDetailRecordStatus", toMap(cdr));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateConferenceDetailRecordMasterEndpointID(ConferenceDetailRecord cdr) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateConferenceDetailRecordMasterEndpointID", toMap(cdr));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateConferenceDetailRecordMasterBridgeEndpointID(ConferenceDetailRecord cdr) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateConferenceDetailRecordMasterBridgeEndpointID", toMap(cdr));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateMasterPresent(ConferenceDetailRecord cdr) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateMasterPresent", toMap(cdr));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateModeratorPresent(ConferenceDetailRecord cdr) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateModeratorPresent", toMap(cdr));
session.commit();
} finally {
session.close();
}
}
@Override
public boolean completeConferenceDetailRecord(Map params) {
final SqlSession session = sessions.openSession();
try {
session.selectOne(namespace + "completeConferenceDetailRecord", params);
return (boolean)params.get("completed");
} finally {
session.close();
}
}
@Override
public void removeConferenceDetailRecord(Sid sid) {
// TODO Add support for conference modification after basic API's as twillio's
}
@Override
public void removeConferenceDetailRecords(Sid accountSid) {
// TODO Add support for conference modification after basic API's as twillio's
}
private List<ConferenceDetailRecord> getConferenceDetailRecords(final String selector, Object input) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(selector, input);
final List<ConferenceDetailRecord> cdrs = new ArrayList<ConferenceDetailRecord>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cdrs.add(toConferenceDetailRecord(result));
}
}
return cdrs;
} finally {
session.close();
}
}
private ConferenceDetailRecord toConferenceDetailRecord(final Map<String, Object> map) {
final Sid sid = DaoUtils.readSid(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final Sid accountSid = DaoUtils.readSid(map.get("account_sid"));
final String status = DaoUtils.readString(map.get("status"));
final String friendlyName = DaoUtils.readString(map.get("friendly_name"));
final String apiVersion = DaoUtils.readString(map.get("api_version"));
final URI uri = DaoUtils.readUri(map.get("uri"));
final String msId = DaoUtils.readString(map.get("master_ms_id"));
final String masterConferenceEndpointId = DaoUtils.readString(map.get("master_conference_endpoint_id"));
final String masterIVREndpointId = DaoUtils.readString(map.get("master_ivr_endpoint_id"));
boolean masterPresent = false;
String masterIVREndpointSessionId = null;
String masterBridgeEndpointId = null;
String masterBridgeEndpointSessionId = null;
String masterBridgeConnectionIdentifier = null;
String masterIVRConnectionIdentifier = null;
boolean moderatorPresent = false;
try {
masterPresent = DaoUtils.readBoolean(map.get("master_present"));
masterIVREndpointSessionId = DaoUtils.readString(map.get("master_ivr_endpoint_session_id"));
masterBridgeEndpointId = DaoUtils.readString(map.get("master_bridge_endpoint_id"));
masterBridgeEndpointSessionId = DaoUtils.readString(map.get("master_bridge_endpoint_session_id"));
masterBridgeConnectionIdentifier = DaoUtils.readString(map.get("master_bridge_conn_id"));
masterIVRConnectionIdentifier = DaoUtils.readString(map.get("master_ivr_conn_id"));
moderatorPresent = DaoUtils.readBoolean(map.get("moderator_present"));
} catch (Exception e) {}
return new ConferenceDetailRecord(sid, dateCreated, dateUpdated, accountSid, status, friendlyName, apiVersion, uri, msId, masterConferenceEndpointId, masterPresent, masterIVREndpointId, masterIVREndpointSessionId, masterBridgeEndpointId, masterBridgeEndpointSessionId, masterBridgeConnectionIdentifier, masterIVRConnectionIdentifier, moderatorPresent);
}
private Map<String, Object> toMap(final ConferenceDetailRecord cdr) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(cdr.getSid()));
map.put("date_created", DaoUtils.writeDateTime(cdr.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(cdr.getDateUpdated()));
map.put("account_sid", DaoUtils.writeSid(cdr.getAccountSid()));
map.put("status", cdr.getStatus());
map.put("friendly_name", cdr.getFriendlyName());
map.put("api_version", cdr.getApiVersion());
map.put("uri", DaoUtils.writeUri(cdr.getUri()));
map.put("master_ms_id", cdr.getMasterMsId());
map.put("master_conference_endpoint_id", cdr.getMasterConferenceEndpointId());
map.put("master_ivr_endpoint_id", cdr.getMasterIVREndpointId());
map.put("master_ivr_endpoint_session_id", cdr.getMasterIVREndpointSessionId());
map.put("master_bridge_endpoint_id", cdr.getMasterBridgeEndpointId());
map.put("master_bridge_endpoint_session_id", cdr.getMasterBridgeEndpointSessionId());
map.put("master_present", cdr.isMasterPresent());
map.put("master_bridge_conn_id", cdr.getMasterBridgeConnectionIdentifier());
map.put("master_ivr_conn_id", cdr.getMasterIVRConnectionIdentifier());
map.put("moderator_present", cdr.isModeratorPresent());
return map;
}
}
| 12,291 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisIncomingPhoneNumbersDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisIncomingPhoneNumbersDao.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.dao.mybatis;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.IncomingPhoneNumbersDao;
import org.restcomm.connect.dao.entities.IncomingPhoneNumberFilter;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.entities.IncomingPhoneNumber;
import org.restcomm.connect.dao.entities.SearchFilterMode;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected]
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisIncomingPhoneNumbersDao implements IncomingPhoneNumbersDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.IncomingPhoneNumbersDao.";
private final SqlSessionFactory sessions;
private final Logger logger = Logger.getLogger(MybatisIncomingPhoneNumbersDao.class.getName());
private static final String ORG_SID = "organization_sid";
private static final String PHONE_NUM = "phone_number";
public MybatisIncomingPhoneNumbersDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addIncomingPhoneNumber(final IncomingPhoneNumber incomingPhoneNumber) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addIncomingPhoneNumber", toMap(incomingPhoneNumber));
session.commit();
} finally {
session.close();
}
}
@Override
public IncomingPhoneNumber getIncomingPhoneNumber(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getIncomingPhoneNumber", sid.toString());
if (result != null) {
return toIncomingPhoneNumber(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<IncomingPhoneNumber> getIncomingPhoneNumbers(final Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getIncomingPhoneNumbers",
accountSid.toString());
final List<IncomingPhoneNumber> incomingPhoneNumbers = new ArrayList<IncomingPhoneNumber>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
incomingPhoneNumbers.add(toIncomingPhoneNumber(result));
}
}
return incomingPhoneNumbers;
} finally {
session.close();
}
}
@Override
public List<IncomingPhoneNumber> getIncomingPhoneNumbersRegex(IncomingPhoneNumberFilter incomingPhoneNumberFilter) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getIncomingPhoneNumbersRegex", incomingPhoneNumberFilter);
final List<IncomingPhoneNumber> incomingPhoneNumbers = new ArrayList<IncomingPhoneNumber>(results.size());
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
incomingPhoneNumbers.add(toIncomingPhoneNumber(result));
}
}
return incomingPhoneNumbers;
} finally {
session.close();
}
}
@Override
public List<IncomingPhoneNumber> getIncomingPhoneNumbersByFilter(IncomingPhoneNumberFilter filter) {
final SqlSession session = sessions.openSession();
try {
String query = "getIncomingPhoneNumbersByFriendlyName";
if (filter.getFilterMode().equals(SearchFilterMode.WILDCARD_MATCH)) {
query = "searchNumbersWithWildcardMode";
}
final List<Map<String, Object>> results = session.selectList(namespace + query,
filter);
final List<IncomingPhoneNumber> incomingPhoneNumbers = new ArrayList<IncomingPhoneNumber>(results.size());
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
incomingPhoneNumbers.add(toIncomingPhoneNumber(result));
}
}
return incomingPhoneNumbers;
} finally {
session.close();
}
}
@Override
public void removeIncomingPhoneNumber(final Sid sid) {
removeIncomingPhoneNumbers("removeIncomingPhoneNumber", sid);
}
@Override
public void removeIncomingPhoneNumbers(final Sid accountSid) {
removeIncomingPhoneNumbers("removeIncomingPhoneNumbers", accountSid);
}
private void removeIncomingPhoneNumbers(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateIncomingPhoneNumber(final IncomingPhoneNumber incomingPhoneNumber) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateIncomingPhoneNumber", toMap(incomingPhoneNumber));
session.commit();
} finally {
session.close();
}
}
@Override
public Integer getTotalIncomingPhoneNumbers(IncomingPhoneNumberFilter filter) {
try (final SqlSession session = sessions.openSession();) {
final Integer total = session.selectOne(namespace + "getTotalIncomingPhoneNumbersByUsingFilters", filter);
return total;
}
}
private IncomingPhoneNumber toIncomingPhoneNumber(final Map<String, Object> map) {
final Sid sid = DaoUtils.readSid(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final String friendlyName = DaoUtils.readString(map.get("friendly_name"));
final Sid accountSid = DaoUtils.readSid(map.get("account_sid"));
final String phoneNumber = DaoUtils.readString(map.get(PHONE_NUM));
final String apiVersion = DaoUtils.readString(map.get("api_version"));
final Boolean hasVoiceCallerIdLookup = DaoUtils.readBoolean(map.get("voice_caller_id_lookup"));
final URI voiceUrl = DaoUtils.readUri(map.get("voice_url"));
final String voiceMethod = DaoUtils.readString(map.get("voice_method"));
final URI voiceFallbackUrl = DaoUtils.readUri(map.get("voice_fallback_url"));
final String voiceFallbackMethod = DaoUtils.readString(map.get("voice_fallback_method"));
final URI statusCallback = DaoUtils.readUri(map.get("status_callback"));
final String statusCallbackMethod = DaoUtils.readString(map.get("status_callback_method"));
final Sid voiceApplicationSid = DaoUtils.readSid(map.get("voice_application_sid"));
final URI smsUrl = DaoUtils.readUri(map.get("sms_url"));
final String smsMethod = DaoUtils.readString(map.get("sms_method"));
final URI smsFallbackUrl = DaoUtils.readUri(map.get("sms_fallback_url"));
final String smsFallbackMethod = DaoUtils.readString(map.get("sms_fallback_method"));
final Sid smsApplicationSid = DaoUtils.readSid(map.get("sms_application_sid"));
final URI uri = DaoUtils.readUri(map.get("uri"));
final URI ussdUrl = DaoUtils.readUri(map.get("ussd_url"));
final String ussdMethod = DaoUtils.readString(map.get("ussd_method"));
final URI ussdFallbackUrl = DaoUtils.readUri(map.get("ussd_fallback_url"));
final String ussdFallbackMethod = DaoUtils.readString(map.get("ussd_fallback_method"));
final Sid ussdApplicationSid = DaoUtils.readSid(map.get("ussd_application_sid"));
final URI referUrl = DaoUtils.readUri(map.get("refer_url"));
final String referMethod = DaoUtils.readString(map.get("refer_method"));
final Sid referApplicationSid = DaoUtils.readSid(map.get("refer_application_sid"));
final Sid organizationSid = DaoUtils.readSid(map.get(ORG_SID));
final Boolean voiceCapable = DaoUtils.readBoolean(map.get("voice_capable"));
final Boolean smsCapable = DaoUtils.readBoolean(map.get("sms_capable"));
final Boolean mmsCapable = DaoUtils.readBoolean(map.get("mms_capable"));
final Boolean faxCapable = DaoUtils.readBoolean(map.get("fax_capable"));
final Boolean pureSip = DaoUtils.readBoolean(map.get("pure_sip"));
final String cost = DaoUtils.readString(map.get("cost"));
// foreign properties loaded from applications table
final String voiceApplicationName = DaoUtils.readString(map.get("voice_application_name"));
final String smsApplicationName = DaoUtils.readString(map.get("sms_application_name"));
final String ussdApplicationName = DaoUtils.readString(map.get("ussd_application_name"));
final String referApplicationName = DaoUtils.readString(map.get("refer_application_name"));
return new IncomingPhoneNumber(sid, dateCreated, dateUpdated, friendlyName, accountSid, phoneNumber, cost, apiVersion,
hasVoiceCallerIdLookup, voiceUrl, voiceMethod, voiceFallbackUrl, voiceFallbackMethod, statusCallback,
statusCallbackMethod, voiceApplicationSid, smsUrl, smsMethod, smsFallbackUrl, smsFallbackMethod,
smsApplicationSid, uri, ussdUrl, ussdMethod, ussdFallbackUrl, ussdFallbackMethod, ussdApplicationSid,
referUrl, referMethod, referApplicationSid,
voiceCapable, smsCapable, mmsCapable, faxCapable, pureSip, voiceApplicationName, smsApplicationName, ussdApplicationName, referApplicationName, organizationSid);
}
private Map<String, Object> toMap(final IncomingPhoneNumber incomingPhoneNumber) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(incomingPhoneNumber.getSid()));
map.put("date_created", DaoUtils.writeDateTime(incomingPhoneNumber.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(incomingPhoneNumber.getDateUpdated()));
map.put("friendly_name", incomingPhoneNumber.getFriendlyName());
map.put("account_sid", DaoUtils.writeSid(incomingPhoneNumber.getAccountSid()));
map.put(PHONE_NUM, incomingPhoneNumber.getPhoneNumber());
map.put("api_version", incomingPhoneNumber.getApiVersion());
map.put("voice_caller_id_lookup", incomingPhoneNumber.hasVoiceCallerIdLookup());
map.put("voice_url", DaoUtils.writeUri(incomingPhoneNumber.getVoiceUrl()));
map.put("voice_method", incomingPhoneNumber.getVoiceMethod());
map.put("voice_fallback_url", DaoUtils.writeUri(incomingPhoneNumber.getVoiceFallbackUrl()));
map.put("voice_fallback_method", incomingPhoneNumber.getVoiceFallbackMethod());
map.put("status_callback", DaoUtils.writeUri(incomingPhoneNumber.getStatusCallback()));
map.put("status_callback_method", incomingPhoneNumber.getStatusCallbackMethod());
map.put("voice_application_sid", DaoUtils.writeSid(incomingPhoneNumber.getVoiceApplicationSid()));
map.put("sms_url", DaoUtils.writeUri(incomingPhoneNumber.getSmsUrl()));
map.put("sms_method", incomingPhoneNumber.getSmsMethod());
map.put("sms_fallback_url", DaoUtils.writeUri(incomingPhoneNumber.getSmsFallbackUrl()));
map.put("sms_fallback_method", incomingPhoneNumber.getSmsFallbackMethod());
map.put("sms_application_sid", DaoUtils.writeSid(incomingPhoneNumber.getSmsApplicationSid()));
map.put("uri", DaoUtils.writeUri(incomingPhoneNumber.getUri()));
map.put("ussd_url", DaoUtils.writeUri(incomingPhoneNumber.getUssdUrl()));
map.put("ussd_method", incomingPhoneNumber.getUssdMethod());
map.put("ussd_fallback_url", DaoUtils.writeUri(incomingPhoneNumber.getUssdFallbackUrl()));
map.put("ussd_fallback_method", incomingPhoneNumber.getUssdFallbackMethod());
map.put("ussd_application_sid", DaoUtils.writeSid(incomingPhoneNumber.getUssdApplicationSid()));
map.put("refer_url", DaoUtils.writeUri(incomingPhoneNumber.getReferUrl()));
map.put("refer_method", incomingPhoneNumber.getReferMethod());
map.put("refer_application_sid", DaoUtils.writeSid(incomingPhoneNumber.getReferApplicationSid()));
map.put("voice_capable", incomingPhoneNumber.isVoiceCapable());
map.put("sms_capable", incomingPhoneNumber.isSmsCapable());
map.put("mms_capable", incomingPhoneNumber.isMmsCapable());
map.put("fax_capable", incomingPhoneNumber.isFaxCapable());
map.put("pure_sip", incomingPhoneNumber.isPureSip());
map.put("cost", incomingPhoneNumber.getCost());
map.put(ORG_SID, DaoUtils.writeSid(incomingPhoneNumber.getOrganizationSid()));
return map;
}
}
| 14,426 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisExtensionsConfigurationDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisExtensionsConfigurationDao.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.dao.mybatis;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.DateTimeComparator;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.ExtensionsConfigurationDao;
import org.restcomm.connect.extension.api.ConfigurationException;
import org.restcomm.connect.extension.api.ExtensionConfiguration;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.restcomm.connect.dao.DaoUtils.readBoolean;
import static org.restcomm.connect.dao.DaoUtils.readDateTime;
/**
* Created by gvagenas on 11/10/2016.
*/
public class MybatisExtensionsConfigurationDao implements ExtensionsConfigurationDao {
private static Logger logger = Logger.getLogger(MybatisExtensionsConfigurationDao.class);
private static final String namespace = "org.restcomm.connect.dao.ExtensionsConfigurationDao.";
private final SqlSessionFactory sessions;
public MybatisExtensionsConfigurationDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addConfiguration(ExtensionConfiguration extensionConfiguration) throws ConfigurationException {
final SqlSession session = sessions.openSession();
try {
if (extensionConfiguration != null && extensionConfiguration.getConfigurationData() != null) {
if (validate(extensionConfiguration)) {
session.insert(namespace + "addConfiguration", toMap(extensionConfiguration));
session.commit();
} else {
throw new ConfigurationException("Exception trying to add new configuration, validation failed. configuration type: "
+ extensionConfiguration.getConfigurationType());
}
}
} finally {
session.close();
}
}
@Override
public void updateConfiguration(ExtensionConfiguration extensionConfiguration) throws ConfigurationException {
final SqlSession session = sessions.openSession();
try {
if (extensionConfiguration != null && extensionConfiguration.getConfigurationData() != null) {
if (validate(extensionConfiguration)) {
session.update(namespace + "updateConfiguration", toMap(extensionConfiguration));
} else {
throw new ConfigurationException("Exception trying to update configuration, validation failed. configuration type: "
+ extensionConfiguration.getConfigurationType());
}
}
session.commit();
} finally {
session.close();
}
}
@Override
public ExtensionConfiguration getConfigurationByName(String extensionName) {
final SqlSession session = sessions.openSession();
ExtensionConfiguration extensionConfiguration = null;
try {
final Map<String, Object> result = session.selectOne(namespace + "getConfigurationByName", extensionName);
if (result != null) {
extensionConfiguration = toExtensionConfiguration(result);
}
return extensionConfiguration;
} finally {
session.close();
}
}
@Override
public ExtensionConfiguration getConfigurationBySid(Sid extensionSid) {
final SqlSession session = sessions.openSession();
ExtensionConfiguration extensionConfiguration = null;
try {
final Map<String, Object> result = session.selectOne(namespace + "getConfigurationBySid", extensionSid.toString());
if (result != null) {
extensionConfiguration = toExtensionConfiguration(result);
}
return extensionConfiguration;
} finally {
session.close();
}
}
@Override
public List<ExtensionConfiguration> getAllConfiguration() {
final SqlSession session = sessions.openSession();
ExtensionConfiguration extensionConfiguration = null;
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getAllConfiguration");
final List<ExtensionConfiguration> confs = new ArrayList<ExtensionConfiguration>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
confs.add(toExtensionConfiguration(result));
}
}
return confs;
} finally {
session.close();
}
}
@Override
public void deleteConfigurationByName(String extensionName) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "deleteConfigurationByName", extensionName);
session.commit();
} finally {
session.close();
}
}
@Override
public void deleteConfigurationBySid(Sid extensionSid) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "deleteConfigurationBySid", extensionSid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public boolean isLatestVersionByName(String extensionName, DateTime dateTime) {
final SqlSession session = sessions.openSession();
boolean result = false;
int comp;
try {
final DateTime dateUpdated = new DateTime(session.selectOne(namespace + "getDateUpdatedByName", extensionName));
if (dateUpdated != null) {
comp = DateTimeComparator.getInstance().compare(dateTime, dateUpdated);
if (comp < 0) {
//Negative value means that given dateTime is less than dateUpdated, which means that DB
//has a newer cnfiguration
result = true;
}
}
} finally {
session.close();
}
return result;
}
@Override
public boolean isLatestVersionBySid(Sid extensionSid, DateTime dateTime) {
final SqlSession session = sessions.openSession();
boolean result = false;
int comp;
try {
final DateTime dateUpdated = new DateTime(session.selectOne(namespace + "getDateUpdatedBySid", extensionSid.toString()));
if (dateUpdated != null) {
comp = DateTimeComparator.getInstance().compare(dateTime, dateUpdated);
if (comp < 0) {
//Negative value means that given dateTime is less than dateUpdated, which means that DB
//has a newer cnfiguration
result = true;
}
}
} finally {
session.close();
}
return result;
}
@Override
public boolean validate(ExtensionConfiguration extensionConfiguration) {
ExtensionConfiguration.configurationType configurationType = extensionConfiguration.getConfigurationType();
if (configurationType.equals(ExtensionConfiguration.configurationType.JSON)) {
Gson gson = new Gson();
try {
Object o = gson.fromJson((String) extensionConfiguration.getConfigurationData(), Object.class);
String json = new GsonBuilder().setPrettyPrinting().create().toJson(o);
return (json != null || !json.isEmpty());
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("invalid json format, exception: "+e);
}
} finally {
gson = null;
}
} else if (configurationType.equals(ExtensionConfiguration.configurationType.XML)) {
Configuration xml = null;
try {
XMLConfiguration xmlConfiguration = new XMLConfiguration();
xmlConfiguration.setDelimiterParsingDisabled(true);
xmlConfiguration.setAttributeSplittingDisabled(true);
InputStream is = IOUtils.toInputStream(extensionConfiguration.getConfigurationData().toString());
xmlConfiguration.load(is);
xml = xmlConfiguration;
return (xml != null || !xml.isEmpty());
} catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("invalid xml document, exception: "+e);
}
} finally {
xml = null;
}
}
return false;
}
private ExtensionConfiguration toExtensionConfiguration(final Map<String, Object> map) {
final Sid sid = new Sid((String)map.get("sid"));
final String extension = (String) map.get("extension");
boolean enabled = true;
if (readBoolean(map.get("enabled")) != null)
enabled = readBoolean(map.get("enabled"));
final Object confData = map.get("configuration_data");
final ExtensionConfiguration.configurationType confType =
ExtensionConfiguration.configurationType.valueOf((String)map.get("configuration_type"));
final DateTime dateCreated = readDateTime(map.get("date_created"));
final DateTime dateUpdated = readDateTime(map.get("date_updated"));
return new ExtensionConfiguration(sid, extension, enabled, confData, confType, dateCreated, dateUpdated);
}
private ExtensionConfiguration toAccountsExtensionConfiguration(final Map<String, Object> map) {
final Sid sid = new Sid((String)map.get("extension"));
final String extension = (String) map.get("extension");
final Object confData = map.get("configuration_data");
return new ExtensionConfiguration(sid, extension, true, confData, null, null, null);
}
private Map<String, Object> toMap(final ExtensionConfiguration extensionConfiguration) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(extensionConfiguration.getSid()));
map.put("extension", extensionConfiguration.getExtensionName());
if (extensionConfiguration.getConfigurationData() != null)
map.put("configuration_data", extensionConfiguration.getConfigurationData());
if (extensionConfiguration.getConfigurationType() != null)
map.put("configuration_type", extensionConfiguration.getConfigurationType().toString());
if (extensionConfiguration.getDateCreated() != null)
map.put("date_created", DaoUtils.writeDateTime(extensionConfiguration.getDateCreated()));
if (extensionConfiguration.getDateUpdated() != null)
map.put("date_updated", DaoUtils.writeDateTime(extensionConfiguration.getDateUpdated()));
map.put("enabled", extensionConfiguration.isEnabled());
return map;
}
@Override
public ExtensionConfiguration getAccountExtensionConfiguration(String accountSid, String extensionSid) {
final SqlSession session = sessions.openSession();
ExtensionConfiguration extensionConfiguration = null;
try {
Map<String, Object> params = new HashMap<String, Object>();
params.put("account_sid", accountSid.toString());
params.put("extension_sid", extensionSid.toString());
final Map<String, Object> result = session.selectOne(namespace + "getAccountExtensionConfiguration", params);
if (result != null) {
extensionConfiguration = toAccountsExtensionConfiguration(result);
}
return extensionConfiguration;
} finally {
session.close();
}
}
@Override
public void addAccountExtensionConfiguration(ExtensionConfiguration extensionConfiguration, Sid accountSid) throws ConfigurationException {
final SqlSession session = sessions.openSession();
try {
if (extensionConfiguration != null && extensionConfiguration.getConfigurationData() != null) {
if (validate(extensionConfiguration)) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("account_sid", DaoUtils.writeSid(accountSid));
map.put("extension_sid", DaoUtils.writeSid(extensionConfiguration.getSid()));
if (extensionConfiguration.getConfigurationData() != null)
map.put("configuration_data", extensionConfiguration.getConfigurationData());
session.insert(namespace + "addAccountExtensionConfiguration", map);
session.commit();
} else {
throw new ConfigurationException("Exception trying to add new configuration, validation failed. configuration type: "
+ extensionConfiguration.getConfigurationType());
}
}
} finally {
session.close();
}
}
@Override
public void updateAccountExtensionConfiguration(ExtensionConfiguration extensionConfiguration, Sid accountSid)
throws ConfigurationException {
final SqlSession session = sessions.openSession();
try {
if (extensionConfiguration != null && extensionConfiguration.getConfigurationData() != null) {
if (validate(extensionConfiguration)) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("account_sid", DaoUtils.writeSid(accountSid));
map.put("extension_sid", DaoUtils.writeSid(extensionConfiguration.getSid()));
if (extensionConfiguration.getConfigurationData() != null)
map.put("configuration_data", extensionConfiguration.getConfigurationData());
session.update(namespace + "updateAccountExtensionConfiguration", map);
} else {
throw new ConfigurationException("Exception trying to update configuration, validation failed. configuration type: "
+ extensionConfiguration.getConfigurationType());
}
}
session.commit();
} finally {
session.close();
}
}
@Override
public void deleteAccountExtensionConfiguration(String accountSid, String extensionSid) {
final SqlSession session = sessions.openSession();
try {
Map<String, Object> params = new HashMap<String, Object>();
params.put("account_sid", accountSid.toString());
params.put("extension_sid", extensionSid.toString());
session.delete(namespace + "deleteAccountExtensionConfiguration", params);
session.commit();
} finally {
session.close();
}
}
}
| 16,251 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisGatewaysDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisGatewaysDao.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.dao.mybatis;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.GatewaysDao;
import org.restcomm.connect.dao.entities.Gateway;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
/**
* @author [email protected] (Thomas Quintana)
*/
@ThreadSafe
public final class MybatisGatewaysDao implements GatewaysDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.GatewaysDao.";
private final SqlSessionFactory sessions;
public MybatisGatewaysDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addGateway(final Gateway gateway) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addGateway", toMap(gateway));
session.commit();
} finally {
session.close();
}
}
@Override
public Gateway getGateway(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getGateway", sid.toString());
if (result != null) {
return toGateway(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Gateway> getGateways() {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getGateways");
final List<Gateway> gateways = new ArrayList<Gateway>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
gateways.add(toGateway(result));
}
}
return gateways;
} finally {
session.close();
}
}
@Override
public void removeGateway(final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "removeGateway", sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateGateway(final Gateway gateway) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateGateway", toMap(gateway));
session.commit();
} finally {
session.close();
}
}
private Gateway toGateway(final Map<String, Object> map) {
final Sid sid = DaoUtils.readSid(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final String friendlName = DaoUtils.readString(map.get("friendly_name"));
final String password = DaoUtils.readString(map.get("password"));
final String proxy = DaoUtils.readString(map.get("proxy"));
final Boolean register = DaoUtils.readBoolean(map.get("register"));
final String userAgent = DaoUtils.readString(map.get("user_name"));
final Integer timeToLive = DaoUtils.readInteger(map.get("ttl"));
final URI uri = DaoUtils.readUri(map.get("uri"));
return new Gateway(sid, dateCreated, dateUpdated, friendlName, password, proxy, register, userAgent, timeToLive, uri);
}
private Map<String, Object> toMap(final Gateway gateway) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(gateway.getSid()));
map.put("date_created", DaoUtils.writeDateTime(gateway.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(gateway.getDateUpdated()));
map.put("friendly_name", gateway.getFriendlyName());
map.put("password", gateway.getPassword());
map.put("proxy", gateway.getProxy());
map.put("register", gateway.register());
map.put("user_name", gateway.getUserName());
map.put("ttl", gateway.getTimeToLive());
map.put("uri", DaoUtils.writeUri(gateway.getUri()));
return map;
}
}
| 5,429 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisOrganizationDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisOrganizationDao.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.dao.mybatis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.OrganizationsDao;
import org.restcomm.connect.dao.entities.Organization;
/**
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisOrganizationDao implements OrganizationsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.OrganizationsDao.";
private final SqlSessionFactory sessions;
public MybatisOrganizationDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addOrganization(final Organization organization) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addOrganization", toMap(organization));
session.commit();
} finally {
session.close();
}
}
@Override
public Organization getOrganization(Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getOrganization", sid.toString());
if (result != null) {
return toOrganization(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public Organization getOrganizationByDomainName(String domainName) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getOrganizationByDomainName", domainName);
if (result != null) {
return toOrganization(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Organization> getOrganizationsByStatus(Organization.Status status) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getOrganizationsByStatus", status.toString());
final List<Organization> organization = new ArrayList<Organization>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
organization.add(toOrganization(result));
}
}
return organization;
} finally {
session.close();
}
}
@Override
public List<Organization> getAllOrganizations() {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getAllOrganizations");
final List<Organization> organization = new ArrayList<Organization>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
organization.add(toOrganization(result));
}
}
return organization;
} finally {
session.close();
}
}
@Override
public void updateOrganization(Organization organization) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateOrganization", toMap(organization));
session.commit();
} finally {
session.close();
}
}
private Organization toOrganization(final Map<String, Object> map) {
final Sid sid = DaoUtils.readSid(map.get("sid"));
final String domainName = DaoUtils.readString(map.get("domain_name"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final Organization.Status status = DaoUtils.readOrganizationStatus(map.get("status"));
return new Organization(sid, domainName, dateCreated, dateUpdated, status);
}
private Map<String, Object> toMap(final Organization org) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(org.getSid()));
map.put("domain_name", org.getDomainName());
map.put("date_created", DaoUtils.writeDateTime(org.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(org.getDateUpdated()));
map.put("status", DaoUtils.writeOrganizationStatus(org.getStatus()));
return map;
}
}
| 5,810 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisProfilesDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisProfilesDao.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.dao.mybatis;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.ProfilesDao;
import org.restcomm.connect.dao.entities.Profile;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisProfilesDao implements ProfilesDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.ProfilesDao.";
private final SqlSessionFactory sessions;
public MybatisProfilesDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public Profile getProfile(String sid) throws SQLException {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getProfile", sid.toString());
if (result != null) {
return toProfile(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Profile> getAllProfiles() throws SQLException {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getAllProfiles");
final List<Profile> profiles = new ArrayList<Profile>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
profiles.add(toProfile(result));
}
}
return profiles;
} finally {
session.close();
}
}
@Override
public int addProfile(Profile profile) {
final SqlSession session = sessions.openSession();
int effectedRows = 0;
try {
effectedRows = session.insert(namespace + "addProfile", profile);
session.commit();
} finally {
session.close();
}
return effectedRows;
}
@Override
public void updateProfile(Profile profile) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateProfile", profile);
session.commit();
} finally {
session.close();
}
}
@Override
public void deleteProfile(String sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "deleteProfile", sid);
session.commit();
} finally {
session.close();
}
}
private Profile toProfile(final Map<String, Object> map) throws SQLException {
final String sid = DaoUtils.readString(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
// byte[] documentArr = null;
// if (map.get("document") instanceof Blob) {
// final Blob document = (Blob) map.get("document");
// documentArr = document.getBytes(1, (int) document.length());
// } else {
// documentArr = (byte[]) map.get("document");
// }
final String document = DaoUtils.readString(map.get("document"));
return new Profile(sid, document, dateCreated.toDate(), dateUpdated.toDate());
}
}
| 4,548 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisProfileAssociationsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisProfileAssociationsDao.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.dao.mybatis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.ProfileAssociationsDao;
import org.restcomm.connect.dao.entities.ProfileAssociation;
/**
* @author [email protected] (Maria Farooq)
*/
@ThreadSafe
public final class MybatisProfileAssociationsDao implements ProfileAssociationsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.ProfileAssociationsDao.";
private final SqlSessionFactory sessions;
public MybatisProfileAssociationsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public ProfileAssociation getProfileAssociationByTargetSid(String targetSid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(namespace + "getProfileAssociationByTargetSid", targetSid);
if (result != null) {
return toProfileAssociation(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<ProfileAssociation> getProfileAssociationsByProfileSid(String profileSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getProfileAssociationsByProfileSid", profileSid);
final List<ProfileAssociation> profiles = new ArrayList<ProfileAssociation>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
profiles.add(toProfileAssociation(result));
}
}
return profiles;
} finally {
session.close();
}
}
@Override
public int addProfileAssociation(ProfileAssociation profileAssociation) {
final SqlSession session = sessions.openSession();
int effectedRows = 0;
try {
effectedRows = session.insert(namespace + "addProfileAssociation", toMap(profileAssociation));
session.commit();
} finally {
session.close();
}
return effectedRows;
}
@Override
public void updateProfileAssociationOfTargetSid(ProfileAssociation profileAssociation) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateProfileAssociationOfTargetSid", toMap(profileAssociation));
session.commit();
} finally {
session.close();
}
}
@Override
public void updateAssociatedProfileOfAllSuchProfileSid(String oldProfileSid, String newProfileSid) {
final SqlSession session = sessions.openSession();
try {
Map<String, Object> map = new HashMap<String, Object>();
map.put("profile_sid", newProfileSid);
map.put("old_profile_sid", oldProfileSid);
session.update(namespace + "updateAssociatedProfileOfAllSuchProfileSid", map);
session.commit();
map = null;
} finally {
session.close();
}
}
@Override
public void deleteProfileAssociationByProfileSid(String profileSid) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "deleteProfileAssociationByProfileSid", profileSid);
session.commit();
} finally {
session.close();
}
}
@Override
public int deleteProfileAssociationByTargetSid(String targetSid, String profileSid) {
int removed = 0;
final SqlSession session = sessions.openSession();
final Map<String, Object> map = new HashMap<String, Object>();
map.put("profile_sid", profileSid);
map.put("target_sid", targetSid);
try {
removed = session.delete(namespace + "deleteProfileAssociationByTargetSid", map);
session.commit();
} finally {
session.close();
}
return removed;
}
private ProfileAssociation toProfileAssociation(final Map<String, Object> map) {
final Sid profileSid = DaoUtils.readSid(map.get("profile_sid"));
final Sid targetSid = DaoUtils.readSid(map.get("target_sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
return new ProfileAssociation(profileSid, targetSid, dateCreated.toDate(), dateUpdated.toDate());
}
private Map<String, Object> toMap(final ProfileAssociation profileAssociation) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("profile_sid", DaoUtils.writeSid(profileAssociation.getProfileSid()));
map.put("target_sid", DaoUtils.writeSid(profileAssociation.getTargetSid()));
map.put("date_created", profileAssociation.getDateCreated());
map.put("date_updated", profileAssociation.getDateCreated());
return map;
}
@Override
public int deleteProfileAssociationByTargetSid(String targetSid) {
return deleteProfileAssociationByTargetSid(targetSid, null);
}
}
| 6,518 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisTranscriptionsDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisTranscriptionsDao.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.dao.mybatis;
import java.math.BigDecimal;
import java.net.URI;
import java.util.ArrayList;
import java.util.Currency;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.joda.time.DateTime;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.TranscriptionsDao;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.entities.Transcription;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
import org.restcomm.connect.dao.entities.TranscriptionFilter;
/**
* @author [email protected] (Thomas Quintana)
*/
@ThreadSafe
public final class MybatisTranscriptionsDao implements TranscriptionsDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.TranscriptionsDao.";
private final SqlSessionFactory sessions;
public MybatisTranscriptionsDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addTranscription(final Transcription transcription) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addTranscription", toMap(transcription));
session.commit();
} finally {
session.close();
}
}
@Override
public Transcription getTranscription(final Sid sid) {
return getTranscription(namespace + "getTranscription", sid);
}
@Override
public Transcription getTranscriptionByRecording(final Sid recordingSid) {
return getTranscription(namespace + "getTranscriptionByRecording", recordingSid);
}
private Transcription getTranscription(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
final Map<String, Object> result = session.selectOne(selector, sid.toString());
if (result != null) {
return toTranscription(result);
} else {
return null;
}
} finally {
session.close();
}
}
@Override
public List<Transcription> getTranscriptions(final Sid accountSid) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session
.selectList(namespace + "getTranscriptions", accountSid.toString());
final List<Transcription> transcriptions = new ArrayList<Transcription>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
transcriptions.add(toTranscription(result));
}
}
return transcriptions;
} finally {
session.close();
}
}
@Override
public List<Transcription> getTranscriptions(TranscriptionFilter filter) {
final SqlSession session = sessions.openSession();
try {
final List<Map<String, Object>> results = session.selectList(namespace + "getTranscriptionsByUsingFilters",
filter);
final List<Transcription> cdrs = new ArrayList<Transcription>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
cdrs.add(toTranscription(result));
}
}
return cdrs;
} finally {
session.close();
}
}
@Override
public Integer getTotalTranscription(TranscriptionFilter filter) {
final SqlSession session = sessions.openSession();
try {
final Integer total = session.selectOne(namespace + "getTotalTranscriptionByUsingFilters", filter);
return total;
} finally {
session.close();
}
}
@Override
public void removeTranscription(final Sid sid) {
removeTranscriptions(namespace + "removeTranscription", sid);
}
@Override
public void removeTranscriptions(final Sid accountSid) {
removeTranscriptions(namespace + "removeTranscriptions", accountSid);
}
private void removeTranscriptions(final String selector, final Sid sid) {
final SqlSession session = sessions.openSession();
try {
session.delete(selector, sid.toString());
session.commit();
} finally {
session.close();
}
}
@Override
public void updateTranscription(final Transcription transcription) {
final SqlSession session = sessions.openSession();
try {
session.update(namespace + "updateTranscription", toMap(transcription));
session.commit();
} finally {
session.close();
}
}
private Map<String, Object> toMap(final Transcription transcription) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("sid", DaoUtils.writeSid(transcription.getSid()));
map.put("date_created", DaoUtils.writeDateTime(transcription.getDateCreated()));
map.put("date_updated", DaoUtils.writeDateTime(transcription.getDateUpdated()));
map.put("account_sid", DaoUtils.writeSid(transcription.getAccountSid()));
map.put("status", transcription.getStatus().toString());
map.put("recording_sid", DaoUtils.writeSid(transcription.getRecordingSid()));
map.put("duration", transcription.getDuration());
map.put("transcription_text", transcription.getTranscriptionText());
map.put("price", DaoUtils.writeBigDecimal(transcription.getPrice()));
map.put("price_unit", DaoUtils.writeCurrency(transcription.getPriceUnit()));
map.put("uri", DaoUtils.writeUri(transcription.getUri()));
return map;
}
private Transcription toTranscription(final Map<String, Object> map) {
final Sid sid = DaoUtils.readSid(map.get("sid"));
final DateTime dateCreated = DaoUtils.readDateTime(map.get("date_created"));
final DateTime dateUpdated = DaoUtils.readDateTime(map.get("date_updated"));
final Sid accountSid = DaoUtils.readSid(map.get("account_sid"));
final String text = DaoUtils.readString(map.get("status"));
final Transcription.Status status = Transcription.Status.getStatusValue(text);
final Sid recordingSid = DaoUtils.readSid(map.get("recording_sid"));
final Double duration = DaoUtils.readDouble(map.get("duration"));
final String transcriptionText = DaoUtils.readString(map.get("transcription_text"));
final BigDecimal price = DaoUtils.readBigDecimal(map.get("price"));
final Currency priceUnit = DaoUtils.readCurrency(map.get("price_unit"));
final URI uri = DaoUtils.readUri(map.get("uri"));
return new Transcription(sid, dateCreated, dateUpdated, accountSid, status, recordingSid, duration, transcriptionText,
price, priceUnit, uri);
}
}
| 7,963 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MybatisAvailablePhoneNumbersDao.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/main/java/org/restcomm/connect/dao/mybatis/MybatisAvailablePhoneNumbersDao.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.dao.mybatis;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.restcomm.connect.dao.DaoUtils;
import org.restcomm.connect.dao.AvailablePhoneNumbersDao;
import org.restcomm.connect.dao.entities.AvailablePhoneNumber;
import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe;
/**
* @author [email protected] (Thomas Quintana)
*/
@ThreadSafe
public final class MybatisAvailablePhoneNumbersDao implements AvailablePhoneNumbersDao {
private static final String namespace = "org.mobicents.servlet.sip.restcomm.dao.AvailablePhoneNumbersDao.";
private static final char[] lookupTable = new char[] { '2', '2', '2', '3', '3', '3', '4', '4', '4', '5', '5', '5', '6',
'6', '6', '7', '7', '7', '7', '8', '8', '8', '9', '9', '9', '9' };
private final SqlSessionFactory sessions;
public MybatisAvailablePhoneNumbersDao(final SqlSessionFactory sessions) {
super();
this.sessions = sessions;
}
@Override
public void addAvailablePhoneNumber(final AvailablePhoneNumber availablePhoneNumber) {
final SqlSession session = sessions.openSession();
try {
session.insert(namespace + "addAvailablePhoneNumber", toMap(availablePhoneNumber));
session.commit();
} finally {
session.close();
}
}
private List<AvailablePhoneNumber> getAvailablePhoneNumbers(final String selector, final Object parameter) {
final SqlSession session = sessions.openSession();
try {
List<Map<String, Object>> results = null;
if (parameter == null) {
results = session.selectList(selector);
} else {
results = session.selectList(selector, parameter);
}
final List<AvailablePhoneNumber> availablePhoneNumbers = new ArrayList<AvailablePhoneNumber>();
if (results != null && !results.isEmpty()) {
for (final Map<String, Object> result : results) {
availablePhoneNumbers.add(toAvailablePhoneNumber(result));
}
}
return availablePhoneNumbers;
} finally {
session.close();
}
}
@Override
public List<AvailablePhoneNumber> getAvailablePhoneNumbers() {
return getAvailablePhoneNumbers(namespace + "getAvailablePhoneNumbers", null);
}
@Override
public List<AvailablePhoneNumber> getAvailablePhoneNumbersByAreaCode(final String areaCode) {
final String phoneNumber = new StringBuilder().append("+1").append(areaCode).append("_______").toString();
return getAvailablePhoneNumbers(namespace + "getAvailablePhoneNumbersByAreaCode", phoneNumber);
}
@Override
public List<AvailablePhoneNumber> getAvailablePhoneNumbersByPattern(final String pattern) throws IllegalArgumentException {
return getAvailablePhoneNumbers(namespace + "getAvailablePhoneNumbersByPattern", normalizePattern(pattern));
}
@Override
public List<AvailablePhoneNumber> getAvailablePhoneNumbersByRegion(final String region) {
return getAvailablePhoneNumbers(namespace + "getAvailablePhoneNumbersByRegion", region);
}
@Override
public List<AvailablePhoneNumber> getAvailablePhoneNumbersByPostalCode(final int postalCode) {
return getAvailablePhoneNumbers(namespace + "getAvailablePhoneNumbersByPostalCode", postalCode);
}
private String normalizePattern(final String input) throws IllegalArgumentException {
final char[] tokens = input.toUpperCase().toCharArray();
final char[] result = new char[tokens.length];
for (int index = 0; index < tokens.length; index++) {
final char token = tokens[index];
if (token == '+' || Character.isDigit(token)) {
result[index] = token;
continue;
} else if (token == '*') {
result[index] = '_';
continue;
} else if (Character.isLetter(token)) {
final int delta = 65; // The decimal distance from 0x0000 to 0x0041 which equals to 'A'
final int position = Character.getNumericValue(token) - delta;
result[index] = lookupTable[position];
} else {
throw new IllegalArgumentException(token + " is not a valid character.");
}
}
return new String(result);
}
@Override
public void removeAvailablePhoneNumber(final String phoneNumber) {
final SqlSession session = sessions.openSession();
try {
session.delete(namespace + "removeAvailablePhoneNumber", phoneNumber);
session.commit();
} finally {
session.close();
}
}
private AvailablePhoneNumber toAvailablePhoneNumber(final Map<String, Object> map) {
final String friendlyName = DaoUtils.readString(map.get("friendly_name"));
final String phoneNumber = DaoUtils.readString(map.get("phone_number"));
final Integer lata = DaoUtils.readInteger(map.get("lata"));
final String rateCenter = DaoUtils.readString(map.get("rate_center"));
final Double latitude = DaoUtils.readDouble(map.get("latitude"));
final Double longitude = DaoUtils.readDouble(map.get("longitude"));
final String region = DaoUtils.readString(map.get("region"));
final Integer postalCode = DaoUtils.readInteger(map.get("postal_code"));
final String isoCountry = DaoUtils.readString(map.get("iso_country"));
final Boolean voiceCapable = DaoUtils.readBoolean(map.get("voice_capable"));
final Boolean smsCapable = DaoUtils.readBoolean(map.get("sms_capable"));
final Boolean mmsCapable = DaoUtils.readBoolean(map.get("mms_capable"));
final Boolean faxCapable = DaoUtils.readBoolean(map.get("fax_capable"));
final String cost = DaoUtils.readString(map.get("cost"));
return new AvailablePhoneNumber(friendlyName, phoneNumber, lata, rateCenter, latitude, longitude, region, postalCode,
isoCountry, cost, voiceCapable, smsCapable, mmsCapable, faxCapable);
}
private Map<String, Object> toMap(final AvailablePhoneNumber availablePhoneNumber) {
final Map<String, Object> map = new HashMap<String, Object>();
map.put("friendly_name", availablePhoneNumber.getFriendlyName());
map.put("phone_number", availablePhoneNumber.getPhoneNumber());
map.put("lata", availablePhoneNumber.getLata());
map.put("rate_center", availablePhoneNumber.getRateCenter());
map.put("latitude", availablePhoneNumber.getLatitude());
map.put("longitude", availablePhoneNumber.getLongitude());
map.put("region", availablePhoneNumber.getRegion());
map.put("postal_code", availablePhoneNumber.getPostalCode());
map.put("iso_country", availablePhoneNumber.getIsoCountry());
map.put("voice_capable", availablePhoneNumber.isVoiceCapable());
map.put("sms_capable", availablePhoneNumber.isSmsCapable());
map.put("mms_capable", availablePhoneNumber.isMmsCapable());
map.put("fax_capable", availablePhoneNumber.isFaxCapable());
map.put("cost", availablePhoneNumber.getCost());
return map;
}
}
| 8,295 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaServerConferenceControllerStateChanged.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/mobicents/servlet/restcomm/mscontrol/messages/MediaServerConferenceControllerStateChanged.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.mobicents.servlet.restcomm.mscontrol.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.mscontrol.api.messages.MediaServerControllerStateChanged;
import org.restcomm.connect.mscontrol.api.messages.MediaSessionInfo;
/**
* @author Maria
*
*/
@Immutable
public final class MediaServerConferenceControllerStateChanged extends MediaServerControllerStateChanged{
private final Sid conferenceSid;
private final String conferenceState;
private final boolean moderatorPresent;
public MediaServerConferenceControllerStateChanged(final MediaServerControllerState state, MediaSessionInfo mediaSession, final Sid conferenceSid, final String conferenceState, final boolean moderatorPresent) {
super(state, mediaSession);
this.conferenceSid = conferenceSid;
this.conferenceState = conferenceState;
this.moderatorPresent = moderatorPresent;
}
public MediaServerConferenceControllerStateChanged(final MediaServerControllerState state, MediaSessionInfo mediaSession, final Sid conferenceSid) {
this(state, mediaSession, conferenceSid, null, false);
}
public MediaServerConferenceControllerStateChanged(final MediaServerControllerState state, final Sid conferenceSid, final String conferenceState) {
this(state, null, conferenceSid, conferenceState, false);
}
public MediaServerConferenceControllerStateChanged(final MediaServerControllerState state, final Sid conferenceSid, final String conferenceState, final boolean moderatorPresent) {
this(state, null, conferenceSid, conferenceState, moderatorPresent);
}
public MediaServerConferenceControllerStateChanged(final MediaServerControllerState state, final Sid conferenceSid) {
this(state, null, conferenceSid, null, false);
}
public Sid conferenceSid() {
return conferenceSid;
}
public String conferenceState() {
return conferenceState;
}
public boolean moderatorPresent (){
return moderatorPresent;
}
}
| 3,049 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaServerControllerFactory.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/MediaServerControllerFactory.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.api;
import akka.actor.Props;
/**
* @author Henrique Rosa ([email protected])
*
*/
public interface MediaServerControllerFactory {
/**
* Provides a new Media Server Controller Props for a Call.
*
* @return The media server controller props
*/
Props provideCallControllerProps();
/**
* Provides a new Media Server Controller Props for a Conference.
*
* @return The media server controller props
*/
Props provideConferenceControllerProps();
/**
* Provides a new Media Server Controller Props for a Bridge.
*
* @return The media server controller props
*/
Props provideBridgeControllerProps();
}
| 1,653 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaResponse.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/MediaResponse.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.api;
import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe;
import org.restcomm.connect.commons.patterns.StandardResponse;
/**
* Generic response to a request made to the {@link MediaServerController}.
* @author Henrique Rosa ([email protected])
* @param <T> The type of the object wrapped in the response.
*/
@NotThreadSafe
public class MediaResponse<T> extends StandardResponse<T> {
public MediaResponse(T object) {
super(object);
}
public MediaResponse(final Throwable cause) {
super(cause);
}
public MediaResponse(final Throwable cause, final String message) {
super(cause, message);
}
}
| 1,636 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaGroup.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/MediaGroup.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
/**
* @author [email protected] (Thomas Quintana)
*/
public abstract class MediaGroup extends RestcommUntypedActor {
}
| 1,060 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaServerInfo.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/MediaServerInfo.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.api;
import java.net.InetAddress;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class MediaServerInfo {
private final String name;
private final InetAddress address;
private final int port;
private final int timeout;
public MediaServerInfo(String name, InetAddress address, int port, int timeout) {
super();
this.name = name;
this.address = address;
this.port = port;
this.timeout = timeout;
}
public String getName() {
return name;
}
public InetAddress getAddress() {
return address;
}
public int getPort() {
return port;
}
public int getTimeout() {
return timeout;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Media Server Information: ").append(this.name).append("\n");
builder.append("Address: ").append(this.address.getHostAddress()).append("\n");
builder.append("Port: ").append(this.port).append("\n");
builder.append("Timeout: ").append(this.timeout).append("\n");
return builder.toString();
}
}
| 2,204 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaSession.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/MediaSession.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.api;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class MediaSession {
private final int id;
public MediaSession(final int id) {
super();
this.id = id;
}
public int getId() {
return id;
}
}
| 1,313 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaServerController.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/MediaServerController.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.mscontrol.api;
import akka.actor.ActorRef;
import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor;
import org.restcomm.connect.commons.fsm.Action;
/**
* Controls the flow of media sessions.
*
* @author Henrique Rosa ([email protected])
*/
public abstract class MediaServerController extends RestcommUntypedActor {
protected MediaServerController() {
super();
}
/*
* ACTIONS
*/
protected abstract class AbstractAction implements Action {
protected final ActorRef source;
public AbstractAction(final ActorRef source) {
super();
this.source = source;
}
}
}
| 1,517 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaServerControllerException.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/exceptions/MediaServerControllerException.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.api.exceptions;
/**
* @author Henrique Rosa ([email protected])
*
*/
public class MediaServerControllerException extends Exception {
private static final long serialVersionUID = -3369602773575455629L;
public MediaServerControllerException(String message, Throwable cause) {
super(message, cause);
}
public MediaServerControllerException(String message) {
super(message);
}
public MediaServerControllerException(Throwable cause) {
super(cause);
}
}
| 1,476 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
StopRecording.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/StopRecording.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.apache.commons.configuration.Configuration;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.commons.dao.Sid;
/**
* Use this to notify a Call object that needs to Record
* @author <a href="mailto:[email protected]">gvagenas</a>
*/
public class StopRecording {
private Sid accountId;
private Configuration runtimeSetting;
private DaoManager daoManager;
public StopRecording(final Sid accountId, final Configuration runtimeSettings, final DaoManager daoManager) {
this.accountId = accountId;
this.runtimeSetting = runtimeSettings;
this.daoManager = daoManager;
}
public Sid getAccountId() {
return accountId;
}
public Configuration getRuntimeSetting() {
return runtimeSetting;
}
public DaoManager getDaoManager() {
return daoManager;
}
}
| 1,737 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaServerControllerError.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaServerControllerError.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*/
@Immutable
public final class MediaServerControllerError {
private final Throwable error;
public MediaServerControllerError(Throwable error) {
super();
this.error = error;
}
public MediaServerControllerError() {
this(null);
}
public Throwable getError() {
return error;
}
}
| 1,446 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Mute.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Mute.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class Mute {
public Mute() {
super();
}
}
| 1,082 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaServerControllerStateChanged.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaServerControllerStateChanged.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public class MediaServerControllerStateChanged {
public enum MediaServerControllerState {
PENDING, ACTIVE, FAILED, INACTIVE;
}
private final MediaServerControllerState state;
private final MediaSessionInfo mediaSession;
public MediaServerControllerStateChanged(MediaServerControllerState state, MediaSessionInfo mediaSession) {
this.state = state;
this.mediaSession = mediaSession;
}
public MediaServerControllerStateChanged(MediaServerControllerState state) {
this(state, null);
}
public MediaServerControllerState getState() {
return state;
}
public MediaSessionInfo getMediaSession() {
return mediaSession;
}
}
| 1,837 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
QueryMediaMixer.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/QueryMediaMixer.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class QueryMediaMixer {
public QueryMediaMixer() {
super();
}
}
| 1,216 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RecordStoped.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/RecordStoped.java | package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Hoan Luu ([email protected])
*/
@Immutable
public class RecordStoped {
public RecordStoped() {
super();
}
}
| 273 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Unmute.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Unmute.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class Unmute {
public Unmute() {
super();
}
}
| 1,086 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Stop.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Stop.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class Stop {
private final boolean createRecord;
public Stop(final boolean createRecord) {
super();
this.createRecord = createRecord;
}
public Stop() {
this(false);
}
public boolean createRecord() {
return createRecord;
}
}
| 1,312 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
StartMediaGroup.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/StartMediaGroup.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class StartMediaGroup {
public StartMediaGroup() {
super();
}
}
| 1,104 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaGroupDestroyed.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaGroupDestroyed.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class MediaGroupDestroyed {
public MediaGroupDestroyed() {
super();
}
}
| 1,224 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaSessionClosed.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaSessionClosed.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*/
@Immutable
public final class MediaSessionClosed {
public MediaSessionClosed() {
super();
}
}
| 1,218 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Leave.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Leave.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class Leave {
private boolean liveCallModification;
public Leave() {
super();
}
public Leave(final boolean liveCallModification) {
super();
this.liveCallModification = true;
}
public boolean isLiveCallModification() {
return liveCallModification;
}
}
| 1,339 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaSessionInfo.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaSessionInfo.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.api.messages;
import java.net.InetAddress;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class MediaSessionInfo {
private final boolean useNat;
private final InetAddress externalAddress;
private final String localSdp;
private final String remoteSdp;
public MediaSessionInfo() {
this(false, null, "", "");
}
public MediaSessionInfo(boolean useNat, InetAddress externalAddress, String localSdp, String remoteSdp) {
super();
this.useNat = useNat;
this.externalAddress = externalAddress;
this.localSdp = localSdp;
this.remoteSdp = remoteSdp;
}
public boolean usesNat() {
return this.useNat;
}
public InetAddress getExternalAddress() {
return externalAddress;
}
public String getLocalSdp() {
return localSdp;
}
public String getRemoteSdp() {
return remoteSdp;
}
}
| 1,986 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CloseMediaSession.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/CloseMediaSession.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*/
@Immutable
public final class CloseMediaSession {
public CloseMediaSession() {
super();
}
}
| 1,216 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaGroupResponse.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaGroupResponse.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.patterns.StandardResponse;
/**
* @author [email protected] (Thomas Quintana)
*/
public final class MediaGroupResponse<T> extends StandardResponse<T> {
public MediaGroupResponse(final T object) {
super(object);
}
public MediaGroupResponse(final Throwable cause) {
super(cause);
}
public MediaGroupResponse(final Throwable cause, final String message) {
super(cause, message);
}
}
| 1,341 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
JoinComplete.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/JoinComplete.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import akka.actor.ActorRef;
import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class JoinComplete {
private final ActorRef endpoint;
private int sessionid;
private ConnectionIdentifier connectionIdentifier;
public JoinComplete() {
this(null);
}
public JoinComplete(final ActorRef endpoint) {
this.endpoint = endpoint;
}
public JoinComplete(ActorRef bridgeEndpoint, int sessionid) {
this(bridgeEndpoint, sessionid, null);
}
public JoinComplete(ActorRef bridgeEndpoint, int sessionid, ConnectionIdentifier connectionIdentifier) {
super();
this.endpoint = bridgeEndpoint;
this.sessionid = sessionid;
this.connectionIdentifier = connectionIdentifier;
}
public Object endpoint() {
return endpoint;
}
public int sessionid() {
return sessionid;
}
public ConnectionIdentifier connectionIdentifier() {
return connectionIdentifier;
}
}
| 2,021 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Record.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Record.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.dao.entities.MediaAttributes;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class Record {
private static final List<URI> empty = new ArrayList<URI>(0);
private final URI destination;
private final List<URI> prompts;
private int timeout;
private final int length;
private String endInputKey;
private final MediaAttributes.MediaType media;
/**
* @param recordingId
* @param prompts
* @param timeout
* @param length
* @param endInputKey
* @param mediaType
*/
public Record(final URI recordingId, final List<URI> prompts, final int timeout, final int length, final String endInputKey, final MediaAttributes.MediaType mediaType) {
super();
this.destination = recordingId;
this.prompts = prompts;
this.timeout = timeout;
this.length = length;
this.endInputKey = endInputKey;
this.media = mediaType;
}
/**
* @param recordingId
* @param timeout
* @param length
* @param endInputKey
* @param mediaType
*/
public Record(final URI recordingId, final int timeout, final int length, final String endInputKey, final MediaAttributes.MediaType mediaType) {
super();
this.destination = recordingId;
this.prompts = empty;
this.timeout = timeout;
this.length = length;
this.endInputKey = endInputKey;
this.media = mediaType;
}
/**
* @param recordingId
* @param length
* @param mediaType
*/
public Record(final URI recordingId, final int length, final MediaAttributes.MediaType mediaType) {
super();
this.destination = recordingId;
this.prompts = empty;
this.length = length;
this.media = mediaType;
}
public URI destination() {
return destination;
}
public List<URI> prompts() {
return prompts;
}
public boolean hasPrompts() {
return (prompts != null && !prompts.isEmpty());
}
public int timeout() {
return timeout;
}
public int length() {
return length;
}
public String endInputKey() {
return endInputKey;
}
public boolean hasEndInputKey() {
return (endInputKey != null && !endInputKey.isEmpty());
}
public MediaAttributes.MediaType media() {
return media;
}
}
| 3,464 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Left.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Left.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.api.messages;
import akka.actor.ActorRef;
import org.apache.http.annotation.Immutable;
/**
* @author Henrique Rosa ([email protected])
*/
@Immutable
public final class Left {
private ActorRef call;
public Left() {
super();
}
public Left(final ActorRef call) {
this.call = call;
}
public ActorRef get() {
return call;
}
}
| 1,348 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DestroyMediaGroup.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/DestroyMediaGroup.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import akka.actor.ActorRef;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class DestroyMediaGroup {
private final ActorRef group;
public DestroyMediaGroup(final ActorRef group) {
super();
this.group = group;
}
public DestroyMediaGroup() {
this(null);
}
public ActorRef group() {
return group;
}
}
| 1,340 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
StartRecording.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/StartRecording.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import java.net.URI;
import org.apache.commons.configuration.Configuration;
import org.restcomm.connect.dao.DaoManager;
import org.restcomm.connect.commons.dao.Sid;
/**
* Use this to notify a Call object that needs to Record
*
* @author <a href="mailto:[email protected]">gvagenas</a>
*/
public class StartRecording {
public enum RecordingType {
DO_NOT_RECORD("do-not-record"), RECORD_FROM_ANSWER("record-from-answer"), RECORD_FROM_RINGING("record-from-ringing");
private final String text;
private RecordingType(final String text) {
this.text = text;
}
public static RecordingType getValueOf(final String text) {
RecordingType[] values = values();
for (final RecordingType value : values) {
if (value.toString().equals(text)) {
return value;
}
}
throw new IllegalArgumentException(text + " is not a valid account status.");
}
@Override
public String toString() {
return text;
}
};
private Sid callId;
private Sid accountId;
private Configuration runtimeSetting;
private DaoManager daoManager;
private Sid recordingSid;
private URI recordingUri;
public StartRecording(final Sid accountId, final Configuration runtimeSettings, final DaoManager daoManager,
final Sid recordingSid, final URI recordingUri) {
this(accountId, null, runtimeSettings, daoManager, recordingSid, recordingUri);
}
public StartRecording(final Sid accountId, final Sid callId, final Configuration runtimeSettings,
final DaoManager daoManager, final Sid recordingSid, final URI recordingUri) {
this.accountId = accountId;
this.callId = callId;
this.runtimeSetting = runtimeSettings;
this.daoManager = daoManager;
this.recordingSid = recordingSid;
this.recordingUri = recordingUri;
}
public Sid getAccountId() {
return accountId;
}
public Configuration getRuntimeSetting() {
return runtimeSetting;
}
public DaoManager getDaoManager() {
return daoManager;
}
public Sid getRecordingSid() {
return recordingSid;
}
public URI getRecordingUri() {
return recordingUri;
}
public void setCallId(Sid callId) {
this.callId = callId;
}
public Sid getCallId() {
return callId;
}
}
| 3,362 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UpdateMediaSession.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/UpdateMediaSession.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class UpdateMediaSession {
private final String sessionDescription;
public UpdateMediaSession(final String sessionDescription) {
super();
this.sessionDescription = sessionDescription;
}
public String getSessionDescription() {
return sessionDescription;
}
}
| 1,439 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CloseConnection.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/CloseConnection.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class CloseConnection {
public CloseConnection() {
super();
}
}
| 1,216 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
JoinCall.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/JoinCall.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.api.messages;
import jain.protocol.ip.mgcp.message.parms.ConnectionMode;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import akka.actor.ActorRef;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.entities.MediaAttributes;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class JoinCall {
private final ActorRef call;
private final ConnectionMode connectionMode;
private final Sid sid;
private final MediaAttributes mediaAttributes;
public JoinCall(final ActorRef call, final ConnectionMode connectionMode) {
this(call, connectionMode, null);
}
public JoinCall(final ActorRef call, final ConnectionMode connectionMode, final Sid sid) {
this(call, connectionMode, sid, new MediaAttributes());
}
public JoinCall(final ActorRef call, final ConnectionMode connectionMode, final Sid sid, final MediaAttributes mediaAttributes){
this.call = call;
this.connectionMode = connectionMode;
this.sid = sid;
this.mediaAttributes = mediaAttributes;
}
public ActorRef getCall() {
return call;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public Sid getSid () {
return sid;
}
public MediaAttributes mediaAttributes(){
return mediaAttributes;
}
}
| 2,370 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Play.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Play.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class Play {
private final List<URI> uris;
private final int iterations;
private boolean confModeratorPresent = false;
public Play(final List<URI> uris, final int iterations, final boolean confModeratorPresent) {
super();
this.uris = uris;
this.iterations = iterations;
this.confModeratorPresent = confModeratorPresent;
}
public Play(final List<URI> uris, final int iterations) {
super();
this.uris = uris;
this.iterations = iterations;
}
public Play(final URI uri, final int iterations, final boolean confModeratorPresent) {
super();
this.uris = new ArrayList<URI>();
uris.add(uri);
this.iterations = iterations;
this.confModeratorPresent = confModeratorPresent;
}
public Play(final URI uri, final int iterations) {
super();
this.uris = new ArrayList<URI>();
uris.add(uri);
this.iterations = iterations;
}
public List<URI> uris() {
return uris;
}
public int iterations() {
return iterations;
}
public boolean isConfModeratorPresent() { return confModeratorPresent; }
}
| 2,285 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
JoinBridge.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/JoinBridge.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.api.messages;
import jain.protocol.ip.mgcp.message.parms.ConnectionMode;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class JoinBridge {
private final Object endpoint;
private final ConnectionMode connectionMode;
public JoinBridge(final Object endpoint, final ConnectionMode connectionMode) {
this.endpoint = endpoint;
this.connectionMode = connectionMode;
}
public Object getEndpoint() {
return endpoint;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
}
| 1,623 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaGroupStateChanged.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaGroupStateChanged.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import akka.actor.ActorRef;
import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class MediaGroupStateChanged {
private ActorRef ivr;
private ConnectionIdentifier connectionIdentifier;
public static enum State {
ACTIVE, INACTIVE
};
private final State state;
public MediaGroupStateChanged(final State state, final ConnectionIdentifier connectionIdentifier) {
this(state, null, connectionIdentifier);
}
public MediaGroupStateChanged(final State state) {
this(state, null, null);
}
public MediaGroupStateChanged(final State state, final ActorRef ivr) {
this(state, ivr, null);
}
public MediaGroupStateChanged(final State state, final ActorRef ivr, final ConnectionIdentifier connectionIdentifier) {
super();
this.state = state;
this.ivr = ivr;
this.connectionIdentifier = connectionIdentifier;
}
public State state() {
return state;
}
public ActorRef ivr() {
return ivr;
}
public ConnectionIdentifier connectionIdentifier() {
return connectionIdentifier;
}
}
| 2,166 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaServerControllerResponse.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaServerControllerResponse.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.commons.patterns.StandardResponse;
/**
* @author Henrique Rosa ([email protected])
*/
@Immutable
public final class MediaServerControllerResponse<T> extends StandardResponse<T> {
public MediaServerControllerResponse(T object) {
super(object);
}
public MediaServerControllerResponse(Throwable cause, String message) {
super(cause, message);
}
public MediaServerControllerResponse(Throwable cause) {
super(cause);
}
}
| 1,552 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Join.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Join.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import jain.protocol.ip.mgcp.message.parms.ConnectionMode;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import akka.actor.ActorRef;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class Join {
private final ActorRef call;
private final ActorRef mscontroller;
private final ConnectionMode mode;
public Join(final ActorRef call, final ActorRef mscontroller, final ConnectionMode mode) {
super();
this.call = call;
this.mscontroller = mscontroller;
this.mode = mode;
}
public ActorRef endpoint() {
return call;
}
public ActorRef mscontroller() {
return mscontroller;
}
public ConnectionMode mode() {
return mode;
}
}
| 1,652 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaGroupStatus.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaGroupStatus.java | package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*/
@Immutable
public final class MediaGroupStatus {
public MediaGroupStatus() {
super();
}
}
| 300 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CreateMediaGroup.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/CreateMediaGroup.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class CreateMediaGroup {
public CreateMediaGroup() {
super();
}
}
| 1,108 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Collect.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/Collect.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import java.net.URI;
import java.util.List;
/**
* @author [email protected] (Thomas Quintana)
*/
@Immutable
public final class Collect {
public enum Type {
DTMF, SPEECH, DTMF_SPEECH;
public static Type parseOrDefault(String name, Type defaultValue){
try {
return "DTMF SPEECH".equalsIgnoreCase(name) ? DTMF_SPEECH : Type.valueOf(name.toUpperCase());
} catch (Exception e) {
return defaultValue;
}
}
}
private final Type type;
private final List<URI> prompts;
private final String pattern;
private final int timeout;
private final String endInputKey;
private final String startInputKey;
private final int numberOfDigits;
private final String lang;
private final String hints;
private final String driver;
private final boolean partialResult;
public Collect(String driver,final Type type, final List<URI> prompts, final String pattern, final int timeout, final String endInputKey,
final String startInputKey, final int numberOfDigits, final String lang, final String hints, final boolean partialResult) {
super();
this.driver = driver;
this.type = type;
this.prompts = prompts;
this.pattern = pattern;
this.timeout = timeout;
this.endInputKey = endInputKey;
this.startInputKey = startInputKey;
this.numberOfDigits = numberOfDigits;
this.lang = lang;
this.hints = hints;
this.partialResult = partialResult;
}
public String getDriver() {
return driver;
}
public Type type() {
return type;
}
public String lang() {
return lang;
}
public List<URI> prompts() {
return prompts;
}
public boolean hasPrompts() {
return (prompts != null && !prompts.isEmpty());
}
public String pattern() {
return pattern;
}
public boolean hasPattern() {
return (pattern != null && !pattern.isEmpty());
}
public int timeout() {
return timeout;
}
public String endInputKey() {
return endInputKey;
}
public boolean hasEndInputKey() {
return (endInputKey != null && !endInputKey.isEmpty());
}
public String startInputKey() { return startInputKey; }
public boolean hasStartInputKey() {return (startInputKey != null && !startInputKey.isEmpty()); }
public int numberOfDigits() {
return numberOfDigits;
}
public String getHints() {
return hints;
}
public boolean needPartialResult() {
return partialResult;
}
}
| 3,618 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CreateMediaSession.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/CreateMediaSession.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.entities.MediaAttributes;
/**
* @author Henrique Rosa ([email protected])
*/
@Immutable
public final class CreateMediaSession {
private final boolean outbound;
private final String connectionMode;
private final String sessionDescription;
private final boolean webrtc;
private final Sid callSid;
private final String conferenceName;
private final MediaAttributes mediaAttributes;
public CreateMediaSession(String connectionMode, String sessionDescription, boolean outbound, boolean webrtc, Sid callSid, final String conferenceName, final MediaAttributes mediaAttributes) {
super();
this.connectionMode = connectionMode;
this.sessionDescription = sessionDescription;
this.outbound = outbound;
this.webrtc = webrtc;
this.callSid = callSid;
this.conferenceName = conferenceName;
this.mediaAttributes = mediaAttributes;
}
public CreateMediaSession(String connectionMode, String sessionDescription, boolean outbound, boolean webrtc, Sid callSid) {
this(connectionMode, sessionDescription, outbound, webrtc, callSid, new MediaAttributes());
}
public CreateMediaSession(String connectionMode, String sessionDescription, boolean outbound, boolean webrtc, Sid callSid, final MediaAttributes mediaAttributes) {
this(connectionMode, sessionDescription, outbound, webrtc, callSid, null, mediaAttributes);
}
public CreateMediaSession(String connectionMode) {
this("sendrecv", "", false, false, null, null, new MediaAttributes());
}
public CreateMediaSession(Sid callSid, final String conferenceName, final MediaAttributes mediaAttributes) {
this("", "", false, false, callSid, conferenceName, mediaAttributes);
}
public CreateMediaSession(Sid callSid) {
this("", "", false, false, callSid, null, new MediaAttributes());
}
public CreateMediaSession(final MediaAttributes mediaAttributes) {
this("", "", false, false, null, null, mediaAttributes);
}
public String getConnectionMode() {
return connectionMode;
}
public String getSessionDescription() {
return sessionDescription;
}
public boolean isOutbound() {
return outbound;
}
public boolean isWebrtc() {
return webrtc;
}
public Sid callSid() {
return callSid;
}
public String conferenceName() {
return conferenceName;
}
public MediaAttributes mediaAttributes() { return mediaAttributes; }
}
| 3,672 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
JoinConference.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/JoinConference.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
import jain.protocol.ip.mgcp.message.parms.ConnectionMode;
import org.restcomm.connect.commons.dao.Sid;
import org.restcomm.connect.dao.entities.MediaAttributes;
/**
* @author Henrique Rosa ([email protected])
*
*/
@Immutable
public final class JoinConference {
private final Object endpoint;
private final ConnectionMode connectionMode;
private final Sid sid;
private final MediaAttributes mediaAttributes;
public JoinConference(final Object endpoint, final ConnectionMode connectionMode, final Sid sid) {
this(endpoint, connectionMode, sid, new MediaAttributes());
}
public JoinConference(final Object endpoint, final ConnectionMode connectionMode, final Sid sid, final MediaAttributes mediaAttributes) {
this.endpoint = endpoint;
this.connectionMode = connectionMode;
this.sid = sid;
this.mediaAttributes = mediaAttributes;
}
public Object getEndpoint() {
return endpoint;
}
public ConnectionMode getConnectionMode() {
return connectionMode;
}
public Sid getSid () {
return sid;
}
public MediaAttributes mediaAttributes(){
return mediaAttributes;
}
}
| 2,254 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
StopMediaGroup.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/StopMediaGroup.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author [email protected] (Thomas Quintana)
* @author Maria Farooq
*/
@Immutable
public final class StopMediaGroup {
private boolean liveCallModification;
private Boolean beep;
/**
* @param beep - If a beep will be played in that case we don't need to send EndSignal(StopMediaGroup)
* to media-server as media-server will automatically stop beep when it will receive
* play command for beep. If a beep wont be played, then conference need to send
* EndSignal(StopMediaGroup) to media-server to stop ongoing music-on-hold.
* https://github.com/RestComm/Restcomm-Connect/issues/2024
* this is applicable only for restcomm mediaserver
*/
public StopMediaGroup(final Boolean beep) {
super();
this.beep = beep;
}
public StopMediaGroup() {
super();
}
public StopMediaGroup(final boolean liveCallModification) {
this.liveCallModification = liveCallModification;
}
public boolean isLiveCallModification() {
return liveCallModification;
}
public Boolean beep() {
return beep;
}
}
| 2,067 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
MediaGroupCreated.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/MediaGroupCreated.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.api.messages;
import org.restcomm.connect.commons.annotations.concurrency.Immutable;
/**
* @author Henrique Rosa ([email protected])
*/
@Immutable
public class MediaGroupCreated {
public MediaGroupCreated() {
super();
}
}
| 1,210 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CollectedResult.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.mscontrol.api/src/main/java/org/restcomm/connect/mscontrol/api/messages/CollectedResult.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.mscontrol.api.messages;
/**
* Created by gdubina on 6/6/17.
*/
public class CollectedResult {
private final String result;
private final boolean isAsr;
private final boolean isPartial;
public CollectedResult(String result, boolean isAsr, boolean isPartial) {
this.result = result;
this.isAsr = isAsr;
this.isPartial = isPartial;
}
public String getResult() {
return result;
}
public boolean isAsr() {
return isAsr;
}
public boolean isPartial() {
return isPartial;
}
@Override
public String toString() {
return "CollectedResult{" +
"result='" + result + '\'' +
", isAsr=" + isAsr +
", isPartial=" + isPartial +
'}';
}
}
| 1,645 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
JavascriptPasswordValidationTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.identity/src/test/java/org/restcomm/connect/identity/passwords/JavascriptPasswordValidationTest.java | package org.restcomm.connect.identity.passwords;
import junit.framework.Assert;
import org.junit.Test;
/**
* @author [email protected] - Orestis Tsakiridis
*/
public class JavascriptPasswordValidationTest {
@Test
public void passwordStrengthTest() {
PasswordValidator validator = PasswordValidatorFactory.createDefault();
Assert.assertFalse(validator.isStrongEnough("1234"));
Assert.assertFalse(validator.isStrongEnough("asdf123"));
Assert.assertTrue(validator.isStrongEnough("asd123$#@"));
Assert.assertTrue(validator.isStrongEnough("γιωργος123#!@"));
}
}
| 620 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UserIdentityContext.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.identity/src/main/java/org/restcomm/connect/identity/UserIdentityContext.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 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.identity;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.restcomm.connect.dao.exceptions.AccountHierarchyDepthCrossed;
import org.restcomm.connect.dao.AccountsDao;
import org.restcomm.connect.dao.entities.Account;
/**
* A per-request security context providing access to Oauth tokens or Account API Keys.
* @author "Tsakiridis Orestis"
*
*/
public class UserIdentityContext {
final AccountKey accountKey;
final Account effectiveAccount; // if oauthToken is set get the account that maps to it. Otherwise use account from accountKey
Set<String> effectiveAccountRoles;
List<String> accountLineage = null; // list of all parent account Sids up to the lop level account. It's initialized in a lazy way.
AccountsDao accountsDao;
/**
* After successfull creation of a UserIdentityContext object the following stands:
* - if an oauth token was present and verified *oauthToken* will contain it. Otherwise it will be null
* - TODO If a *linked* account exists for the oauth token username *effectiveAccount* will be set
* - if BASIC http credentials were present *accountKey* will contain them. Check accountKey.isVerified()
* - if BASIC http credentials were verified effective account will be set to this account.
* - if both oauthToken and accountKey are set and verified, effective account will be set to the account indicated by accountKey.
* @param request
* @param accountsDao
*/
public UserIdentityContext(HttpServletRequest request, AccountsDao accountsDao) {
this.accountsDao = accountsDao;
this.accountKey = extractAccountKey(request, accountsDao);
if (accountKey != null) {
if (accountKey.isVerified()) {
effectiveAccount = accountKey.getAccount();
} else
effectiveAccount = null;
} else
effectiveAccount = null;
if (effectiveAccount != null)
effectiveAccountRoles = extractAccountRoles(effectiveAccount);
}
private Set<String> extractAccountRoles(Account account) {
if (account == null)
return null;
Set<String> roles = new HashSet<String>();
if (!StringUtils.isEmpty(account.getRole())) {
roles.add(account.getRole());
}
return roles;
}
private AccountKey extractAccountKey(HttpServletRequest request, AccountsDao dao) {
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
String[] parts = authHeader.split(" ");
if (parts.length >= 2 && parts[0].equals("Basic")) {
String base64Credentials = parts[1].trim();
String credentials = new String(Base64.decodeBase64(base64Credentials), Charset.forName("UTF-8"));
// credentials = username:password
final String[] values = credentials.split(":",2);
if (values.length >= 2) {
AccountKey accountKey = new AccountKey(values[0], values[1], dao);
return accountKey;
}
}
}
return null;
}
public AccountKey getAccountKey() {
return accountKey;
}
public Account getEffectiveAccount() {
return effectiveAccount;
}
public Set<String> getEffectiveAccountRoles() {
return effectiveAccountRoles;
}
/**
* Returns the list of ancestors for the effective (the one specified in the credentials) account
* in a lazy way.
*
* @return
*/
public List<String> getEffectiveAccountLineage() {
if (accountLineage == null) {
if (effectiveAccount != null) {
try {
accountLineage = accountsDao.getAccountLineage(effectiveAccount);
} catch (AccountHierarchyDepthCrossed e) {
throw new RuntimeException("Logged account has a very big line of ancestors. Something seems wrong. Account sid: " + effectiveAccount.getSid().toString(), e);
}
}
}
return accountLineage;
}
}
| 5,182 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
IdentityContext.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.identity/src/main/java/org/restcomm/connect/identity/IdentityContext.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.identity;
import org.apache.commons.configuration.Configuration;
import org.restcomm.connect.identity.shiro.RestcommRoles;
/**
* Identity Context holds all identity related entities whose lifecycle follows Restcomm lifecycle, such as
* keycloak deployment (to be added) and restcomm roles.
*
* In a typical use case you can access to the IdentityContext from the ServletContext.
*
* @author "Tsakiridis Orestis"
*/
public class IdentityContext {
RestcommRoles restcommRoles;
/**
* @param restcommConfiguration An apache configuration object representing <restcomm/> element of restcomm.xml
*/
public IdentityContext(Configuration restcommConfiguration) {
this.restcommRoles = new RestcommRoles(restcommConfiguration.subset("runtime-settings").subset("security-roles"));
}
public IdentityContext(RestcommRoles restcommRoles) {
if (restcommRoles == null)
throw new IllegalArgumentException("Cannot create an IdentityContext object with null roles!");
this.restcommRoles = restcommRoles;
}
public RestcommRoles getRestcommRoles() { return restcommRoles; }
}
| 1,985 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
AccountKey.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.identity/src/main/java/org/restcomm/connect/identity/AccountKey.java | package org.restcomm.connect.identity;
import org.apache.commons.codec.digest.DigestUtils;
import org.restcomm.connect.dao.AccountsDao;
import org.restcomm.connect.dao.entities.Account;
/**
* Represents authorization information for an Account. When a request initially arrives carrying basic HTTP auth
* credentials an AccountKey is created. It carries the challenged credentials and the verification result.
*
* - use isVerified() to check the verification result.
* -use getAccount() to check if the account in the credentials actually exists (may not be verified)
*
* @author "Tsakiridis Orestis"
*/
public class AccountKey {
private String challengedSid;
private String challengedKey;
private Account account; // Having this set does not mean it is verified. It just means that the (account) challengedSid exists.
private boolean verified = false;
public AccountKey(String sid, String key, AccountsDao dao) {
this.challengedSid = sid; // store there for future reference, maybe we need the raw data
this.challengedKey = key;
account = dao.getAccountToAuthenticate(sid); // We don't just retrieve an account, we're authenticating. Friendly names as authentnication tokens should be prevented
verify(dao);
}
private void verify(AccountsDao dao) {
if ( account != null ) {
if ( challengedKey != null )
// Compare both the plaintext version of the token and md5'ed version of it
if ( challengedKey.equals(account.getAuthToken()) || DigestUtils.md5Hex(challengedKey).equals(account.getAuthToken()) ) {
verified = true;
}
}
}
public Account getAccount() {
return account;
}
public boolean isVerified() {
return verified;
}
}
| 1,838 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
PasswordValidator.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.identity/src/main/java/org/restcomm/connect/identity/passwords/PasswordValidator.java | package org.restcomm.connect.identity.passwords;
/**
* Checks the strength of a password
*
* @author [email protected] - Orestis Tsakiridis
*/
public interface PasswordValidator {
boolean isStrongEnough(String password);
}
| 232 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
PasswordValidatorFactory.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.identity/src/main/java/org/restcomm/connect/identity/passwords/PasswordValidatorFactory.java | package org.restcomm.connect.identity.passwords;
/**
* @author [email protected] - Orestis Tsakiridis
*/
public class PasswordValidatorFactory {
public static PasswordValidator createDefault() {
return new JavascriptPasswordValidator();
}
}
| 260 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
JavascriptPasswordValidator.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.identity/src/main/java/org/restcomm/connect/identity/passwords/JavascriptPasswordValidator.java | package org.restcomm.connect.identity.passwords;
import org.apache.log4j.Logger;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
/**
* @author [email protected] - Orestis Tsakiridis
*/
public class JavascriptPasswordValidator implements PasswordValidator {
protected static Logger logger = Logger.getLogger(JavascriptPasswordValidator.class);
@Override
public boolean isStrongEnough(String password) {
Integer result = getStrength(password);
if (result == null ||result < 50)
return false;
return true;
}
/**
* Returns a number from 0-100 according to the strength of the password passed.
* In case of error it returns null. The actual implementation of the algorithm is implemented
* in Javascript hence the name of the class.
*
* @param password
* @return
*/
private Integer getStrength(String password) {
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("JavaScript");
String js = "function getStrength(p) {var stringReverse = function(str) {for (var i = str.length - 1, out = ''; i >= 0; out += str[i--]) {}return out;},matches = {pos: {},neg: {}},counts = {pos: {},neg: {seqLetter: 0,seqNumber: 0,seqSymbol: 0}},tmp,strength = 0,letters = 'abcdefghijklmnopqrstuvwxyz',numbers = '01234567890',symbols = '\\\\!@#$%&/()=?¿',back,forth,i;if (p) {matches.pos.lower = p.match(/[a-z]/g);matches.pos.upper = p.match(/[A-Z]/g);matches.pos.numbers = p.match(/\\d/g);matches.pos.symbols = p.match(/[$-/:-?{-~!^_`\\[\\]]/g);matches.pos.middleNumber = p.slice(1, -1).match(/\\d/g);matches.pos.middleSymbol = p.slice(1, -1).match(/[$-/:-?{-~!^_`\\[\\]]/g);counts.pos.lower = matches.pos.lower ? matches.pos.lower.length : 0;counts.pos.upper = matches.pos.upper ? matches.pos.upper.length : 0;counts.pos.numbers = matches.pos.numbers ? matches.pos.numbers.length : 0;counts.pos.symbols = matches.pos.symbols ? matches.pos.symbols.length : 0;tmp = Object.keys(counts.pos).reduce(function(previous, key) {return previous + Math.min(1, counts.pos[key]);}, 0);counts.pos.numChars = p.length;tmp += (counts.pos.numChars >= 8) ? 1 : 0;counts.pos.requirements = (tmp >= 3) ? tmp : 0;counts.pos.middleNumber = matches.pos.middleNumber ? matches.pos.middleNumber.length : 0;counts.pos.middleSymbol = matches.pos.middleSymbol ? matches.pos.middleSymbol.length : 0;matches.neg.consecLower = p.match(/(?=([a-z]{2}))/g);matches.neg.consecUpper = p.match(/(?=([A-Z]{2}))/g);matches.neg.consecNumbers = p.match(/(?=(\\d{2}))/g);matches.neg.onlyNumbers = p.match(/^[0-9]*$/g);matches.neg.onlyLetters = p.match(/^([a-z]|[A-Z])*$/g);counts.neg.consecLower = matches.neg.consecLower ? matches.neg.consecLower.length : 0;counts.neg.consecUpper = matches.neg.consecUpper ? matches.neg.consecUpper.length : 0;counts.neg.consecNumbers = matches.neg.consecNumbers ? matches.neg.consecNumbers.length : 0;for (i = 0; i < letters.length - 2; i++) {var p2 = p.toLowerCase();forth = letters.substring(i, parseInt(i + 3));back = stringReverse(forth);if (p2.indexOf(forth) !== -1 || p2.indexOf(back) !== -1) {counts.neg.seqLetter++;}}for (i = 0; i < numbers.length - 2; i++) {forth = numbers.substring(i, parseInt(i + 3));back = stringReverse(forth);if (p.indexOf(forth) !== -1 || p.toLowerCase().indexOf(back) !== -1) {counts.neg.seqNumber++;}}for (i = 0; i < symbols.length - 2; i++) {forth = symbols.substring(i, parseInt(i + 3));back = stringReverse(forth);if (p.indexOf(forth) !== -1 || p.toLowerCase().indexOf(back) !== -1) {counts.neg.seqSymbol++;}}var repeats = {};var _p = p.toLowerCase();var arr = _p.split('');counts.neg.repeated = 0;for (i = 0; i < arr.length; i++) {var _reg = new RegExp(_p[i], 'g');var cnt = _p.match(_reg).length;if (cnt > 1 && !repeats[_p[i]]) {repeats[_p[i]] = cnt;counts.neg.repeated += cnt;}}strength += counts.pos.numChars * 4;if (counts.pos.upper) {strength += (counts.pos.numChars - counts.pos.upper) * 2;}if (counts.pos.lower) {strength += (counts.pos.numChars - counts.pos.lower) * 2;}if (counts.pos.upper || counts.pos.lower) {strength += counts.pos.numbers * 4;}strength += counts.pos.symbols * 6;strength += (counts.pos.middleSymbol + counts.pos.middleNumber) * 2;strength += counts.pos.requirements * 2;strength -= counts.neg.consecLower * 2;strength -= counts.neg.consecUpper * 2;strength -= counts.neg.consecNumbers * 2;strength -= counts.neg.seqNumber * 3;strength -= counts.neg.seqLetter * 3;strength -= counts.neg.seqSymbol * 3;if (matches.neg.onlyNumbers) {strength -= counts.pos.numChars;}if (matches.neg.onlyLetters) {strength -= counts.pos.numChars;}if (counts.neg.repeated) {strength -= (counts.neg.repeated / counts.pos.numChars) * 10;}}return Math.max(0, Math.min(100, Math.round(strength)));}";
js += "var result = getStrength(password);";
try {
engine.put("password", password);
engine.eval(js);
Double result = (Double) engine.get("result");
//throw new ScriptException("manally thrown");
return result.intValue();
} catch (ScriptException e) {
logger.error("Javascript-based password validation mechanism failed. Make sure a proper JAVA implementation is used.", e);
return null;
}
}
}
| 5,375 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RestcommRoles.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.identity/src/main/java/org/restcomm/connect/identity/shiro/RestcommRoles.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.identity.shiro;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.configuration.Configuration;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleRole;
import org.apache.shiro.authz.permission.WildcardPermission;
/**
* @author [email protected] (Orestis Tsakiridis)
*/
public class RestcommRoles {
private Map<String, SimpleRole> roles;
/**
* Parses restcomm.xml configuration and builds a map out of roles from it.
*
* @param configuration - An apache configuration object based on the <security-roles/> element
*/
public RestcommRoles(Configuration configuration) {
roles = new HashMap<String, SimpleRole>();
loadSecurityRoles(configuration);
}
public SimpleRole getRole(final String role) {
return roles.get(role);
}
private void loadSecurityRoles(final Configuration configuration) {
@SuppressWarnings("unchecked")
final List<String> roleNames = (List<String>) configuration.getList("role[@name]");
final int numberOfRoles = roleNames.size();
if (numberOfRoles > 0) {
for (int roleIndex = 0; roleIndex < numberOfRoles; roleIndex++) {
StringBuilder buffer = new StringBuilder();
buffer.append("role(").append(roleIndex).append(")").toString();
final String prefix = buffer.toString();
final String name = configuration.getString(prefix + "[@name]");
@SuppressWarnings("unchecked")
final List<String> permissions = configuration.getList(prefix + ".permission");
if (name != null) {
if (permissions.size() > 0 ) {
final SimpleRole role = new SimpleRole(name);
for (String permissionString: permissions) {
//logger.info("loading permission " + permissionString + " into " + name + " role");
final Permission permission = new WildcardPermission(permissionString);
role.add(permission);
}
roles.put(name, role);
}
}
}
}
}
@Override
public String toString() {
if ( roles == null || roles.size() == 0 )
return "no roles defined";
else {
StringBuffer buffer = new StringBuffer();
for ( String role: roles.keySet() ) {
buffer.append(role);
SimpleRole simpleRole = roles.get(role);
Set<Permission> permissions = simpleRole.getPermissions();
buffer.append("[");
for (Permission permission: permissions) {
buffer.append(permission.toString());
buffer.append(",");
}
buffer.append("]");
}
return buffer.toString();
}
}
}
| 3,911 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DnsProvisioningManagerProvider.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dns.api/src/main/java/org/restcomm/connect/dns/DnsProvisioningManagerProvider.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.dns;
import javax.servlet.ServletContext;
import org.apache.commons.configuration.Configuration;
import org.apache.log4j.Logger;
import org.restcomm.connect.commons.loader.ObjectFactory;
import org.restcomm.connect.commons.loader.ObjectInstantiationException;
/**
* A single place to create the dns provisioning manager
*
* @author maria farooq
*/
public class DnsProvisioningManagerProvider {
protected Logger logger = Logger.getLogger(DnsProvisioningManagerProvider.class);
protected Configuration configuration;
protected ServletContext context;
public DnsProvisioningManagerProvider(Configuration configuration, ServletContext context) {
this.configuration = configuration;
this.context = context;
}
/**
* @return initialized instance of DnsProvisioningManager
*/
private DnsProvisioningManager create() {
Configuration dnsProvisioningConfiguration = configuration.subset("dns-provisioning");
if (dnsProvisioningConfiguration == null || dnsProvisioningConfiguration.isEmpty()){
logger.warn("dns-provisioning configuration is null or empty");
return null;
}
final boolean enabled = configuration.getBoolean("dns-provisioning[@enabled]", false);
if(!enabled){
logger.warn("dns-provisioning is disabled in configuration");
return null;
}
final String dnsProvisioningManagerClass = configuration.getString("dns-provisioning[@class]");
if(dnsProvisioningManagerClass == null || dnsProvisioningManagerClass.trim().equals("")){
logger.warn("dns-provisioning is enabled but manager class is null or empty");
return null;
}
DnsProvisioningManager dnsProvisioningManager;
try {
dnsProvisioningManager = (DnsProvisioningManager) new ObjectFactory(getClass().getClassLoader())
.getObjectInstance(dnsProvisioningManagerClass);
dnsProvisioningManager.init(dnsProvisioningConfiguration);
} catch (ObjectInstantiationException e) {
throw new RuntimeException(e);
}
return dnsProvisioningManager;
}
/**
* Tries to retrieve the manager from the Servlet context. If it's not there it creates is, stores it
* in the context and also returns it.
*
* @param context
* @return
*/
public DnsProvisioningManager get() {
DnsProvisioningManager manager = (DnsProvisioningManager) context.getAttribute("DnsProvisioningManager");
if (manager != null) // ok, it's already in the context. Return it
return manager;
manager = create();
// put it into the context for next time that is requested
context.setAttribute("DnsProvisioningManager", manager);
return manager;
}
}
| 3,697 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
DnsProvisioningManager.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dns.api/src/main/java/org/restcomm/connect/dns/DnsProvisioningManager.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.dns;
import org.apache.commons.configuration.Configuration;
public interface DnsProvisioningManager {
/**
* Initialize the Manager with the RestComm configuration passed in restcomm.xml
*
* @param dnsConfiguration the configuration from restcomm.xml contained within <dns-provisioning> tags
*/
void init(Configuration dnsConfiguration);
/**
* @param name The name of the domain you want to perform the action on.
* Enter a sub domain name only. For example to add 'company1.restcomm.com',
* provide only 'company1' and provide hosted zone for 'restcomm.com'
* @param hostedZoneId hostedZoneId The ID of the hosted zone that contains the resource record sets that you want to change.
* If none provided, then default will be used as per configuration
* @return true if operation successful, false otherwise.
*/
boolean createResourceRecord(final String name, final String hostedZoneId);
/**
* @param name The name of the domain you want to read.
* Enter a sub domain name only. For example to add 'company1.restcomm.com',
* provide only 'company1' and provide hosted zone for 'restcomm.com'
* @param hostedZoneId hostedZoneId The ID of the hosted zone that contains the resource record sets that you want to change.
* If none provided, then default will be used as per configuration
* @return true if resource record exists, false otherwise.
*/
boolean doesResourceRecordAlreadyExists(final String name, final String hostedZoneId);
/**
* @param name The name of the domain you want to perform the action on.
* Enter a sub domain name only. For example to add 'company1.restcomm.com',
* provide only 'company1' and provide hosted zone for 'restcomm.com'
* @param hostedZoneId hostedZoneId The ID of the hosted zone that contains the resource record sets that you want to change.
* If none provided, then default will be used as per configuration
* @return true if operation successful, false otherwise.
*/
boolean updateResourceRecord(final String name, final String hostedZoneId);
/**
* @param name The name of the domain you want to perform the action on.
* Enter a sub domain name only. For example to add 'company1.restcomm.com',
* provide only 'company1' and provide hosted zone for 'restcomm.com'
* @param hostedZoneId hostedZoneId The ID of the hosted zone that contains the resource record sets that you want to change.
* If none provided, then default will be used as per configuration
* @return true if operation successful, false otherwise.
*/
boolean deleteResourceRecord(final String name, final String hostedZoneId);
/**
* @param subDomainName
* @param hostedZoneId
* @return
*/
String getCompleteDomainName(String subDomainName, final String hostedZoneId);
}
| 3,756 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdPullTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/UssdPullTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite;
import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sip.DialogState;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.address.Address;
import javax.sip.header.ContentTypeHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipRequest;
import org.cafesip.sipunit.SipStack;
import org.cafesip.sipunit.SipTransaction;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.UnstableTests;
import org.restcomm.connect.commons.annotations.WithInMinsTests;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
* @modified <a href="mailto:[email protected]"> Fernando Mendioroz </a>
*
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInMinsTests.class, ParallelClassTests.class})
public class UssdPullTest {
private final static Logger logger = Logger.getLogger(UssdPullTest.class.getName());
private static final String version = Version.getVersion();
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
private static SipStackTool tool1;
private SipStack bobSipStack;
private SipPhone bobPhone;
private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String bobContact = "sip:[email protected]:" + bobPort;
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
private static String ussdPullDid = "sip:5544@" + restcommContact;
private static String ussdPullShortCodeDialDid = "sip:*777#@" + restcommContact;
private static String ussdPullFastDialDid = "sip:*777*3#@" + restcommContact;
private static String ussdPullWithCollectDID = "sip:5555@" + restcommContact;
private static String ussdPullMessageLengthExceeds = "sip:5566@" + restcommContact;
private static String ussdPullDidNoHttpMethod = "sip:5577@" + restcommContact;
private static String ussdPullDidClosedAccount = "sip:5578@" + restcommContact;
private static String ussdPullDidSuspendedAccount = "sip:5579@" + restcommContact;
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("UssdPullTest");
}
public static void reconfigurePorts() {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
ussdPullDid = "sip:5544@" + restcommContact;
ussdPullShortCodeDialDid = "sip:*777#@" + restcommContact;
ussdPullFastDialDid = "sip:*777*3#@" + restcommContact;
ussdPullWithCollectDID = "sip:5555@" + restcommContact;
ussdPullMessageLengthExceeds = "sip:5566@" + restcommContact;
ussdPullDidNoHttpMethod = "sip:5577@" + restcommContact;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact);
bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact);
}
@After
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
bobPhone = null;
}
if (bobSipStack != null) {
bobSipStack.dispose();
bobSipStack = null;
}
}
@Test
@Category(UnstableTests.class)
public void testUssdPull() {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullDid, null, UssdPullTestMessages.ussdClientRequestBody, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING);
} else {
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING);
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertEquals(DialogState._CONFIRMED, bobCall.getDialog().getState().getValue());
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
String receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessages.ussdRestcommResponse.trim()));
bobCall.dispose();
}
@Test
public void testUssdPullNoHttpMethod() {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullDidNoHttpMethod, null, UssdPullTestMessages.ussdClientRequestBody, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING);
} else {
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING);
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue() == DialogState._CONFIRMED);
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
String receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessages.ussdRestcommResponse.trim()));
bobCall.dispose();
}
@Test //USSD Pull to *777#
public void testUssdPullShortCodeDial() {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullShortCodeDialDid, null, UssdPullTestMessages.ussdClientRequestBody, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING);
} else {
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING);
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue() == DialogState._CONFIRMED);
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
String receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessages.ussdRestcommResponse.trim()));
bobCall.dispose();
}
@Test //USSD Pull to *777*...#
@Category(UnstableTests.class)
public void testUssdPullFastDial() {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullFastDialDid, null, UssdPullTestMessages.ussdClientFastDialRequestBody, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING);
} else {
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.RINGING);
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue() == DialogState._CONFIRMED);
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
String receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessages.ussdRestcommShortDialResponse.trim()));
bobCall.dispose();
}
@Test
public void testUssdPullWithCollect() throws InterruptedException, SipException, ParseException {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullWithCollectDID, null, UssdPullTestMessages.ussdClientRequestBodyForCollect, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING);
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue() == DialogState._CONFIRMED);
String toTag = bobCall.getDialog().getLocalTag();
Address bobAddress = bobPhone.getAddress();
assertTrue(bobPhone.listenRequestMessage());
RequestEvent requestEvent = bobPhone.waitRequest(30 * 1000);
assertNotNull(requestEvent);
assertTrue(requestEvent.getRequest().getMethod().equalsIgnoreCase("INFO"));
bobPhone.sendReply(requestEvent, 200, "OK", toTag, bobAddress, 0);
String receivedUssdPayload = new String(requestEvent.getRequest().getRawContent());
System.out.println("receivedUssdPayload: \n" + receivedUssdPayload);
System.out.println("UssdPullTestMessages.ussdRestcommResponseWithCollect: \n" + UssdPullTestMessages.ussdRestcommResponseWithCollect);
assertTrue(receivedUssdPayload.equals(UssdPullTestMessages.ussdRestcommResponseWithCollect.trim()));
Request infoResponse = requestEvent.getDialog().createRequest(Request.INFO);
ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml");
infoResponse.setContent(UssdPullTestMessages.ussdClientResponseBodyToCollect.getBytes(), contentTypeHeader);
bobPhone.sendRequestWithTransaction(infoResponse, false, requestEvent.getDialog());
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessages.ussdRestcommResponse.trim()));
bobCall.dispose();
}
@Test
@Ignore
public void testUssdPullWithCollectFromRVD() throws InterruptedException, SipException, ParseException {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, "sip:*888#@" + restcommContact, null, UssdPullTestMessages.ussdClientRequestBodyForCollect, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING);
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue() == DialogState._CONFIRMED);
String toTag = bobCall.getDialog().getLocalTag();
Address bobAddress = bobPhone.getAddress();
assertTrue(bobPhone.listenRequestMessage());
RequestEvent requestEvent = bobPhone.waitRequest(30 * 1000);
assertNotNull(requestEvent);
assertTrue(requestEvent.getRequest().getMethod().equalsIgnoreCase("INFO"));
bobPhone.sendReply(requestEvent, 200, "OK", toTag, bobAddress, 0);
String receivedUssdPayload = new String(requestEvent.getRequest().getRawContent());
System.out.println("receivedUssdPayload: \n" + receivedUssdPayload);
System.out.println("UssdPullTestMessages.ussdRestcommResponseWithCollect: \n" + UssdPullTestMessages.ussdRestcommResponseWithCollect);
assertTrue(receivedUssdPayload.equals(UssdPullTestMessages.ussdRestcommResponseWithCollect.trim()));
Request infoResponse = requestEvent.getDialog().createRequest(Request.INFO);
ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml");
infoResponse.setContent(UssdPullTestMessages.ussdClientResponseBodyToCollect.getBytes(), contentTypeHeader);
bobPhone.sendRequestWithTransaction(infoResponse, false, requestEvent.getDialog());
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessages.ussdRestcommResponse.trim()));
bobCall.dispose();
}
@Test
public void testUssdPullWithCollect_DisconnectFromUser() throws InterruptedException, SipException, ParseException {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullWithCollectDID, null, UssdPullTestMessages.ussdClientRequestBodyForCollect, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING);
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue() == DialogState._CONFIRMED);
String toTag = bobCall.getDialog().getLocalTag();
Address bobAddress = bobPhone.getAddress();
assertTrue(bobPhone.listenRequestMessage());
RequestEvent requestEvent = bobPhone.waitRequest(30 * 1000);
assertNotNull(requestEvent);
assertTrue(requestEvent.getRequest().getMethod().equalsIgnoreCase("INFO"));
bobPhone.sendReply(requestEvent, 200, "OK", toTag, bobAddress, 0);
String receivedUssdPayload = new String(requestEvent.getRequest().getRawContent());
System.out.println("receivedUssdPayload: \n" + receivedUssdPayload);
System.out.println("UssdPullTestMessages.ussdRestcommResponseWithCollect: \n" + UssdPullTestMessages.ussdRestcommResponseWithCollect);
assertTrue(receivedUssdPayload.equals(UssdPullTestMessages.ussdRestcommResponseWithCollect.trim()));
bobCall.disconnect();
bobCall.waitForAnswer(10000);
assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == 200);
}
@Test
@Ignore
public void testUssdPullWithCollect_CancelFromUser() throws InterruptedException, SipException, ParseException {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullWithCollectDID, null, UssdPullTestMessages.ussdClientRequestBodyForCollect, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
bobCall.waitOutgoingCallResponse(1000);
// Thread.sleep(1000);
SipTransaction cancelTransaction = bobCall.sendCancel();
assertNotNull(cancelTransaction);
bobCall.waitForCancel(5 * 1000);
int lastResponseCode = bobCall.getLastReceivedResponse().getStatusCode();
if (lastResponseCode != Response.REQUEST_TERMINATED) {
bobCall.waitOutgoingCallResponse(1000);
}
assertEquals(Response.REQUEST_TERMINATED, bobCall.getLastReceivedResponse().getStatusCode());
Request ackRequest = cancelTransaction.getServerTransaction().getDialog().createRequest(Request.ACK);
ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml");
ackRequest.setContent(null, contentTypeHeader);
assertNotNull(bobPhone.sendRequestWithTransaction(ackRequest, false, cancelTransaction.getServerTransaction().getDialog()));
//
// assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
// int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
// assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING);
//
// if (responseBob == Response.TRYING || responseBob == Response.RINGING) {
// SipTransaction cancelTransaction = bobCall.sendCancel();
// assertNotNull(cancelTransaction);
//
// bobCall.waitForAnswer(5 * 1000);
// assertEquals(Response.REQUEST_TERMINATED, bobCall.getLastReceivedResponse().getStatusCode());
//
// Request ackRequest = cancelTransaction.getServerTransaction().getDialog().createRequest(Request.ACK);
// ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml");
// ackRequest.setContent(null, contentTypeHeader);
//
// assertNotNull(bobPhone.sendRequestWithTransaction(ackRequest, false, cancelTransaction.getServerTransaction().getDialog()));
// }
}
@Test
@Category(UnstableTests.class)
public void testUssdMessageLengthExceeds() {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullMessageLengthExceeds, null, UssdPullTestMessages.ussdClientRequestBodyForMessageLengthExceeds, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING);
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue() == DialogState._CONFIRMED);
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
String receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessages.ussdRestcommResponseForMessageLengthExceeds.trim()));
bobCall.dispose();
}
@Test
public void testUssdPullClosedAccount() {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullDidClosedAccount, null, UssdPullTestMessages.ussdClientRequestBody, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode());
} else {
assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode());
}
bobCall.dispose();
}
@Test
public void testUssdPullSuspendedAccount() {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullDidSuspendedAccount, null, UssdPullTestMessages.ussdClientRequestBody, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode());
} else {
assertEquals(Response.FORBIDDEN, bobCall.getLastReceivedResponse().getStatusCode());
}
bobCall.dispose();
}
@Deployment(name = "UssdPullTest", managed = true, testable = false)
public static WebArchive createWebArchiveNoGw() {
logger.info("Packaging Test App");
reconfigurePorts();
Map<String,String> webInfResources = new HashMap();
webInfResources.put("restcomm.xml", "conf/restcomm.xml");
webInfResources.put("org/restcomm/connect/ussd/restcomm.script_ussdPullTest", "data/hsql/restcomm.script");
webInfResources.put("akka_application.conf", "classes/application.conf");
webInfResources.put("sip.xml", "/sip.xml");
webInfResources.put("web.xml", "web.xml");
Map<String, String> replacements = new HashMap();
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("5080", String.valueOf(restcommPort));
replacements.put("5090", String.valueOf(bobPort));
List<String> resources = new ArrayList(Arrays.asList(
"org/restcomm/connect/ussd/ussd-rcml.xml",
"org/restcomm/connect/ussd/ussd-rcml-collect.xml",
"org/restcomm/connect/ussd/ussd-rcml-character-limit-exceed.xml",
"org/restcomm/connect/ussd/ussd-rcml-shortdial.xml"
));
return WebArchiveUtil.createWebArchiveNoGw(webInfResources,
resources,
replacements);
}
}
| 26,829 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdPullTestMessages.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/UssdPullTestMessages.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
* @modified <a href="mailto:[email protected]"> Fernando Mendioroz </a>
*
*/
public class UssdPullTestMessages {
static String ussdClientRequestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"5544\"/>\n"
+ "</ussd-data>";
static String ussdClientRequestBodyForCollect = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"5555\"/>\n"
+ "</ussd-data>";
static String ussdRestcommResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ussd-data>\n"
+ "<language value=\"en\"></language>\n"
+ "<ussd-string value=\"The information you requested is 1234567890\"></ussd-string>\n"
+ "<anyExt>\n"
+ "<message-type>processUnstructuredSSRequest_Response</message-type>\n"
+ "</anyExt>\n"
+ "</ussd-data>\n";
static String ussdRestcommResponseWithCollect = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ussd-data>\n"
+ "<language value=\"en\"></language>\n"
+ "<ussd-string value=\"Please press\n1 For option1\n2 For option2\"></ussd-string>\n"
+ "<anyExt>\n"
+ "<message-type>unstructuredSSRequest_Request</message-type>\n"
+ "</anyExt>\n"
+ "</ussd-data>\n";
static String ussdClientResponseBodyToCollect = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"1\"/>\n"
+ "\t<anyExt>\n"
+ "\t\t<message-type>unstructuredSSRequest_Response</message-type>\n"
+ "\t</anyExt>\n"
+ "</ussd-data>";
static String ussdClientRequestBodyForMessageLengthExceeds = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"5566\"/>\n"
+ "</ussd-data>";
static String ussdRestcommResponseForMessageLengthExceeds = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ussd-data>\n"
+ "<language value=\"en\"></language>\n"
+ "<ussd-string value=\"Error while preparing the response.\nMessage length exceeds the maximum.\"></ussd-string>\n"
+ "<anyExt>\n"
+ "<message-type>processUnstructuredSSRequest_Response</message-type>\n"
+ "</anyExt>\n"
+ "</ussd-data>\n";
static String ussdClientFastDialRequestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"*777*3#\"/>\n"
+ "</ussd-data>";
static String ussdRestcommShortDialResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ussd-data>\n"
+ "<language value=\"en\"></language>\n"
+ "<ussd-string value=\"The information you requested for option 3 is bronze\"></ussd-string>\n"
+ "<anyExt>\n"
+ "<message-type>processUnstructuredSSRequest_Response</message-type>\n"
+ "</anyExt>\n"
+ "</ussd-data>\n";
}
| 4,291 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdPullTestMessagesEC2.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/UssdPullTestMessagesEC2.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
* @modified <a href="mailto:[email protected]"> Fernando Mendioroz </a>
*
*/
public class UssdPullTestMessagesEC2 {
static String ussdClientRequestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"5544\"/>\n"
+ "</ussd-data>";
static String ussdClientRequestBodyForCollect = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"5555\"/>\n"
+ "</ussd-data>";
static String ussdRestcommResponse = "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n"
+"<ussd-data>\n"
+"<language value=\"en\"/>\n"
+"<ussd-string value=\"You pressed 1 for option1, so here it is OPTION1\"/>\n"
+"<anyExt>\n"
+"<message-type>processUnstructuredSSRequest_Response</message-type>\n"
+"</anyExt>\n"
+"</ussd-data>";
static String ussdRestcommResponseWithCollect = "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n"
+ "<ussd-data>\n"
+ "<language value=\"en\"/>\n"
+ "<ussd-string value=\"Please press 1 for option1 or 2 for option 2\"/>\n"
+ "<anyExt>\n"
+ "<message-type>unstructuredSSRequest_Request</message-type>\n"
+ "</anyExt>\n"
+ "</ussd-data>";
static String ussdClientResponseBodyToCollect = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"1\"/>\n"
+ "\t<anyExt>\n"
+ "\t\t<message-type>unstructuredSSRequest_Response</message-type>\n"
+ "\t</anyExt>\n"
+ "</ussd-data>";
static String ussdClientRequestBodyForMessageLengthExceeds = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"5566\"/>\n"
+ "</ussd-data>";
static String ussdRestcommResponseForMessageLengthExceeds = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ussd-data>\n"
+ "<language value=\"en\"></language>\n"
+ "<ussd-string value=\"Error while preparing the response.\nMessage length exceeds the maximum.\"></ussd-string>\n"
+ "<anyExt>\n"
+ "<message-type>processUnstructuredSSRequest_Response</message-type>\n"
+ "</anyExt>\n"
+ "</ussd-data>\n";
static String ussdClientFastDialRequestBody = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
+ "<ussd-data>\n"
+ "\t<language value=\"en\"/>\n"
+ "\t<ussd-string value=\"*777*3#\"/>\n"
+ "</ussd-data>";
static String ussdRestcommShortDialResponse = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<ussd-data>\n"
+ "<language value=\"en\"></language>\n"
+ "<ussd-string value=\"The information you requested for option 3 is bronze\"></ussd-string>\n"
+ "<anyExt>\n"
+ "<message-type>processUnstructuredSSRequest_Response</message-type>\n"
+ "</anyExt>\n"
+ "</ussd-data>\n";
}
| 4,244 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RvdProjectsMigratorWorkspaceMigratedTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/RvdProjectsMigratorWorkspaceMigratedTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2015, Telestax Inc and individual contributors
* by the @authors tag.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.connect.testsuite;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.runner.RunWith;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.experimental.categories.Category;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.UnstableTests;
import org.restcomm.connect.commons.annotations.WithInMinsTests;
/**
* @author [email protected]
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInMinsTests.class, ParallelClassTests.class})
public class RvdProjectsMigratorWorkspaceMigratedTest {
private final static Logger logger = Logger.getLogger(RvdProjectsMigratorWorkspaceMigratedTest.class);
private static final String version = Version.getVersion();
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
private static int smtpPort = NetworkPortAssigner.retrieveNextPortByFile();
private String adminUsername = "[email protected]";
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
private static GreenMail mailServer;
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
public static void reconfigurePorts() throws Exception {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@AfterClass
public static void stopMailServer() {
mailServer.stop();
}
@Test
public void checkApplications() {
JsonArray applicationsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.APPLICATIONS);
for (int i = 0; i < applicationsListJson.size(); i++) {
JsonObject applicationJson = applicationsListJson.get(i).getAsJsonObject();
String applicationSid = applicationJson.get("sid").getAsString();
String applicationVoiceUrl = applicationJson.get("rcml_url").getAsString();
assertTrue(applicationVoiceUrl != null && !applicationVoiceUrl.isEmpty());
assertTrue(applicationVoiceUrl.contains(applicationSid));
}
}
@Test
@Category(UnstableTests.class)
public void checkIncomingPhoneNumbers() {
JsonArray incomingPhoneNumbersListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.INCOMING_PHONE_NUMBERS);
for(int i =0; i < incomingPhoneNumbersListJson.size(); i++){
JsonObject incomingPhoneNumberJson = incomingPhoneNumbersListJson.get(i).getAsJsonObject();
assertTrue(incomingPhoneNumberJson.get("voice_url").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("voice_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("sms_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("ussd_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("voice_application_sid").isJsonNull());
}
}
@Test
public void checkClients() {
JsonArray clientsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(deploymentUrl.toString(),
adminUsername, adminAuthToken, adminAccountSid, RestcommRvdProjectsMigratorTool.Endpoint.CLIENTS);
for (int i = 0; i < clientsListJson.size(); i++) {
JsonObject clientJson = clientsListJson.get(i).getAsJsonObject();
assertTrue(clientJson.get("voice_url") == null || clientJson.get("voice_url").isJsonNull());
assertTrue(!clientJson.get("voice_method").isJsonNull());
assertTrue(clientJson.get("voice_application_sid") == null || clientJson.get("voice_application_sid").isJsonNull());
}
}
@Test
public void checkNotifications() {
JsonArray notificationsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.NOTIFICATIONS, "notifications");
String message = notificationsListJson.toString();
assertTrue(message.contains("Workspace migration finished with success"));
assertTrue(message.contains("3 Projects processed"));
assertTrue(message.contains("3 with success"));
assertTrue(message.contains("0 with error"));
assertTrue(message.contains("0 IncomingPhoneNumbers"));
assertTrue(message.contains("0 Clients"));
}
@Test
@Category(UnstableTests.class)
public void checkEmail() throws IOException, MessagingException, InterruptedException {
mailServer.waitForIncomingEmail(60000, 1);
MimeMessage[] messages = mailServer.getReceivedMessages();
assertNotNull(messages);
assertEquals(1, messages.length);
MimeMessage m = messages[0];
assertTrue(String.valueOf(m.getContent()).contains("Workspace migration finished with success"));
assertTrue(String.valueOf(m.getContent()).contains("3 Projects processed"));
assertTrue(String.valueOf(m.getContent()).contains("3 with success"));
assertTrue(String.valueOf(m.getContent()).contains("0 with error"));
assertTrue(String.valueOf(m.getContent()).contains("0 IncomingPhoneNumbers"));
assertTrue(String.valueOf(m.getContent()).contains("0 Clients"));
}
@Deployment(name = "RvdProjectsMigratorWorkspaceMigratedTest", managed = true, testable = false)
public static WebArchive createWebArchiveRestcomm() throws Exception {
logger.info("Packaging Test App");
reconfigurePorts();
Map<String, String> replacements = new HashMap();
replacements.put("3025", String.valueOf(smtpPort));
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("5080", String.valueOf(restcommPort));
List<String> resources = new ArrayList(Arrays.asList(
));
WebArchive archive = WebArchiveUtil.createWebArchiveNoGw("restcomm_workspaceMigration.xml",
"restcomm.script_projectMigratorWorkspaceMigratedTest",
resources, replacements);
String source = "src/test/resources/workspace-migration-scenarios/migrated";
String target = "workspace-migration";
File f = new File(source);
addFiles(archive, f, source, target);
return archive;
}
private static void addFiles(WebArchive war, File dir, String source, String target) throws Exception {
if (!dir.isDirectory()) {
throw new Exception("not a directory");
}
for (File f : dir.listFiles()) {
if (f.isFile()) {
String prefix = target != null && !target.isEmpty() ? target : "";
war.addAsWebResource(f, prefix + f.getPath().replace("\\", "/").substring(source.length()));
} else {
addFiles(war, f, source, target);
}
}
}
@BeforeClass
public static void startEmailServer() {
ServerSetup setup = new ServerSetup(smtpPort, "127.0.0.1", "smtp");
mailServer = new GreenMail(setup);
mailServer.start();
mailServer.setUser("hascode@localhost", "hascode", "abcdef123");
}
}
| 10,131 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RvdProjectsMigratorWorkspaceOriginalTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/RvdProjectsMigratorWorkspaceOriginalTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2015, Telestax Inc and individual contributors
* by the @authors tag.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.connect.testsuite;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.runner.RunWith;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.experimental.categories.Category;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.UnstableTests;
import org.restcomm.connect.commons.annotations.WithInMinsTests;
/**
* @author [email protected]
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInMinsTests.class, ParallelClassTests.class})
public class RvdProjectsMigratorWorkspaceOriginalTest {
private final static Logger logger = Logger.getLogger(RvdProjectsMigratorWorkspaceOriginalTest.class);
private static final String version = Version.getVersion();
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
private static int smtpPort = NetworkPortAssigner.retrieveNextPortByFile();
private String adminUsername = "[email protected]";
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
private static ArrayList<String> applicationNames;
private static GreenMail mailServer;
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
public static void reconfigurePorts() throws Exception {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@BeforeClass
public static void before() {
applicationNames = new ArrayList<String>();
applicationNames.add("rvdCollectVerbDemo");
applicationNames.add("rvdESDemo");
applicationNames.add("rvdSayVerbDemo");
}
@AfterClass
public static void stopMailServer() {
mailServer.stop();
}
@Test
public void checkApplications() {
JsonArray applicationsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.APPLICATIONS);
boolean result = true;
for (String applicationName : applicationNames) {
boolean current = false;
for (int i = 0; i < applicationsListJson.size(); i++) {
JsonObject applicationJson = applicationsListJson.get(i).getAsJsonObject();
String applicationNameJson = applicationJson.get("friendly_name").getAsString();
if (applicationName.equals(applicationNameJson)) {
current = true;
break;
}
}
if (!current) {
result = false;
break;
}
}
assertTrue(result);
}
@Test
@Category(UnstableTests.class)
public void checkIncomingPhoneNumbers() {
JsonArray incomingPhoneNumbersListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.INCOMING_PHONE_NUMBERS);
for (int i = 0; i < incomingPhoneNumbersListJson.size(); i++) {
JsonObject incomingPhoneNumberJson = incomingPhoneNumbersListJson.get(i).getAsJsonObject();
assertTrue(incomingPhoneNumberJson.get("voice_url").isJsonNull());
String applicationSid = incomingPhoneNumberJson.get("voice_application_sid").getAsString();
JsonObject applicationJson = RestcommRvdProjectsMigratorTool.getInstance().getEntity(deploymentUrl.toString(),
adminUsername, adminAuthToken, adminAccountSid, applicationSid,
RestcommRvdProjectsMigratorTool.Endpoint.APPLICATIONS);
assertTrue(!incomingPhoneNumberJson.get("voice_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("sms_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("ussd_method").isJsonNull());
assertTrue(applicationJson != null);
assertTrue(!applicationJson.isJsonNull());
assertTrue(applicationJson.get("sid").getAsString().equals(applicationSid));
}
}
@Test
public void checkClients() {
JsonArray clientsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(deploymentUrl.toString(),
adminUsername, adminAuthToken, adminAccountSid, RestcommRvdProjectsMigratorTool.Endpoint.CLIENTS);
for (int i = 0; i < clientsListJson.size(); i++) {
JsonObject clientJson = clientsListJson.get(i).getAsJsonObject();
assertTrue(clientJson.get("voice_url") == null || clientJson.get("voice_url").isJsonNull());
assertTrue(!clientJson.get("voice_method").isJsonNull());
assertTrue(clientJson.get("voice_application_sid") == null || clientJson.get("voice_application_sid").isJsonNull());
}
}
@Test
public void checkNotifications() {
JsonArray notificationsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.NOTIFICATIONS, "notifications");
String message = notificationsListJson.toString();
assertTrue(message.contains("Workspace migration finished with success"));
assertTrue(message.contains("3 Projects processed"));
assertTrue(message.contains("3 with success"));
assertTrue(message.contains("0 with error"));
assertTrue(message.contains("3 IncomingPhoneNumbers"));
assertTrue(message.contains("0 Clients"));
}
@Test
@Category({UnstableTests.class})
public void checkEmail() throws IOException, MessagingException, InterruptedException {
mailServer.waitForIncomingEmail(60000, 1);
MimeMessage[] messages = mailServer.getReceivedMessages();
assertNotNull(messages);
assertEquals(1, messages.length);
MimeMessage m = messages[0];
assertTrue(String.valueOf(m.getContent()).contains("Workspace migration finished with success"));
assertTrue(String.valueOf(m.getContent()).contains("3 Projects processed"));
assertTrue(String.valueOf(m.getContent()).contains("3 with success"));
assertTrue(String.valueOf(m.getContent()).contains("0 with error"));
assertTrue(String.valueOf(m.getContent()).contains("3 IncomingPhoneNumbers"));
assertTrue(String.valueOf(m.getContent()).contains("0 Clients"));
}
@Deployment(name = "RvdProjectsMigratorWorkspaceOriginalTest", managed = true, testable = false)
public static WebArchive createWebArchiveRestcomm() throws Exception {
logger.info("Packaging Test App");
reconfigurePorts();
Map<String, String> replacements = new HashMap();
replacements.put("3025", String.valueOf(smtpPort));
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("5080", String.valueOf(restcommPort));
List<String> resources = new ArrayList(Arrays.asList(
));
WebArchive archive = WebArchiveUtil.createWebArchiveNoGw("restcomm_workspaceMigration.xml",
"restcomm.script_projectMigratorWorkspaceOriginalTest",
resources, replacements);
String source = "src/test/resources/workspace-migration-scenarios/original";
String target = "workspace-migration";
File f = new File(source);
addFiles(archive, f, source, target);
return archive;
}
private static void addFiles(WebArchive war, File dir, String source, String target) throws Exception {
if (!dir.isDirectory()) {
throw new Exception("not a directory");
}
for (File f : dir.listFiles()) {
if (f.isFile()) {
String prefix = target != null && !target.isEmpty() ? target : "";
war.addAsWebResource(f, prefix + f.getPath().replace("\\", "/").substring(source.length()));
} else {
addFiles(war, f, source, target);
}
}
}
@BeforeClass
public static void startEmailServer() {
ServerSetup setup = new ServerSetup(smtpPort, "127.0.0.1", "smtp");
mailServer = new GreenMail(setup);
mailServer.start();
mailServer.setUser("hascode@localhost", "hascode", "abcdef123");
}
}
| 11,127 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RvdProjectsMigratorWorkspaceMixedTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/RvdProjectsMigratorWorkspaceMixedTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2015, Telestax Inc and individual contributors
* by the @authors tag.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.connect.testsuite;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.runner.RunWith;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.icegreen.greenmail.util.GreenMail;
import com.icegreen.greenmail.util.ServerSetup;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.experimental.categories.Category;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.UnstableTests;
import org.restcomm.connect.commons.annotations.WithInMinsTests;
/**
* @author [email protected]
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInMinsTests.class, ParallelClassTests.class})
public class RvdProjectsMigratorWorkspaceMixedTest {
private final static Logger logger = Logger.getLogger(RvdProjectsMigratorWorkspaceMixedTest.class);
private static final String version = Version.getVersion();
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
private static int smtpPort = NetworkPortAssigner.retrieveNextPortByFile();
private String adminUsername = "[email protected]";
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
private String didSid = "PNc2b81d68a221482ea387b6b4e2cbd9d7";
private String clientSid = "CLa2b99142e111427fbb489c3de357f60a";
private static ArrayList<String> applicationNames;
private static ArrayList<String> didSids;
private static ArrayList<String> clientSids;
private static GreenMail mailServer;
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
public static void reconfigurePorts() throws Exception {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@BeforeClass
public static void before() {
applicationNames = new ArrayList<String>();
applicationNames.add("project-1");
applicationNames.add("project-2");
applicationNames.add("project-3");
applicationNames.add("project-4");
applicationNames.add("rvdCollectVerbDemo");
applicationNames.add("rvdESDemo");
applicationNames.add("AP670c33bf0b6748f09eaec97030af36f3");
didSids = new ArrayList<String>();
didSids.add("PN46678e5b01d44973bf184f6527bc33f7");
didSids.add("PN46678e5b01d44973bf184f6527bc33f1");
didSids.add("PN46678e5b01d44973bf184f6527bc33f2");
clientSids = new ArrayList<String>();
clientSids.add("CL3003328d0de04ba68f38de85b732ed56");
clientSids.add("CL3003328d0de04ba68f38de85b732ed51");
clientSids.add("CL3003328d0de04ba68f38de85b732ed52");
}
@AfterClass
public static void stopMailServer() {
mailServer.stop();
}
@Test
public void checkApplications() {
JsonArray applicationsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.APPLICATIONS);
boolean result = true;
for (String applicationName : applicationNames) {
boolean current = false;
for (int i = 0; i < applicationsListJson.size(); i++) {
JsonObject applicationJson = applicationsListJson.get(i).getAsJsonObject();
String applicationNameJson = applicationJson.get("friendly_name").getAsString();
if (applicationName.equals(applicationNameJson)) {
current = true;
break;
}
}
if (!current) {
result = false;
break;
}
}
assertTrue(result);
}
@Test
@Category(UnstableTests.class)
public void checkIncomingPhoneNumbers() {
// Check those who should be migrated
JsonArray incomingPhoneNumbersListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.INCOMING_PHONE_NUMBERS);
boolean result = true;
for (String didSid : didSids) {
boolean current = false;
for (int i = 0; i < incomingPhoneNumbersListJson.size(); i++) {
JsonObject incomingPhoneNumberJson = incomingPhoneNumbersListJson.get(i).getAsJsonObject();
if (incomingPhoneNumberJson.get("sid").getAsString().equals(didSid)) {
assertTrue(incomingPhoneNumberJson.get("voice_url").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("voice_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("sms_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("ussd_method").isJsonNull());
String applicationSid = incomingPhoneNumberJson.get("voice_application_sid").getAsString();
JsonObject applicationJson = RestcommRvdProjectsMigratorTool.getInstance().getEntity(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid,
RestcommRvdProjectsMigratorTool.Endpoint.APPLICATIONS);
assertTrue(applicationJson != null);
assertTrue(!applicationJson.isJsonNull());
assertTrue(applicationJson.get("sid").getAsString().equals(applicationSid));
current = true;
break;
}
}
if (!current) {
result = false;
break;
}
}
assertTrue(result);
// Check the one who should not be touched
JsonObject incomingPhoneNumberJson = RestcommRvdProjectsMigratorTool.getInstance().getEntity(deploymentUrl.toString(),
adminUsername, adminAuthToken, adminAccountSid, didSid,
RestcommRvdProjectsMigratorTool.Endpoint.INCOMING_PHONE_NUMBERS);
assertTrue(incomingPhoneNumberJson.get("voice_application_sid").isJsonNull());
assertTrue(incomingPhoneNumberJson.get("voice_url").isJsonNull());
}
@Test
@Category(UnstableTests.class)
public void checkClients() {
// Check those who should be migrated
JsonArray clientsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(deploymentUrl.toString(),
adminUsername, adminAuthToken, adminAccountSid, RestcommRvdProjectsMigratorTool.Endpoint.CLIENTS);
boolean result = true;
for (String clientSid : clientSids) {
boolean current = false;
for (int i = 0; i < clientsListJson.size(); i++) {
JsonObject clientJson = clientsListJson.get(i).getAsJsonObject();
if (clientJson.get("sid").getAsString().equals(clientSid)) {
assertTrue(clientJson.get("voice_url") == null || clientJson.get("voice_url").isJsonNull());
assertTrue(!clientJson.get("voice_method").isJsonNull());
String applicationSid = clientJson.get("voice_application_sid").getAsString();
JsonObject applicationJson = RestcommRvdProjectsMigratorTool.getInstance().getEntity(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid, applicationSid,
RestcommRvdProjectsMigratorTool.Endpoint.APPLICATIONS);
assertTrue(applicationJson != null);
assertTrue(!applicationJson.isJsonNull());
assertTrue(applicationJson.get("sid").getAsString().equals(applicationSid));
current = true;
break;
}
}
if (!current) {
result = false;
break;
}
}
assertTrue(result);
// Check the one who should not be touched
JsonObject clientJson = RestcommRvdProjectsMigratorTool.getInstance().getEntity(deploymentUrl.toString(),
adminUsername, adminAuthToken, adminAccountSid, clientSid, RestcommRvdProjectsMigratorTool.Endpoint.CLIENTS);
assertTrue(clientJson.get("voice_url") == null || clientJson.get("voice_url").isJsonNull());
assertTrue(clientJson.get("voice_application_sid") == null || clientJson.get("voice_application_sid").isJsonNull());
}
@Test
public void checkNotifications() {
JsonArray notificationsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.NOTIFICATIONS, "notifications");
String message = notificationsListJson.toString();
assertTrue(message.contains("Workspace migration finished with success"));
assertTrue(message.contains("7 Projects processed"));
assertTrue(message.contains("7 with success"));
assertTrue(message.contains("0 with error"));
assertTrue(message.contains("3 IncomingPhoneNumbers"));
assertTrue(message.contains("3 Clients"));
}
@Test
@Category({UnstableTests.class})
public void checkEmail() throws IOException, MessagingException, InterruptedException {
mailServer.waitForIncomingEmail(60000, 1);
MimeMessage[] messages = mailServer.getReceivedMessages();
assertNotNull(messages);
assertEquals(1, messages.length);
MimeMessage m = messages[0];
assertTrue(String.valueOf(m.getContent()).contains("Workspace migration finished with success"));
assertTrue(String.valueOf(m.getContent()).contains("7 Projects processed"));
assertTrue(String.valueOf(m.getContent()).contains("7 with success"));
assertTrue(String.valueOf(m.getContent()).contains("0 with error"));
assertTrue(String.valueOf(m.getContent()).contains("3 IncomingPhoneNumbers"));
assertTrue(String.valueOf(m.getContent()).contains("3 Clients"));
}
@Deployment(name = "RvdProjectsMigratorWorkspaceMixedTest", managed = true, testable = false)
public static WebArchive createWebArchiveRestcomm() throws Exception {
logger.info("Packaging Test App");
reconfigurePorts();
Map<String, String> replacements = new HashMap();
replacements.put("3025", String.valueOf(smtpPort));
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("5080", String.valueOf(restcommPort));
List<String> resources = new ArrayList(Arrays.asList(
));
WebArchive archive = WebArchiveUtil.createWebArchiveNoGw("restcomm_workspaceMigration.xml",
"restcomm.script_projectMigratorWorkspaceMixedTest", resources, replacements);
String source = "src/test/resources/workspace-migration-scenarios/mixed";
String target = "workspace-migration";
File f = new File(source);
addFiles(archive, f, source, target);
return archive;
}
private static void addFiles(WebArchive war, File dir, String source, String target) throws Exception {
if (!dir.isDirectory()) {
throw new Exception("not a directory");
}
for (File f : dir.listFiles()) {
if (f.isFile()) {
String prefix = target != null && !target.isEmpty() ? target : "";
war.addAsWebResource(f, prefix + f.getPath().replace("\\", "/").substring(source.length()));
} else {
addFiles(war, f, source, target);
}
}
}
@BeforeClass
public static void startEmailServer() {
ServerSetup setup = new ServerSetup(smtpPort, "127.0.0.1", "smtp");
mailServer = new GreenMail(setup);
mailServer.start();
mailServer.setUser("hascode@localhost", "hascode", "abcdef123");
}
}
| 14,553 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
VersionTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/VersionTest.java | package org.restcomm.connect.testsuite;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.restcomm.connect.commons.Version;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
* @author <a href="mailto:[email protected]">Jean Deruelle</a>
*/
public class VersionTest {
private final static Logger logger = Logger.getLogger(VersionTest.class.getName());
private static final String version = Version.getVersion();
@Test
public void testVersion() {
logger.info(version);
}
}
| 618 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdPullTestEC2.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/UssdPullTestEC2.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite;
import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import javax.sip.DialogState;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.address.Address;
import javax.sip.header.ContentTypeHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipRequest;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.restcomm.connect.commons.Version;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
@Ignore //Ignore because this will be running only manually against an EC2 instance
public class UssdPullTestEC2 {
private final static Logger logger = Logger.getLogger(UssdPullTestEC2.class.getName());
private static final String version = Version.getVersion();
private static SipStackTool tool1;
private String ec2IPAddress = "54.198.164.153";
private String myIpAddress = "192.168.1.70";
private SipStack bobSipStack;
private SipPhone bobPhone;
private String bobContact = "sip:bob@"+myIpAddress+":5090";
private String ussdPullWithCollectDID = "sip:*123#@"+ec2IPAddress+":5080";
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("UssdPullTest");
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, myIpAddress, "5090", ec2IPAddress+":5080");
bobPhone = bobSipStack.createSipPhone(ec2IPAddress, SipStack.PROTOCOL_UDP, 5080, bobContact);
}
@After
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
bobPhone = null;
}
if (bobSipStack != null) {
bobSipStack.dispose();
bobSipStack = null;
}
}
@Test
public void testUssdPullWithCollect() throws InterruptedException, SipException, ParseException {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullWithCollectDID, null, UssdPullTestMessages.ussdClientRequestBodyForCollect, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING);
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue()==DialogState._CONFIRMED);
String toTag = bobCall.getDialog().getLocalTag();
Address bobAddress = bobPhone.getAddress();
bobPhone.setLoopback(true);
assertTrue(bobPhone.listenRequestMessage());
RequestEvent requestEvent = bobPhone.waitRequest(30*1000);
assertNotNull(requestEvent);
assertTrue(requestEvent.getRequest().getMethod().equalsIgnoreCase("INFO"));
bobPhone.sendReply(requestEvent, 200, "OK", toTag, bobAddress, 0);
String receivedUssdPayload = new String(requestEvent.getRequest().getRawContent());
System.out.println("receivedUssdPayload: \n"+receivedUssdPayload);
System.out.println("UssdPullTestMessagesEC2.ussdRestcommResponseWithCollect: \n"+UssdPullTestMessagesEC2.ussdRestcommResponseWithCollect);
assertTrue(receivedUssdPayload.equals(UssdPullTestMessagesEC2.ussdRestcommResponseWithCollect.trim()));
Request infoResponse = requestEvent.getDialog().createRequest(Request.INFO);
ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml");
infoResponse.setContent(UssdPullTestMessages.ussdClientResponseBodyToCollect.getBytes(), contentTypeHeader);
bobPhone.sendRequestWithTransaction(infoResponse, false, requestEvent.getDialog());
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessagesEC2.ussdRestcommResponse.trim()));
bobCall.dispose();
}
}
| 6,148 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
RvdProjectsMigratorDisabled.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/RvdProjectsMigratorDisabled.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2015, Telestax Inc and individual contributors
* by the @authors tag.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.restcomm.connect.testsuite;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.net.URL;
import org.apache.log4j.Logger;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.runner.RunWith;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.restcomm.connect.commons.Version;
/**
* @author [email protected]
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class RvdProjectsMigratorDisabled {
private final static Logger logger = Logger.getLogger(RvdProjectsMigratorDisabled.class);
private static final String version = Version.getVersion();
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
private String adminUsername = "[email protected]";
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
@Test
public void checkApplications() {
JsonArray applicationsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.APPLICATIONS);
for (int i = 0; i < applicationsListJson.size(); i++) {
JsonObject applicationJson = applicationsListJson.get(i).getAsJsonObject();
String applicationSid = applicationJson.get("sid").getAsString();
String applicationVoiceUrl = applicationJson.get("rcml_url").getAsString();
assertTrue(applicationVoiceUrl != null && !applicationVoiceUrl.isEmpty());
assertTrue(applicationVoiceUrl.contains(applicationSid));
}
}
@Test
public void checkIncomingPhoneNumbers() {
JsonArray incomingPhoneNumbersListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.INCOMING_PHONE_NUMBERS);
for(int i =0; i < incomingPhoneNumbersListJson.size(); i++){
JsonObject incomingPhoneNumberJson = incomingPhoneNumbersListJson.get(i).getAsJsonObject();
assertTrue(incomingPhoneNumberJson.get("voice_url").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("voice_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("sms_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("ussd_method").isJsonNull());
assertTrue(!incomingPhoneNumberJson.get("voice_application_sid").isJsonNull());
}
}
@Test
public void checkClients() {
JsonArray clientsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(deploymentUrl.toString(),
adminUsername, adminAuthToken, adminAccountSid, RestcommRvdProjectsMigratorTool.Endpoint.CLIENTS);
for (int i = 0; i < clientsListJson.size(); i++) {
JsonObject clientJson = clientsListJson.get(i).getAsJsonObject();
assertTrue(clientJson.get("voice_url") == null || clientJson.get("voice_url").isJsonNull());
assertTrue(!clientJson.get("voice_method").isJsonNull());
assertTrue(clientJson.get("voice_application_sid") == null || clientJson.get("voice_application_sid").isJsonNull());
}
}
@Test
public void checkNotifications() {
JsonArray notificationsListJson = RestcommRvdProjectsMigratorTool.getInstance().getEntitiesList(
deploymentUrl.toString(), adminUsername, adminAuthToken, adminAccountSid,
RestcommRvdProjectsMigratorTool.Endpoint.NOTIFICATIONS);
String message = notificationsListJson.toString();
assertTrue(!message.contains("Workspace migration"));
}
@Deployment(name = "RvdProjectsMigratorDisabled", managed = true, testable = false)
public static WebArchive createWebArchiveRestcomm() throws Exception {
WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war");
final WebArchive restcommArchive = Maven.resolver()
.resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity()
.asSingle(WebArchive.class);
archive = archive.merge(restcommArchive);
archive.delete("/WEB-INF/sip.xml");
archive.delete("/WEB-INF/web.xml");
archive.delete("/WEB-INF/conf/restcomm.xml");
archive.delete("/WEB-INF/data/hsql/restcomm.script");
archive.addAsWebInfResource("sip.xml");
archive.addAsWebInfResource("web.xml");
archive.addAsWebInfResource("restcomm_workspaceMigrationDisabled.xml", "conf/restcomm.xml");
archive.addAsWebInfResource("restcomm.script_projectMigratorWorkspaceMigratedTest", "data/hsql/restcomm.script");
String source = "src/test/resources/workspace-migration-scenarios/migrated";
String target = "workspace-migration";
File f = new File(source);
addFiles(archive, f, source, target);
return archive;
}
private static void addFiles(WebArchive war, File dir, String source, String target) throws Exception {
if (!dir.isDirectory()) {
throw new Exception("not a directory");
}
for (File f : dir.listFiles()) {
if (f.isFile()) {
String prefix = target != null && !target.isEmpty() ? target : "";
war.addAsWebResource(f, prefix + f.getPath().replace("\\", "/").substring(source.length()));
} else {
addFiles(war, f, source, target);
}
}
}
}
| 7,105 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
UssdCollectMessageTestLive.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/UssdCollectMessageTestLive.java | package org.restcomm.connect.testsuite;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipRequest;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.restcomm.connect.commons.Version;
import javax.sip.DialogState;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.address.Address;
import javax.sip.header.ContentTypeHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.text.ParseException;
import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Created by gvagenas on 4/10/16.
*/
@Ignore
public class UssdCollectMessageTestLive {
private final static Logger logger = Logger.getLogger(UssdCollectMessageTestLive.class.getName());
private static final String version = Version.getVersion();
private static SipStackTool tool1;
private String restcommAddress = "192.168.1.151";
private String myIpAddress = "192.168.1.151";
private SipStack bobSipStack;
private SipPhone bobPhone;
private String bobContact = "sip:bob@"+myIpAddress+":5090";
private String ussdPullWithCollectDID = "sip:*123#@"+ restcommAddress +":5080";
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("UssdPullTest");
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, myIpAddress, "5090", restcommAddress +":5080");
bobPhone = bobSipStack.createSipPhone(restcommAddress, SipStack.PROTOCOL_UDP, 5080, bobContact);
}
@After
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
bobPhone = null;
}
if (bobSipStack != null) {
bobSipStack.dispose();
bobSipStack = null;
}
}
@Test @Ignore
public void testUssdPullWithCollect() throws InterruptedException, SipException, ParseException {
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, ussdPullWithCollectDID, null, UssdPullTestMessagesEC2.ussdClientRequestBodyForCollect, "application", "vnd.3gpp.ussd+xml", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING);
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(bobCall.getDialog().getState().getValue()== DialogState._CONFIRMED);
String toTag = bobCall.getDialog().getLocalTag();
Address bobAddress = bobPhone.getAddress();
bobPhone.setLoopback(true);
assertTrue(bobPhone.listenRequestMessage());
RequestEvent requestEvent = bobPhone.waitRequest(30*1000);
assertNotNull(requestEvent);
assertTrue(requestEvent.getRequest().getMethod().equalsIgnoreCase("INFO"));
bobPhone.sendReply(requestEvent, 200, "OK", toTag, bobAddress, 0);
String receivedUssdPayload = new String(requestEvent.getRequest().getRawContent());
System.out.println("receivedUssdPayload: \n"+receivedUssdPayload);
System.out.println("UssdPullTestMessagesEC2.ussdRestcommResponseWithCollect: \n"+UssdPullTestMessagesEC2.ussdRestcommResponseWithCollect);
assertTrue(receivedUssdPayload.equals(UssdPullTestMessagesEC2.ussdRestcommResponseWithCollect.trim()));
Request infoResponse = requestEvent.getDialog().createRequest(Request.INFO);
ContentTypeHeader contentTypeHeader = bobCall.getHeaderFactory().createContentTypeHeader("application", "vnd.3gpp.ussd+xml");
infoResponse.setContent(UssdPullTestMessages.ussdClientResponseBodyToCollect.getBytes(), contentTypeHeader);
bobPhone.sendRequestWithTransaction(infoResponse, false, requestEvent.getDialog());
assertTrue(bobCall.listenForDisconnect());
assertTrue(bobCall.waitForDisconnect(30 * 1000));
bobCall.respondToDisconnect();
SipRequest bye = bobCall.getLastReceivedRequest();
receivedUssdPayload = new String(bye.getRawContent());
assertTrue(receivedUssdPayload.equalsIgnoreCase(UssdPullTestMessagesEC2.ussdRestcommResponse.trim()));
bobCall.dispose();
}
}
| 5,210 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsOutTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/sms/SmsOutTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite.sms;
import static org.junit.Assert.assertTrue;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sip.address.SipURI;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.Credential;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.FeatureExpTests;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.WithInSecsTests;
import org.restcomm.connect.testsuite.NetworkPortAssigner;
import org.restcomm.connect.testsuite.WebArchiveUtil;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInSecsTests.class, ParallelClassTests.class})
public class SmsOutTest {
private final static Logger logger = Logger.getLogger(SmsOutTest.class);
private static final String version = Version.getVersion();
private static SipStackTool tool1;
private static SipStackTool tool2;
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
private SipStack aliceSipStack;
private SipPhone alicePhone;
private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String aliceContact = "sip:[email protected]:" + alicePort;
private SipStack outboundDestSipStack;
private SipPhone outboundDestPhone;
private static String outboundPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String outboundDestContact = "sip:[email protected]:" + outboundPort;
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("SmsTest1");
tool2 = new SipStackTool("SmsTest2");
}
public static void reconfigurePorts() {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@Before
public void before() throws Exception {
aliceSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact);
alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact);
outboundDestSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", outboundPort, restcommContact);
outboundDestPhone = outboundDestSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, outboundDestContact);
}
@After
public void after() throws Exception {
if (aliceSipStack != null) {
aliceSipStack.dispose();
}
if (alicePhone != null) {
alicePhone.dispose();
}
if (outboundDestSipStack != null) {
outboundDestSipStack.dispose();
}
if (outboundDestPhone != null) {
outboundDestPhone.dispose();
}
}
@Test
@Category(value={FeatureExpTests.class})
public void testSendSmsToInvalidNumber() throws ParseException, InterruptedException {
SipCall outboundDestCall = outboundDestPhone.createSipCall();
outboundDestCall.listenForMessage();
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
Credential credential = new Credential("127.0.0.1", "alice", "1234");
alicePhone.addUpdateCredential(credential);
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.initiateOutgoingMessage(aliceContact, "sip:9898989@" + restcommContact, null, null, null, "Test message");
assertTrue(aliceCall.waitForAuthorisation(5000));
assertTrue(aliceCall.waitOutgoingMessageResponse(5000));
assertTrue(aliceCall.getLastReceivedResponse().getStatusCode() == 100);
assertTrue(outboundDestCall.waitForMessage(5000));
assertTrue(outboundDestCall.sendMessageResponse(404, "Not Found", 3600, null));
assertTrue(aliceCall.waitOutgoingMessageResponse(5000));
logger.info("Last received response status code: "+aliceCall.getLastReceivedResponse().getStatusCode());
assertTrue(aliceCall.getLastReceivedResponse().getStatusCode() == 404);
}
@Test
public void testSendSmsToValidNumber() throws ParseException, InterruptedException {
SipCall outboundDestCall = outboundDestPhone.createSipCall();
outboundDestCall.listenForMessage();
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
Credential credential = new Credential("127.0.0.1", "alice", "1234");
alicePhone.addUpdateCredential(credential);
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.initiateOutgoingMessage(aliceContact, "sip:9898989@" + restcommContact, null, null, null, "Test message");
assertTrue(aliceCall.waitForAuthorisation(5000));
assertTrue(aliceCall.waitOutgoingMessageResponse(5000));
assertTrue(aliceCall.getLastReceivedResponse().getStatusCode() == 100);
assertTrue(outboundDestCall.waitForMessage(5000));
assertTrue(outboundDestCall.sendMessageResponse(202, "Accepted", 3600, null));
assertTrue(aliceCall.waitOutgoingMessageResponse(5000));
logger.info("Last received response status code: "+aliceCall.getLastReceivedResponse().getStatusCode());
assertTrue(aliceCall.getLastReceivedResponse().getStatusCode() == 202);
}
@Deployment(name = "SmsTest", managed = true, testable = false)
public static WebArchive createWebArchive() {
reconfigurePorts();
Map<String, String> webInfResources = new HashMap();
webInfResources.put("restcomm_SmsTest2.xml", "conf/restcomm.xml");
webInfResources.put("restcomm.script_SmsTest", "data/hsql/restcomm.script");
webInfResources.put("sip.xml", "sip.xml");
webInfResources.put("web_for_SmsTest.xml", "web.xml");
webInfResources.put("akka_application.conf", "classes/application.conf");
Map<String, String> replacements = new HashMap();
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("5080", String.valueOf(restcommPort));
replacements.put("5091", String.valueOf(alicePort));
replacements.put("5094", String.valueOf(outboundPort));
List<String> resources = new ArrayList(Arrays.asList(
));
return WebArchiveUtil.createWebArchiveNoGw(webInfResources,
resources,
replacements);
}
}
| 8,787 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsSessionTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/sms/SmsSessionTest.java | package org.restcomm.connect.testsuite.sms;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sip.address.SipURI;
import javax.sip.header.Header;
import org.cafesip.sipunit.Credential;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
//import org.restcomm.connect.sms.Version;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.FeatureAltTests;
import org.restcomm.connect.commons.annotations.FeatureExpTests;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.WithInSecsTests;
import org.restcomm.connect.testsuite.NetworkPortAssigner;
import org.restcomm.connect.testsuite.WebArchiveUtil;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
/**
* @author [email protected] (Thomas Quintana)
* @author [email protected] (George Vagenas)
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInSecsTests.class, ParallelClassTests.class})
public final class SmsSessionTest {
private static final String version = Version.getVersion();
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile();
@Rule
public WireMockRule wireMockRule = new WireMockRule(mockPort);
private static SipStackTool tool;
private SipStack receiver;
private SipPhone phone;
private static String phonePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String phoneContact = "sip:[email protected]:" + phonePort;
private static SipStackTool tool2;
private SipStack alice;
private SipPhone alicePhone;
private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String aliceContact = "sip:[email protected]:" + alicePort;
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
public SmsSessionTest() {
super();
}
@BeforeClass
public static void beforeClass() throws Exception {
tool = new SipStackTool("SmsSessionTest");
tool2 = new SipStackTool("SmsSessionTest2");
}
public static void reconfigurePorts() {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@Before
public void before() throws Exception {
receiver = tool.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", phonePort, restcommContact);
phone = receiver.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, phoneContact);
alice = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact);
alicePhone = alice.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact);
}
@After
public void after() throws Exception {
if (phone != null) {
phone.dispose();
}
if (receiver != null) {
receiver.dispose();
}
if (alicePhone != null) {
alicePhone.dispose();
}
if (alice != null) {
alice.dispose();
}
Thread.sleep(1000);
}
@Test
public void testSendSmsRedirectReceiveSms() throws ParseException {
// Send restcomm an sms.
final String proxy = phone.getStackAddress() + ":" + restcommPort + ";lr/udp";
final String to = "sip:+12223334450@" + restcommContact;
final String body = "Hello, waiting your response!";
final SipCall call = phone.createSipCall();
call.initiateOutgoingMessage(to, proxy, body);
assertLastOperationSuccess(call);
// Wait for a response sms.
phone.setLoopback(true);
phone.listenRequestMessage();
assertTrue(call.waitForMessage(60 * 1000));
call.sendMessageResponse(202, "Accepted", -1);
final List<String> messages = call.getAllReceivedMessagesContent();
assertTrue(messages.size() > 0);
assertTrue(messages.get(0).equals("Hello World!"));
}
@Test
@Category(value={FeatureAltTests.class})
public void testSendSmsRedirectReceiveSms2() throws ParseException {
// Send restcomm an sms.
final String proxy = phone.getStackAddress() + ":" + restcommPort + ";lr/udp";
final String to = "sip:2001@" + restcommContact;
final String body = "Hello, waiting your response!";
final SipCall call = phone.createSipCall();
call.initiateOutgoingMessage(to, proxy, body);
assertLastOperationSuccess(call);
// Wait for a response sms.
phone.setLoopback(true);
phone.listenRequestMessage();
assertTrue(call.waitForMessage(60 * 1000));
call.sendMessageResponse(202, "Accepted", -1);
final List<String> messages = call.getAllReceivedMessagesContent();
assertTrue(messages.size() > 0);
assertTrue(messages.get(0).equals("Hello World!"));
}
@Test
@Category(value={FeatureAltTests.class})
public void testSendSmsRedirectReceiveSms3() throws ParseException {
// Send restcomm an sms.
final String proxy = phone.getStackAddress() + ":" + restcommPort + ";lr/udp";
final String to = "sip:2001@" + restcommContact;
final String body = "Hello, waiting your response!";
final SipCall call = phone.createSipCall();
call.initiateOutgoingMessage(to, proxy, body);
assertLastOperationSuccess(call);
// Wait for a response sms.
phone.setLoopback(true);
phone.listenRequestMessage();
assertTrue(call.waitForMessage(60 * 1000));
call.sendMessageResponse(202, "Accepted", -1);
final List<String> messages = call.getAllReceivedMessagesContent();
assertTrue(messages.size() > 0);
assertTrue(messages.get(0).equals("Hello World!"));
}
@Test
public void testAliceEchoTest() throws ParseException {
SipURI uri = alice.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
Credential credential = new Credential("127.0.0.1", "alice", "1234");
alicePhone.addUpdateCredential(credential);
// Prepare Alice to receive call
final SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
// // Send restcomm an sms.
final String proxy = phone.getStackAddress() + ":" + restcommPort + ";lr/udp";
final String to = "sip:2002@" + restcommContact;
final String body = "Hello, waiting your response!";
final SipCall call = phone.createSipCall();
call.initiateOutgoingMessage(to, proxy, body);
// Wait for a response sms.
alicePhone.setLoopback(true);
aliceCall.listenForMessage();
assertTrue(aliceCall.waitForMessage(5000));
assertTrue(aliceCall.sendMessageResponse(202, "Alice-Accepted", -1));
String messageBody = new String(aliceCall.getLastReceivedMessageRequest().getRawContent());
assertTrue(messageBody.equals("Hello World!"));
aliceCall.initiateOutgoingMessage(phoneContact, null, "Its great to hear from you!");
assertTrue(aliceCall.waitForAuthorisation(5000));
call.listenForMessage();
assertTrue(call.waitForMessage(6 * 1000));
call.sendMessageResponse(202, "Accepted", -1);
final List<String> messages = call.getAllReceivedMessagesContent();
assertTrue(messages.size() > 0);
assertTrue(messages.get(0).equals("Its great to hear from you!"));
}
private String smsRcml = "<Response><Sms to=\"alice\" from=\"restcomm\">Hello World!</Sms></Response>";
@Test
@Category(value={FeatureAltTests.class})
public void testSmsWithCustomHeaders() throws ParseException {
stubFor(get(urlPathEqualTo("/rcml"))
.withQueryParam("SipHeader_X-MyCustom-Header1", containing("Value1"))
.withQueryParam("SipHeader_X-MyCustom-Header2", containing("Value2"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(smsRcml)));
SipURI uri = alice.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
Credential credential = new Credential("127.0.0.1", "alice", "1234");
alicePhone.addUpdateCredential(credential);
// Prepare Alice to receive call
final SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
// // Send restcomm an sms.
final String proxy = phone.getStackAddress() + ":" + restcommPort + ";lr/udp";
final String to = "sip:2003@" + restcommContact;
final String body = "Hello, waiting your response!";
final SipCall call = phone.createSipCall();
ArrayList<Header> additionalHeaders = new ArrayList<Header>();
additionalHeaders.add(phone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header1", "Value1"));
additionalHeaders.add(phone.getParent().getHeaderFactory().createHeader("X-MyCustom-Header2", "Value2"));
call.initiateOutgoingMessage(phoneContact, to, proxy, additionalHeaders, null, body);
// call.initiateOutgoingMessage(to, proxy, body);
// Wait for a response sms.
alicePhone.setLoopback(true);
aliceCall.listenForMessage();
assertTrue(aliceCall.waitForMessage(5000));
assertTrue(aliceCall.sendMessageResponse(202, "Alice-Accepted", -1));
String messageBody = new String(aliceCall.getLastReceivedMessageRequest().getRawContent());
assertTrue(messageBody.equals("Hello World!"));
aliceCall.initiateOutgoingMessage(phoneContact, null, "Its great to hear from you!");
assertTrue(aliceCall.waitForAuthorisation(5000));
call.listenForMessage();
assertTrue(call.waitForMessage(6 * 1000));
call.sendMessageResponse(202, "Accepted", -1);
final List<String> messages = call.getAllReceivedMessagesContent();
assertTrue(messages.size() > 0);
assertTrue(messages.get(0).equals("Its great to hear from you!"));
}
@Test
@Category(value={FeatureExpTests.class})
public void sendMessageUsingValidContentType() throws ParseException, InterruptedException {
final String proxy = phone.getStackAddress() + ":" + restcommPort + ";lr/udp";
final String to = "sip:+12223334450@" + restcommContact;
final String body = "VALID-CONTENT-TYPE";
final SipCall call = phone.createSipCall();
gov.nist.javax.sip.header.ContentType header = new gov.nist.javax.sip.header.ContentType();
header.setContentType("text");
header.setContentSubType("plain;charset=UTF-8");
ArrayList<Header> replaceHeaders = new ArrayList<Header>();
replaceHeaders.add(header);
call.initiateOutgoingMessage(null, to, proxy, new ArrayList<Header>(), replaceHeaders, body);
assertLastOperationSuccess(call);
Thread.sleep(1000);
// Verify if message was properly registered
JsonArray array = SmsEndpointTool.getInstance().getSmsList(deploymentUrl.toString(), adminAccountSid, adminAuthToken);
assertNotNull(array);
boolean found = false;
for (int i = 0; i < array.size(); i++) {
if (((JsonObject) array.get(i)).get("body").getAsString().equals(body)) {
found = true;
break;
}
}
assertTrue(found);
}
@Test
@Category(value={FeatureExpTests.class})
public void sendMessageUsingInvalidContentType() throws ParseException {
final String proxy = phone.getStackAddress() + ":" + restcommPort + ";lr/udp";
final String to = "sip:+12223334450@" + restcommContact;
final String body = "INVALID-CONTENT-TYPE-COMPOSING";
final SipCall call = phone.createSipCall();
gov.nist.javax.sip.header.ContentType header = new gov.nist.javax.sip.header.ContentType();
header.setContentType("application");
header.setContentSubType("im-iscomposing+xml");
ArrayList<Header> replaceHeaders = new ArrayList<Header>();
replaceHeaders.add(header);
call.initiateOutgoingMessage(null, to, proxy, new ArrayList<Header>(), replaceHeaders, body);
assertLastOperationSuccess(call);
assertTrue(call.waitOutgoingMessageResponse(5000));
assertTrue(call.getLastReceivedResponse().getStatusCode() == 406);
// Verify if message was properly discarded
JsonArray array = SmsEndpointTool.getInstance().getSmsList(deploymentUrl.toString(), adminAccountSid, adminAuthToken);
boolean found = false;
for (int i = 0; i < array.size(); i++) {
if (((JsonObject) array.get(i)).get("body").getAsString().equals(body)) {
found = true;
break;
}
}
assertFalse(found);
}
@Test
@Category(value={FeatureExpTests.class})
public void sendMessageUsingInvalidContentType2() throws ParseException {
final String proxy = phone.getStackAddress() + ":" + restcommPort + ";lr/udp";
final String to = "sip:+12223334450@" + restcommContact;
final String body = "INVALID-CONTENT-TYPE-HTML";
final SipCall call = phone.createSipCall();
gov.nist.javax.sip.header.ContentType header = new gov.nist.javax.sip.header.ContentType();
header.setContentType("text");
header.setContentSubType("html;charset=UTF-8");
ArrayList<Header> replaceHeaders = new ArrayList<Header>();
replaceHeaders.add(header);
call.initiateOutgoingMessage(null, to, proxy, new ArrayList<Header>(), replaceHeaders, body);
assertLastOperationSuccess(call);
assertTrue(call.waitOutgoingMessageResponse(5000));
assertTrue(call.getLastReceivedResponse().getStatusCode() == 406);
// Verify if message was properly discarded
JsonArray array = SmsEndpointTool.getInstance().getSmsList(deploymentUrl.toString(), adminAccountSid, adminAuthToken);
boolean found = false;
for (int i = 0; i < array.size(); i++) {
if (((JsonObject) array.get(i)).get("body").getAsString().equals(body)) {
found = true;
break;
}
}
assertFalse(found);
}
@Deployment(name = "SmsSessionTest", managed = true, testable = false)
public static WebArchive createWebArchive() {
reconfigurePorts();
Map<String, String> webInfResources = new HashMap();
webInfResources.put("restcomm_SmsTest.xml", "conf/restcomm.xml");
webInfResources.put("restcomm.script_SmsTest", "data/hsql/restcomm.script");
webInfResources.put("sip.xml", "sip.xml");
webInfResources.put("web.xml", "web.xml");
webInfResources.put("akka_application.conf", "classes/application.conf");
Map<String, String> replacements = new HashMap();
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("8090", String.valueOf(mockPort));
replacements.put("5080", String.valueOf(restcommPort));
replacements.put("5091", String.valueOf(phonePort));
replacements.put("5092", String.valueOf(alicePort));
List<String> resources = new ArrayList(Arrays.asList(
"entry.xml",
"sms.xml",
"sms_to_alice.xml"
));
return WebArchiveUtil.createWebArchiveNoGw(webInfResources,
resources,
replacements);
}
}
| 18,120 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsEndpointTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/sms/SmsEndpointTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite.sms;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sip.address.SipURI;
import javax.sip.message.Request;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.FeatureAltTests;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.UnstableTests;
import org.restcomm.connect.commons.annotations.WithInSecsTests;
import org.restcomm.connect.testsuite.NetworkPortAssigner;
import org.restcomm.connect.testsuite.WebArchiveUtil;
import com.google.gson.JsonObject;
import gov.nist.javax.sip.header.SIPHeader;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInSecsTests.class, ParallelClassTests.class})
public class SmsEndpointTest {
private static Logger logger = Logger.getLogger(SmsEndpointTest.class);
private static final String version = Version.getVersion();
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
private static SipStackTool tool1;
private SipStack bobSipStack;
private SipPhone bobPhone;
private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String bobContact = "sip:[email protected]:" + bobPort;
private static SipStackTool tool2;
private SipStack aliceSipStack;
private SipPhone alicePhone;
private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String aliceContact = "sip:[email protected]:" + alicePort;
private static SipStackTool tool3;
private SipStack aliceSipStackOrg2;
private SipPhone alicePhoneOrg2;
private static String alicePort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String aliceContactOrg2 = "sip:[email protected]:" + alicePort2;
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
private String adminAccountSidOrg2 = "ACae6e420f425248d6a26948c17a9e2acg";
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("SmsTest1");
tool2 = new SipStackTool("SmsTest2");
tool3 = new SipStackTool("SmsTest3");
}
public static void reconfigurePorts() {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact);
bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact);
aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact);
alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact);
aliceSipStackOrg2 = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort2, restcommContact);
alicePhoneOrg2 = aliceSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContactOrg2);
}
@After
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
}
if (bobSipStack != null) {
bobSipStack.dispose();
}
if (alicePhone != null) {
alicePhone.dispose();
}
if (aliceSipStack != null) {
aliceSipStack.dispose();
}
if (alicePhoneOrg2 != null) {
alicePhoneOrg2.dispose();
}
if (aliceSipStackOrg2 != null) {
aliceSipStackOrg2.dispose();
}
}
@Test
public void sendSmsTest() {
SipCall bobCall = bobPhone.createSipCall();
bobCall.listenForMessage();
String from = "+15126002188";
String to = "1213";
String body = "Hello Bob!";
JsonObject callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid,
adminAuthToken, from, to, body, null);
assertNotNull(callResult);
// bobPhone.setLoopback(true);
assertTrue(bobCall.waitForMessage(10000));
Request messageRequest = bobCall.getLastReceivedMessageRequest();
assertTrue(bobCall.sendMessageResponse(202, "Accepted", 3600));
String messageReceived = new String(messageRequest.getRawContent());
assertTrue(messageReceived.equals(body));
}
@Test
@Category(value={FeatureAltTests.class})
public void sendSmsTestToClientAlice() throws ParseException {
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
String from = "+15126002188";
String to = "client:alice";
String body = "Hello Alice!";
JsonObject callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid,
adminAuthToken, from, to, body, null);
assertNotNull(callResult);
// bobPhone.setLoopback(true);
assertTrue(aliceCall.waitForMessage(10000));
Request messageRequest = aliceCall.getLastReceivedMessageRequest();
assertTrue(aliceCall.sendMessageResponse(202, "Accepted", 3600));
String messageReceived = new String(messageRequest.getRawContent());
assertTrue(messageReceived.equals(body));
}
/**
* Try to send sms to alice:
* alice exist in both org1 and org2
* make sure only proper alice gets the msg (the one that exists in source account's organization)
* @throws ParseException
*/
@Test
@Category(value={FeatureAltTests.class, UnstableTests.class})
public void sendSmsTestToClientExistingInDifferentOrganizations() throws ParseException {
// Prepare alice org2 phone to receive call
SipURI uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:" + alicePort2, 3600, 3600));
SipCall aliceCallOrg2 = alicePhoneOrg2.createSipCall();
aliceCallOrg2.listenForMessage();
// Prepare alice org1 phone to receive call
SipURI urialiceSipStack = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(urialiceSipStack, "alice", "1234", aliceContact, 3600, 3600));
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
String from = "+15126002188";
String to = "client:alice";
String body = "Hello Alice!";
//send msg from org2 account
JsonObject msgResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSidOrg2,
adminAuthToken, from, to, body, null);
assertNotNull(msgResult);
assertTrue(aliceCallOrg2.waitForMessage(10000));
Request messageRequest = aliceCallOrg2.getLastReceivedMessageRequest();
assertTrue(aliceCallOrg2.sendMessageResponse(202, "Accepted", 3600));
String messageReceived = new String(messageRequest.getRawContent());
assertTrue(messageReceived.equals(body));
assertTrue(!aliceCall.waitForMessage(10000));
}
@Test
public void sendSmsTestToAlice() throws ParseException {
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
String from = "+15126002188";
String to = "alice";
String body = "Hello Alice!";
JsonObject callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid,
adminAuthToken, from, to, body, null);
assertNotNull(callResult);
// bobPhone.setLoopback(true);
assertTrue(aliceCall.waitForMessage(10000));
Request messageRequest = aliceCall.getLastReceivedMessageRequest();
assertTrue(aliceCall.sendMessageResponse(202, "Accepted", 3600));
String messageReceived = new String(messageRequest.getRawContent());
assertTrue(messageReceived.equals(body));
}
@Test
@Category(value={FeatureAltTests.class})
public void sendSmsTestGSMEncoding() {
SipCall bobCall = bobPhone.createSipCall();
bobCall.listenForMessage();
String from = "+15126002188";
String to = "1213";
String body = "Hello Bob!";
String encoding = "GSM";
JsonObject callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid,
adminAuthToken, from, to, body, null, encoding);
assertNotNull(callResult);
assertTrue(bobCall.waitForMessage(10000));
Request messageRequest = bobCall.getLastReceivedMessageRequest();
assertTrue(bobCall.sendMessageResponse(202, "Accepted", 3600));
String messageReceived = new String(messageRequest.getRawContent());
assertTrue(messageReceived.equals(body));
}
@Test
@Category(value={FeatureAltTests.class})
public void sendSmsTestUCS2Encoding() {
SipCall bobCall = bobPhone.createSipCall();
bobCall.listenForMessage();
String from = "+15126002188";
String to = "1213";
String body = " ̰Heo llb!Bo ͤb!";
String encoding = "UCS-2";
JsonObject callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid,
adminAuthToken, from, to, body, null, encoding);
assertNotNull(callResult);
assertTrue(bobCall.waitForMessage(10000));
Request messageRequest = bobCall.getLastReceivedMessageRequest();
assertTrue(bobCall.sendMessageResponse(202, "Accepted", 3600));
String messageReceived = new String(messageRequest.getRawContent());
System.out.println("Body: " + body);
System.out.println("messageReceived: " + messageReceived);
assertTrue(messageReceived.equals(body));
}
@Test
@Category(value={FeatureAltTests.class})
public void sendSmsTestWithCustomHeaders() {
String myFirstHeaderName = "X-Custom-Header-1";
String myFirstHeaderValue = "X Custom Header Value 1";
String mySecondHeaderName = "X-Custom-Header-2";
String mySecondHeaderValue = "X Custom Header Value 2";
SipCall bobCall = bobPhone.createSipCall();
bobCall.listenForMessage();
String from = "+15126002188";
String to = "1213";
String body = "Hello Bob! This time I sent you the message and some additional headers.";
HashMap<String, String> additionalHeaders = new HashMap<String, String>();
additionalHeaders.put(myFirstHeaderName, myFirstHeaderValue);
additionalHeaders.put(mySecondHeaderName, mySecondHeaderValue);
JsonObject callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid,
adminAuthToken, from, to, body, additionalHeaders);
assertNotNull(callResult);
assertTrue(bobCall.waitForMessage(10000));
Request messageRequest = bobCall.getLastReceivedMessageRequest();
assertTrue(bobCall.sendMessageResponse(202, "Accepted", 3600));
String messageReceived = new String(messageRequest.getRawContent());
assertTrue(messageReceived.equals(body));
SIPHeader myFirstHeader = (SIPHeader)messageRequest.getHeader(myFirstHeaderName);
assertTrue(myFirstHeader != null);
assertTrue(myFirstHeader.getValue().equalsIgnoreCase(myFirstHeaderValue));
SIPHeader mySecondHeader = (SIPHeader)messageRequest.getHeader(mySecondHeaderName);
assertTrue(mySecondHeader != null);
assertTrue(mySecondHeader.getHeaderValue().equalsIgnoreCase(mySecondHeaderValue));
}
@Deployment(name = "LiveCallModificationTest", managed = true, testable = false)
public static WebArchive createWebArchiveNoGw() {
logger.info("Packaging Test App");
reconfigurePorts();
Map<String, String> webInfResources = new HashMap();
webInfResources.put("restcomm_for_SMSEndpointTest.xml", "conf/restcomm.xml");
webInfResources.put("restcomm.script_dialTest", "data/hsql/restcomm.script");
//webInfResources.put("restcomm.script_SmsTest", "data/hsql/restcomm.script");
webInfResources.put("akka_application.conf", "classes/application.conf");
webInfResources.put("sip.xml", "sip.xml");
webInfResources.put("web.xml", "web.xml");
Map<String, String> replacements = new HashMap();
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("5080", String.valueOf(restcommPort));
replacements.put("5090", String.valueOf(bobPort));
replacements.put("5091", String.valueOf(alicePort));
replacements.put("5092", String.valueOf(alicePort2));
List<String> resources = new ArrayList(Arrays.asList(
));
return WebArchiveUtil.createWebArchiveNoGw(webInfResources,
resources,
replacements);
}
}
| 16,180 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsRcmlServlet.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/sms/SmsRcmlServlet.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite.sms;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This is a helper class to serve RCML request and also return any custom headers
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
public class SmsRcmlServlet extends HttpServlet{
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
if (line.contains("SipHeader_X-")){
String[] parameters = line.split("&");
for (String parameter: parameters) {
if (parameter.startsWith("SipHeader_X-")){
String headerName = parameter.split("=")[0].replaceFirst("SipHeader_X-", "X-");
String headerValue = URLDecoder.decode(parameter.split("=")[1], "UTF-8");
resp.setHeader(headerName, headerValue);
}
}
}
} catch (Exception e) { /*report an error*/ }
// while (headers.hasMoreElements()) {
// String name = headers.nextElement();
// if (name.startsWith("X-")) {
// resp.setHeader(name, req.getHeader(name));
// }
// }
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<Response>");
out.println("<Sms to=\"1313\" from=\"+12223334499\">Hello World!</Sms>");
out.println("</Response>");
out.flush();
}
private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
Enumeration<String> headers = req.getHeaderNames();
// <?xml version="1.0" encoding="UTF-8"?>
// <Response>
// <Sms to="1313" from="+12223334499">Hello World!</Sms>
// </Response>
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
while (headers.hasMoreElements()) {
String name = headers.nextElement();
if (name.startsWith("X-")) {
resp.setHeader(name, req.getHeader(name));
}
}
out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
out.println("<Response>");
out.println("<Sms to=\"1313\" from=\"+12223334499\">Hello World!</Sms>");
out.println("</Response>");
out.flush();
}
}
| 3,983 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/sms/SmsTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite.sms;
import gov.nist.javax.sip.header.SIPHeader;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.Credential;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.FeatureAltTests;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.UnstableTests;
import org.restcomm.connect.commons.annotations.WithInSecsTests;
import org.restcomm.connect.testsuite.NetworkPortAssigner;
import org.restcomm.connect.testsuite.WebArchiveUtil;
import javax.sip.address.SipURI;
import javax.sip.header.Header;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static javax.servlet.sip.SipServletResponse.SC_FORBIDDEN;
import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInSecsTests.class, ParallelClassTests.class})
public class SmsTest {
private final static Logger logger = Logger.getLogger(SmsTest.class);
private static final String version = Version.getVersion();
private static final byte[] bytes = new byte[]{118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53,
53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46,
48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49,
13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65,
86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10};
private static final String body = new String(bytes);
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
private static SipStackTool tool1;
private static SipStackTool tool2;
private static SipStackTool tool3;
private static SipStackTool tool4;
private static SipStackTool tool5;
private static SipStackTool tool6;
private static SipStackTool tool7;
private static SipStackTool tool8;
private static SipStackTool tool9;
private static SipStackTool tool10;
private SipStack bobSipStack;
private SipPhone bobPhone;
private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String bobContact = "sip:[email protected]:" + bobPort;
private SipStack aliceSipStack;
private SipPhone alicePhone;
private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String aliceContact = "sip:[email protected]:" + alicePort;
private SipStack georgeSipStack;
private SipPhone georgePhone;
private static String georgePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String georgeContact = "sip:[email protected]:" + georgePort;
private SipStack fotiniSipStack;
private SipPhone fotiniPhone;
private static String fotiniPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String fotiniContact = "sip:[email protected]:" + fotiniPort;
private SipStack aliceSipStackOrg2;
private SipPhone alicePhoneOrg2;
private static String alicePort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String aliceContactOrg2 = "sip:[email protected]";
private SipStack bobSipStackOrg2;
private SipPhone bobPhoneOrg2;
private static String bobPort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String bobContactOrg2 = "sip:[email protected]";
private SipStack georgeSipStackOrg2;
private SipPhone georgePhoneOrg2;
private static String georgePort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String georgeContactOrg2 = "sip:[email protected]";
private SipStack fotiniSipStackOrg2;
private SipPhone fotiniPhoneOrg2;
private static String fotiniPort2 = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String fotiniContactOrg2 = "sip:[email protected]";
private SipStack closedSipStack;
private SipPhone closedPhone;
private static String closedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String closedContact = "sip:[email protected]:" + closedPort;
private SipStack suspendedSipStack;
private SipPhone suspendedPhone;
private static String suspendedPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String suspendedContact = "sip:[email protected]:" + suspendedPort;
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
private static String dialSendSMS = "sip:+12223334444@" + restcommContact;
private static String dialSendSMS2 = "sip:+12223334445@" + restcommContact;
private static String dialSendSMS2_Greek = "sip:+12223334447@" + restcommContact;
private static String dialSendSMS2_Greek_Huge = "sip:+12223334448@" + restcommContact;
private static String dialSendSMS3 = "sip:+12223334446@" + restcommContact;
private static String dialSendSMSwithCustomHeaders = "sip:+12223334449@" + restcommContact;
private static String dialSendSMS2Org2 = "sip:[email protected]";
private String greekHugeMessage = "Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα "
+ "Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα "
+ "Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα "
+ "Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα Καλημερα "
+ "Καλημερα Καλημερα Καλημερα";
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("SmsTest1");
tool2 = new SipStackTool("SmsTest2");
tool3 = new SipStackTool("SmsTest3");
tool4 = new SipStackTool("SmsTest4");
tool5 = new SipStackTool("SmsTest5");
tool6 = new SipStackTool("SmsTest6");
tool7 = new SipStackTool("SmsTest7");
tool8 = new SipStackTool("SmsTest8");
tool9 = new SipStackTool("SmsTest9");
tool10 = new SipStackTool("SmsTest10");
}
public static void reconfigurePorts() {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
dialSendSMS = "sip:+12223334444@" + restcommContact;
dialSendSMS2 = "sip:+12223334445@" + restcommContact;
dialSendSMS2_Greek = "sip:+12223334447@" + restcommContact;
dialSendSMS2_Greek_Huge = "sip:+12223334448@" + restcommContact;
dialSendSMS3 = "sip:+12223334446@" + restcommContact;
dialSendSMSwithCustomHeaders = "sip:+12223334449@" + restcommContact;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact);
bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact);
aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact);
alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact);
georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort, restcommContact);
georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContact);
fotiniSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", fotiniPort, restcommContact);
fotiniPhone = fotiniSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, fotiniContact);
aliceSipStackOrg2 = tool5.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort2, restcommContact);
alicePhoneOrg2 = aliceSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContactOrg2);
bobSipStackOrg2 = tool6.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort2, restcommContact);
bobPhoneOrg2 = bobSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContactOrg2);
georgeSipStackOrg2 = tool7.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", georgePort2, restcommContact);
georgePhoneOrg2 = georgeSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, georgeContactOrg2);
fotiniSipStackOrg2 = tool8.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", fotiniPort2, restcommContact);
fotiniPhoneOrg2 = fotiniSipStackOrg2.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, fotiniContactOrg2);
closedSipStack = tool9.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", closedPort, restcommContact);
closedPhone = closedSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, closedContact);
suspendedSipStack = tool10.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", suspendedPort, restcommContact);
suspendedPhone = suspendedSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, suspendedContact);
}
@After
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
}
if (bobSipStack != null) {
bobSipStack.dispose();
}
if (aliceSipStack != null) {
aliceSipStack.dispose();
}
if (alicePhone != null) {
alicePhone.dispose();
}
if (georgeSipStack != null) {
georgeSipStack.dispose();
}
if (georgePhone != null) {
georgePhone.dispose();
}
if (fotiniSipStack != null) {
fotiniSipStack.dispose();
}
if (fotiniPhone != null) {
fotiniPhone.dispose();
}
if (georgeSipStackOrg2 != null) {
georgeSipStackOrg2.dispose();
}
if (georgePhoneOrg2 != null) {
georgePhoneOrg2.dispose();
}
if (fotiniSipStackOrg2 != null) {
fotiniSipStackOrg2.dispose();
}
if (fotiniPhoneOrg2 != null) {
fotiniPhoneOrg2.dispose();
}
if (bobPhoneOrg2 != null) {
bobPhoneOrg2.dispose();
}
if (bobSipStackOrg2 != null) {
bobSipStackOrg2.dispose();
}
if (aliceSipStackOrg2 != null) {
aliceSipStackOrg2.dispose();
}
if (alicePhoneOrg2 != null) {
alicePhoneOrg2.dispose();
}
if (closedPhone != null) {
closedPhone.dispose();
}
if (closedSipStack != null) {
closedSipStack.dispose();
}
if (suspendedPhone != null) {
suspendedPhone.dispose();
}
if (suspendedSipStack != null) {
suspendedSipStack.dispose();
}
Thread.sleep(1000);
}
@Test
public void testAliceActsAsSMSGatewayAndReceivesSMS() throws ParseException {
// Phone2 register as alice
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, dialSendSMS, null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.TRYING || response == Response.RINGING);
if (response == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
bobCall.sendInviteOkAck();
bobCall.listenForDisconnect();
assertTrue(aliceCall.waitForMessage(5 * 1000));
String msgReceived = new String(aliceCall.getLastReceivedMessageRequest().getRawContent());
assertTrue("Hello World!".equals(msgReceived));
aliceCall.sendMessageResponse(200, "OK-From-Alice", 3600);
assertTrue(bobCall.waitForDisconnect(40 * 1000));
assertTrue(bobCall.respondToDisconnect());
try {
Thread.sleep(10 * 1000);
} catch (final InterruptedException exception) {
exception.printStackTrace();
}
}
@Test
public void TestIncomingSmsSendToClientAlice() throws ParseException, InterruptedException {
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingMessage(dialSendSMS2, null, "Hello from Bob!");
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.ACCEPTED);
//Restcomm receives the SMS message from Bob, matches the DID with an RCML application, and executes it.
//The new RCML application sends an SMS to Alice with body "Hello World!"
assertTrue(aliceCall.waitForMessage(5 * 1000));
String msgReceived = new String(aliceCall.getLastReceivedMessageRequest().getRawContent());
assertTrue("Hello World!".equals(msgReceived));
aliceCall.sendMessageResponse(200, "OK-From-Alice", 3600);
}
@Test
public void TestIncomingSmsSendToClientAliceOfOrganization2() throws ParseException, InterruptedException {
SipURI uri = aliceSipStackOrg2.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhoneOrg2.register(uri, "alice", "1234", "sip:[email protected]:" + alicePort2, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCallOrg2 = alicePhoneOrg2.createSipCall();
aliceCallOrg2.listenForMessage();
// Create outgoing call with first phone
final SipCall bobCallOrg2 = bobPhoneOrg2.createSipCall();
bobCallOrg2.initiateOutgoingMessage(dialSendSMS2Org2, null, "Hello from Bob!");
assertLastOperationSuccess(bobCallOrg2);
assertTrue(bobCallOrg2.waitOutgoingCallResponse(5 * 1000));
final int response = bobCallOrg2.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.ACCEPTED);
//Restcomm receives the SMS message from Bob, matches the DID with an RCML application, and executes it.
//The new RCML application sends an SMS to Alice with body "Hello World!"
assertTrue(aliceCallOrg2.waitForMessage(5 * 1000));
String msgReceived = new String(aliceCallOrg2.getLastReceivedMessageRequest().getRawContent());
assertTrue("Hello World!".equals(msgReceived));
aliceCallOrg2.sendMessageResponse(200, "OK-From-Alice", 3600);
}
@Test
@Category(value={FeatureAltTests.class})
public void TestIncomingSmsSendToClientAliceGreekHugeMessage() throws ParseException, InterruptedException {
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingMessage(dialSendSMS2_Greek_Huge, null, greekHugeMessage);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.ACCEPTED);
//Restcomm receives the SMS message from Bob, matches the DID with an RCML application, and executes it.
//The new RCML application sends an SMS to Alice with body "Hello World!"
assertTrue(aliceCall.waitForMessage(5 * 1000));
String msgReceived = new String(aliceCall.getLastReceivedMessageRequest().getRawContent());
assertTrue(greekHugeMessage.equals(msgReceived));
aliceCall.sendMessageResponse(200, "OK-From-Alice", 3600);
}
@Test
@Category(value={FeatureAltTests.class})
public void TestIncomingSmsSendToClientAliceGreek() throws ParseException, InterruptedException {
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingMessage(dialSendSMS2_Greek, null, "Καλώς τον Γιώργο!");
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.ACCEPTED);
//Restcomm receives the SMS message from Bob, matches the DID with an RCML application, and executes it.
//The new RCML application sends an SMS to Alice with body "Hello World!"
assertTrue(aliceCall.waitForMessage(5 * 1000));
String msgReceived = new String(aliceCall.getLastReceivedMessageRequest().getRawContent());
assertTrue("Καλώς τον Γιώργο!".equals(msgReceived));
aliceCall.sendMessageResponse(200, "OK-From-Alice", 3600);
}
@Test
public void TestIncomingSmsSendToNumber1313() throws ParseException, InterruptedException {
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:" + alicePort, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingMessage(dialSendSMS3, null, "Hello from Bob!");
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.ACCEPTED);
//Restcomm receives the SMS message from Bob, matches the DID with an RCML application, and executes it.
//The new RCML application sends an SMS to Alice with body "Hello World!"
assertTrue(aliceCall.waitForMessage(5 * 1000));
String msgReceived = new String(aliceCall.getLastReceivedMessageRequest().getRawContent());
assertTrue("Hello World!".equals(msgReceived));
aliceCall.sendMessageResponse(200, "OK-From-Alice", 3600);
}
@Test
@Category(value={FeatureAltTests.class})
public void TestIncomingSmsSendToNumber1313WithCustomHeaders() throws ParseException, InterruptedException {
String myFirstHeaderName = "X-Custom-Header-1";
String myFirstHeaderValue = "X Custom Header Value 1";
String mySecondHeaderName = "X-Custom-Header-2";
String mySecondHeaderValue = "X Custom Header Value 2";
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:" + alicePort, 3600, 3600));
// Prepare second phone to receive call
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
ArrayList<Header> additionalHeaders = new ArrayList<Header>();
Header header1 = bobSipStack.getHeaderFactory().createHeader(myFirstHeaderName, myFirstHeaderValue);
Header header2 = bobSipStack.getHeaderFactory().createHeader(mySecondHeaderName, mySecondHeaderValue);
additionalHeaders.add(header1);
additionalHeaders.add(header2);
bobCall.initiateOutgoingMessage(bobContact, dialSendSMSwithCustomHeaders, null, additionalHeaders, null, "Hello from Bob!");
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.ACCEPTED);
//Restcomm receives the SMS message from Bob, matches the DID with an RCML application, and executes it.
//The new RCML application sends an SMS to Alice with body "Hello World!"
assertTrue(aliceCall.waitForMessage(5 * 1000));
Request receivedRequest = aliceCall.getLastReceivedMessageRequest();
String msgReceived = new String(receivedRequest.getRawContent());
assertTrue("Hello World!".equals(msgReceived));
SIPHeader myFirstHeader = (SIPHeader) receivedRequest.getHeader(myFirstHeaderName);
assertTrue(myFirstHeader != null);
assertTrue(myFirstHeader.getValue().equalsIgnoreCase(myFirstHeaderValue));
SIPHeader mySecondHeader = (SIPHeader) receivedRequest.getHeader(mySecondHeaderName);
assertTrue(mySecondHeader != null);
assertTrue(mySecondHeader.getHeaderValue().equalsIgnoreCase(mySecondHeaderValue));
aliceCall.sendMessageResponse(200, "OK-From-Alice", 3600);
}
@Test
@Category(UnstableTests.class)
public void testP2PSendSMS_GeorgeClient_ToFotiniClient() throws ParseException {
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
//Register George phone
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
Credential aliceCredentials = new Credential("127.0.0.1", "alice", "1234");
alicePhone.addUpdateCredential(aliceCredentials);
//Register Fotini phone
assertTrue(fotiniPhone.register(uri, "fotini", "1234", fotiniContact, 3600, 3600));
Credential fotiniCredentials = new Credential("127.0.0.1", "fotini", "1234");
fotiniPhone.addUpdateCredential(fotiniCredentials);
//Prepare Fotini to receive message
SipCall fotiniCall = fotiniPhone.createSipCall();
fotiniCall.listenForMessage();
//Prepare George to send message
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.initiateOutgoingMessage(aliceContact, "sip:fotini@" + restcommContact, null, null, null, greekHugeMessage);
assertLastOperationSuccess(aliceCall);
aliceCall.waitForAuthorisation(30 * 1000);
assertTrue(aliceCall.waitOutgoingMessageResponse(3000));
assertEquals(Response.TRYING, aliceCall.getLastReceivedResponse().getStatusCode());
assertTrue(fotiniCall.waitForMessage(30 * 1000));
assertTrue(fotiniCall.sendMessageResponse(200, "OK-Fotini-Mesasge-Receieved", 1800));
assertTrue(aliceCall.waitOutgoingMessageResponse(3000));
assertTrue(aliceCall.getLastReceivedResponse().getStatusCode() == Response.OK);
List<String> msgsFromGeorge = fotiniCall.getAllReceivedMessagesContent();
assertTrue(msgsFromGeorge.size() > 0);
assertTrue(msgsFromGeorge.get(0).equals(greekHugeMessage));
}
@Test
@Category(UnstableTests.class)
public void testP2PSendSMS_GeorgeClient_ToFotiniClientOrg2() throws ParseException {
SipURI uri = georgeSipStackOrg2.getAddressFactory().createSipURI(null, restcommContact);
//Register George phone
assertTrue(georgePhoneOrg2.register(uri, "george", "1234", "sip:[email protected]:" + georgePort2, 3600, 3600));
Credential georgeCredentialsOrg2 = new Credential("org2.restcomm.com", "george", "1234");
georgePhoneOrg2.addUpdateCredential(georgeCredentialsOrg2);
//Register Fotini phone
assertTrue(fotiniPhoneOrg2.register(uri, "fotini", "1234", "sip:[email protected]:" + fotiniPort2, 3600, 3600));
Credential fotiniCredentials = new Credential("org2.restcomm.com", "fotini", "1234");
fotiniPhoneOrg2.addUpdateCredential(fotiniCredentials);
//Prepare Fotini to receive message
SipCall fotiniCallOrg2 = fotiniPhoneOrg2.createSipCall();
fotiniCallOrg2.listenForMessage();
//Prepare George to send message
SipCall georgeCallOrg2 = georgePhoneOrg2.createSipCall();
georgeCallOrg2.initiateOutgoingMessage(georgeContactOrg2, fotiniContactOrg2, null, null, null, greekHugeMessage);
assertLastOperationSuccess(georgeCallOrg2);
georgeCallOrg2.waitForAuthorisation(30 * 1000);
assertTrue(georgeCallOrg2.waitOutgoingMessageResponse(3000));
assertTrue(georgeCallOrg2.getLastReceivedResponse().getStatusCode() == Response.TRYING);
assertTrue(fotiniCallOrg2.waitForMessage(30 * 1000));
assertTrue(fotiniCallOrg2.sendMessageResponse(200, "OK-Fotini-Mesasge-Receieved", 1800));
assertTrue(georgeCallOrg2.waitOutgoingMessageResponse(3000));
assertTrue(georgeCallOrg2.getLastReceivedResponse().getStatusCode() == Response.OK);
List<String> msgsFromGeorge = fotiniCallOrg2.getAllReceivedMessagesContent();
assertTrue(msgsFromGeorge.size() > 0);
assertTrue(msgsFromGeorge.get(0).equals(greekHugeMessage));
}
@Test
@Category(value={FeatureAltTests.class})
public void testP2PSendSMS_GeorgeClient_ToFotiniClient_EmptyContent() throws ParseException {
SipURI uri = georgeSipStack.getAddressFactory().createSipURI(null, restcommContact);
//Register George phone
assertTrue(georgePhone.register(uri, "george", "1234", georgeContact, 3600, 3600));
Credential georgeCredentials = new Credential("127.0.0.1", "george", "1234");
georgePhone.addUpdateCredential(georgeCredentials);
//Register Fotini phone
assertTrue(fotiniPhone.register(uri, "fotini", "1234", "sip:fotini@" + restcommContact, 3600, 3600));
Credential fotiniCredentials = new Credential("127.0.0.1", "fotini", "1234");
fotiniPhone.addUpdateCredential(fotiniCredentials);
//Prepare Fotini to receive message
SipCall fotiniCall = fotiniPhone.createSipCall();
fotiniCall.listenForMessage();
//Prepare George to send message
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.initiateOutgoingMessage(georgeContact, fotiniContact, null, null, null, null);
assertLastOperationSuccess(georgeCall);
assertTrue(georgeCall.waitOutgoingMessageResponse(5000));
assertTrue(georgeCall.getLastReceivedResponse().getStatusCode() == Response.NOT_ACCEPTABLE);
}
@Test
public void TestIncomingSmsSendToNumberOfClosedAccount() throws ParseException, InterruptedException {
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingMessage("sip:2222@" + restcommContact, null, "Hello from Bob!");
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertEquals(SC_FORBIDDEN, response);
}
@Test
public void TestIncomingSmsSendToNumberOfSuspendedAccount() throws ParseException, InterruptedException {
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingMessage("sip:3333@" + restcommContact, null, "Hello from Bob!");
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertEquals(SC_FORBIDDEN, response);
}
@Deployment(name = "SmsTest", managed = true, testable = false)
public static WebArchive createWebArchiveNoGw() {
logger.info("Packaging Test App");
reconfigurePorts();
Map<String, String> webInfResources = new HashMap();
webInfResources.put("restcomm_SmsTest.xml", "conf/restcomm.xml");
webInfResources.put("restcomm.script_SmsTest", "data/hsql/restcomm.script");
webInfResources.put("sip.xml", "sip.xml");
webInfResources.put("web_for_SmsTest.xml", "web.xml");
webInfResources.put("akka_application.conf", "classes/application.conf");
Map<String, String> replacements = new HashMap();
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("5080", String.valueOf(restcommPort));
replacements.put("5090", String.valueOf(bobPort));
replacements.put("5091", String.valueOf(alicePort));
replacements.put("5092", String.valueOf(georgePort));
replacements.put("5093", String.valueOf(fotiniPort));
replacements.put("5094", String.valueOf(alicePort2));
replacements.put("5095", String.valueOf(bobPort2));
replacements.put("5096", String.valueOf(georgePort2));
replacements.put("5097", String.valueOf(fotiniPort2));
List<String> resources = new ArrayList(Arrays.asList(
"send-sms-test.xml",
"send-sms-test-greek.xml",
"send-sms-test-greek_huge.xml",
"send-sms-test2.xml",
"dial-client-entry.xml"
));
return WebArchiveUtil.createWebArchiveNoGw(webInfResources,
resources,
replacements);
}
}
| 33,906 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
SmsPushNotificationServerTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/sms/push/SmsPushNotificationServerTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite.sms.push;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import javax.sip.address.SipURI;
import javax.sip.message.Request;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.Credential;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.restcomm.connect.commons.annotations.ParallelClassTests;
import org.restcomm.connect.commons.annotations.UnstableTests;
import org.restcomm.connect.commons.annotations.WithInSecsTests;
import org.restcomm.connect.testsuite.NetworkPortAssigner;
import org.restcomm.connect.testsuite.WebArchiveUtil;
import org.restcomm.connect.testsuite.http.CreateClientsTool;
import org.restcomm.connect.testsuite.sms.SmsEndpointTool;
import com.github.tomakehurst.wiremock.http.RequestListener;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.google.gson.JsonObject;
/**
* @author [email protected] (Oleg Agafonov)
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInSecsTests.class, ParallelClassTests.class})
public class SmsPushNotificationServerTest {
private final static Logger logger = Logger.getLogger(SmsPushNotificationServerTest.class.getName());
private static final String CLIENT_PASSWORD = "qwerty1234RT";
private static int mediaPort = NetworkPortAssigner.retrieveNextPortByFile();
private static int mockPort = NetworkPortAssigner.retrieveNextPortByFile();
@Rule
public WireMockRule wireMockRule = new WireMockRule(mockPort);
@ArquillianResource
URL deploymentUrl;
private static SipStackTool tool1;
private static SipStackTool tool2;
private SipStack bobSipStack;
private SipPhone bobPhone;
private static String bobPort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String bobContact = "sip:[email protected]:" + bobPort;
private SipStack aliceSipStack;
private SipPhone alicePhone;
private static String alicePort = String.valueOf(NetworkPortAssigner.retrieveNextPortByFile());
private String aliceContact = "sip:[email protected]:" + alicePort;
private static int restcommPort = 5080;
private static int restcommHTTPPort = 8080;
private static String restcommContact = "127.0.0.1:" + restcommPort;
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("SmsPushNotificationServerTest1");
tool2 = new SipStackTool("SmsPushNotificationServerTest2");
}
public static void reconfigurePorts() {
if (System.getProperty("arquillian_sip_port") != null) {
restcommPort = Integer.valueOf(System.getProperty("arquillian_sip_port"));
restcommContact = "127.0.0.1:" + restcommPort;
}
if (System.getProperty("arquillian_http_port") != null) {
restcommHTTPPort = Integer.valueOf(System.getProperty("arquillian_http_port"));
}
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", bobPort, restcommContact);
bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, bobContact);
aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", alicePort, restcommContact);
alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, restcommPort, aliceContact);
}
@After
@SuppressWarnings("Duplicates")
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
}
if (bobSipStack != null) {
bobSipStack.dispose();
}
if (alicePhone != null) {
alicePhone.dispose();
}
if (aliceSipStack != null) {
aliceSipStack.dispose();
}
Thread.sleep(1000);
wireMockRule.resetRequests();
Thread.sleep(4000);
}
@Test
@Category(UnstableTests.class)
public void testB2BUAMessage() throws ParseException, InterruptedException, IOException {
stubFor(post(urlPathEqualTo("/api/notifications"))
.withHeader("Content-Type", matching("application/json;.*"))
.willReturn(aResponse()
.withStatus(200)));
final SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
wireMockRule.addMockServiceRequestListener(new RequestListener() {
@Override
public void requestReceived(com.github.tomakehurst.wiremock.http.Request request, com.github.tomakehurst.wiremock.http.Response response) {
if (request.getAbsoluteUrl().contains("/api/notifications") && response.getStatus() == 200) {
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
}
}
});
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
CreateClientsTool.getInstance().createClient(deploymentUrl.toString(), "bob", CLIENT_PASSWORD, null);
Credential c = new Credential("127.0.0.1", "bob", CLIENT_PASSWORD);
bobPhone.addUpdateCredential(c);
assertTrue(bobPhone.register(uri, "bob", CLIENT_PASSWORD, bobContact, 3600, 3600));
SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingMessage(bobContact, aliceContact, null, null, null, "Hello, Alice!");
assertTrue(bobCall.waitForAuthorisation(5000));
assertTrue(bobCall.waitOutgoingMessageResponse(5000));
assertTrue(aliceCall.waitForMessage(5000));
assertTrue(aliceCall.sendMessageResponse(Response.ACCEPTED, "Accepted", 3600, null));
int response;
do {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
response = bobCall.getLastReceivedResponse().getStatusCode();
} while (response == Response.TRYING);
assertTrue(response == Response.ACCEPTED);
verify(postRequestedFor(urlEqualTo("/api/notifications")));
}
@Test
public void testSmsEndpointMessage() throws ParseException {
stubFor(post(urlPathEqualTo("/api/notifications"))
.withHeader("Content-Type", matching("application/json;.*"))
.willReturn(aResponse()
.withStatus(200)));
final SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, restcommContact);
wireMockRule.addMockServiceRequestListener(new RequestListener() {
@Override
public void requestReceived(com.github.tomakehurst.wiremock.http.Request request, com.github.tomakehurst.wiremock.http.Response response) {
if (request.getAbsoluteUrl().contains("/api/notifications") && response.getStatus() == 200) {
assertTrue(alicePhone.register(uri, "alice", "1234", aliceContact, 3600, 3600));
}
}
});
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForMessage();
String from = "+15126002188";
String to = "alice";
String body = "Hello, Alice!";
JsonObject callResult = SmsEndpointTool.getInstance().createSms(deploymentUrl.toString(), adminAccountSid,
adminAuthToken, from, to, body, null);
assertNotNull(callResult);
assertTrue(aliceCall.waitForMessage(10000));
Request messageRequest = aliceCall.getLastReceivedMessageRequest();
assertTrue(aliceCall.sendMessageResponse(202, "Accepted", 3600));
String messageReceived = new String(messageRequest.getRawContent());
assertTrue(messageReceived.equals(body));
verify(postRequestedFor(urlEqualTo("/api/notifications")));
}
@SuppressWarnings("Duplicates")
@Deployment(name = "SmsPushNotificationServerTest", testable = false)
public static WebArchive createWebArchiveNoGw() {
logger.info("Packaging Test App");
reconfigurePorts();
Map<String,String> replacements = new HashMap();
//replace mediaport 2727
replacements.put("2727", String.valueOf(mediaPort));
replacements.put("8080", String.valueOf(restcommHTTPPort));
replacements.put("8090", String.valueOf(mockPort));
replacements.put("5080", String.valueOf(restcommPort));
replacements.put("5090", String.valueOf(bobPort));
replacements.put("5091", String.valueOf(alicePort));
return WebArchiveUtil.createWebArchiveNoGw("restcomm_for_SMSEndpointTest.xml", "restcomm.script_pushNotificationServer", replacements);
}
}
| 11,066 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
CallLifecycleTestLive.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/CallLifecycleTestLive.java | package org.restcomm.connect.testsuite.telephony;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.Credential;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipStack;
import org.cafesip.sipunit.SipTransaction;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.restcomm.connect.commons.Version;
import javax.sip.message.Response;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Created by gvagenas on 4/5/16.
*/
@Ignore public class CallLifecycleTestLive {
private final static Logger logger = Logger.getLogger(CallLifecycleTest.class.getName());
private static final String version = Version.getVersion();
private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53,
53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46,
48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49,
13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65,
86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 };
private static final String body = new String(bytes);
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
//Dial Action URL: http://ACae6e420f425248d6a26948c17a9e2acf:[email protected]:8080/restcomm/2012-04-24/DialAction Method: POST
@Rule
public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080
private static SipStackTool tool1;
private static SipStackTool tool2;
private static SipStackTool tool3;
private static SipStackTool tool4;
// Bob is a simple SIP Client. Will not register with Restcomm
private SipStack bobSipStack;
private SipPhone bobPhone;
private String bobContact = "sip:[email protected]:5090";
// Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML
// of the VoiceURL will be executed.
private SipStack aliceSipStack;
private SipPhone alicePhone;
private String aliceContact = "sip:[email protected]:5091";
// Henrique is a simple SIP Client. Will not register with Restcomm
private SipStack henriqueSipStack;
private SipPhone henriquePhone;
private String henriqueContact = "sip:[email protected]:5092";
// George is a simple SIP Client. Will not register with Restcomm
private SipStack georgeSipStack;
private SipPhone georgePhone;
private String georgeContact = "sip:[email protected]:5070";
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("DialActionTest1");
tool2 = new SipStackTool("DialActionTest2");
tool3 = new SipStackTool("DialActionTest3");
tool4 = new SipStackTool("DialActionTest4");
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "192.168.1.190", "5090", "192.168.1.190:5080");
bobPhone = bobSipStack.createSipPhone("192.168.1.190", SipStack.PROTOCOL_UDP, 5080, bobContact);
aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "192.168.1.190", "5091", "192.168.1.190:5080");
alicePhone = aliceSipStack.createSipPhone("192.168.1.190", SipStack.PROTOCOL_UDP, 5080, aliceContact);
henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "192.168.1.190", "5092", "192.168.1.190:5080");
henriquePhone = henriqueSipStack.createSipPhone("192.168.1.190", SipStack.PROTOCOL_UDP, 5080, henriqueContact);
georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "192.168.1.190", "5070", "192.168.1.190:5080");
georgePhone = georgeSipStack.createSipPhone("192.168.1.190", SipStack.PROTOCOL_UDP, 5080, georgeContact);
}
@After
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
}
if (bobSipStack != null) {
bobSipStack.dispose();
}
if (aliceSipStack != null) {
aliceSipStack.dispose();
}
if (alicePhone != null) {
alicePhone.dispose();
}
if (henriqueSipStack != null) {
henriqueSipStack.dispose();
}
if (henriquePhone != null) {
henriquePhone.dispose();
}
if (georgePhone != null) {
georgePhone.dispose();
}
if (georgeSipStack != null) {
georgeSipStack.dispose();
}
Thread.sleep(2000);
wireMockRule.resetRequests();
Thread.sleep(2000);
}
@Test @Ignore
public void testDialCancelBeforeDialingClientAliceAfterTryingLive() throws ParseException, InterruptedException, MalformedURLException {
Credential c = new Credential("192.168.1.190","bob","1234");
bobPhone.addUpdateCredential(c);
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitForAuthorisation(5 * 1000));
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.TRYING);
SipTransaction cancelTransaction = bobCall.sendCancel();
assertNotNull(cancelTransaction);
assertTrue(bobCall.waitForCancelResponse(cancelTransaction,5 * 1000));
assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.OK);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.REQUEST_TERMINATED);
Thread.sleep(10000);
}
@Test @Ignore
public void testDialCancelBeforeDialingClientAliceAfterRinging() throws ParseException, InterruptedException, MalformedURLException {
Credential c = new Credential("192.168.1.190","bob","1234");
bobPhone.addUpdateCredential(c);
// Create outgoing call with first phone
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]:5080", null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitForAuthorisation(5 * 1000));
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.TRYING || response == Response.RINGING);
if (response == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
// assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
// assertTrue(bobCall.getLastReceivedResponse().getStatusCode() == Response.OK);
// bobCall.sendInviteOkAck();
Thread.sleep(15);
SipTransaction cancelTransaction = bobCall.sendCancel();
assertNotNull(cancelTransaction);
assertTrue(bobCall.waitForCancelResponse(cancelTransaction,5 * 1000));
assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.OK);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertTrue(bobCall.getLastReceivedResponse().getStatusCode()==Response.REQUEST_TERMINATED);
}
}
| 8,774 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
ReferOrganizationTest.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/ReferOrganizationTest.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite.telephony;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.verification.LoggedRequest;
import com.google.gson.JsonObject;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.Credential;
import org.cafesip.sipunit.ReferSubscriber;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipRequest;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.runner.RunWith;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.testsuite.http.RestcommCallsTool;
import org.restcomm.connect.testsuite.tools.MonitoringServiceTool;
import javax.sip.SipException;
import javax.sip.address.SipURI;
import javax.sip.message.Response;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.findAll;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess;
import static org.cafesip.sipunit.SipAssert.assertNoSubscriptionErrors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.experimental.categories.Category;
import org.restcomm.connect.commons.annotations.FeatureAltTests;
import org.restcomm.connect.commons.annotations.FeatureExpTests;
import org.restcomm.connect.commons.annotations.SequentialClassTests;
import org.restcomm.connect.commons.annotations.WithInMinsTests;
/**
* Test for SIP Refer support according to the RFC5589 spec in order to provide call transfer capabilities to deskphone
* sip clients that use SIP Refer to implement call transfer.
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(value={WithInMinsTests.class, SequentialClassTests.class})
public class ReferOrganizationTest {
private final static Logger logger = Logger.getLogger(ReferOrganizationTest.class.getName());
private static final String version = Version.getVersion();
private static final byte[] bytes = new byte[] { 118, 61, 48, 13, 10, 111, 61, 117, 115, 101, 114, 49, 32, 53, 51, 54, 53,
53, 55, 54, 53, 32, 50, 51, 53, 51, 54, 56, 55, 54, 51, 55, 32, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46,
48, 46, 49, 13, 10, 115, 61, 45, 13, 10, 99, 61, 73, 78, 32, 73, 80, 52, 32, 49, 50, 55, 46, 48, 46, 48, 46, 49,
13, 10, 116, 61, 48, 32, 48, 13, 10, 109, 61, 97, 117, 100, 105, 111, 32, 54, 48, 48, 48, 32, 82, 84, 80, 47, 65,
86, 80, 32, 48, 13, 10, 97, 61, 114, 116, 112, 109, 97, 112, 58, 48, 32, 80, 67, 77, 85, 47, 56, 48, 48, 48, 13, 10 };
private static final String body = new String(bytes);
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
@Rule
public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080
private static SipStackTool tool1;
private static SipStackTool tool2;
private static SipStackTool tool3;
private String dialRestcommOrg3 = "sip:[email protected]";
// Bob is a simple SIP Client. Will not register with Restcomm
private SipStack bobSipStack;
private SipPhone bobPhone;
private String bobContact = "sip:[email protected]";
// Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm.
private SipStack aliceSipStack;
private SipPhone alicePhone;
private String aliceContact = "sip:[email protected]"; //127.0.0.1:5091";
// George is a simple SIP Client. Will not register with Restcomm
private SipStack georgeSipStack;
private SipPhone georgePhone;
private String georgeContact = "sip:[email protected]:5070";
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("DialActionTest1");
tool2 = new SipStackTool("DialActionTest2");
tool3 = new SipStackTool("DialActionTest3");
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080");
bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact);
aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080");
alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact);
georgeSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080");
georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact);
}
@After
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
}
if (bobSipStack != null) {
bobSipStack.dispose();
}
if (aliceSipStack != null) {
aliceSipStack.dispose();
}
if (alicePhone != null) {
alicePhone.dispose();
}
if (georgePhone != null) {
georgePhone.dispose();
}
if (georgeSipStack != null) {
georgeSipStack.dispose();
}
Thread.sleep(1000);
wireMockRule.resetRequests();
Thread.sleep(4000);
}
private String dialGeorgeRcml = "<Response><Dial><Number>+131313</Number></Dial></Response>";
private String dialAliceRcml = "<Response><Dial><Client>alice</Client></Dial></Response>";
private final String clientPassword = "1234";
@Test
public void testTransfer() throws ParseException, InterruptedException, MalformedURLException, SipException {
stubFor(get(urlPathEqualTo("/1111"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialGeorgeRcml)));
stubFor(get(urlPathEqualTo("/2222"))
.withQueryParam("ReferTarget", equalTo("alice"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialAliceRcml)));
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080");
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600));
Credential c = new Credential("refertest.restcomm.com", "alice", clientPassword );
alicePhone.addUpdateCredential(c);
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.listenForIncomingCall();
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForIncomingCall();
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, dialRestcommOrg3, null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int callResponse = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING);
logger.info("Last response: "+callResponse);
if (callResponse == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(georgeCall.waitForIncomingCall(5000));
assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600));
assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600));
SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest();
String receivedBody = new String(lastReceivedRequest.getRawContent());
assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(georgeCall.waitForAck(5000));
SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "refertest.restcomm.com");
ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000);
assertNotNull(subscription);
assertTrue(subscription.isSubscriptionPending());
assertTrue(subscription.processResponse(1000));
assertTrue(subscription.isSubscriptionPending());
assertNoSubscriptionErrors(subscription);
georgeCall.listenForDisconnect();
assertTrue(georgeCall.waitForDisconnect(10000));
assertTrue(georgeCall.respondToDisconnect());
assertTrue(aliceCall.waitForIncomingCall(5000));
assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600));
assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600));
receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent());
assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(aliceCall.waitForAck(5000));
int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertTrue(liveCalls==2);
assertTrue(liveIncomingCalls==1);
assertTrue(liveOutgoingCalls==1);
assertTrue(liveCallsArraySize==2);
bobCall.listenForDisconnect();
assertTrue(aliceCall.disconnect());
assertTrue(bobCall.waitForDisconnect(5000));
assertTrue(bobCall.respondToDisconnect());
Thread.sleep(10000);
logger.info("About to check the Requests");
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111")));
assertTrue(requests.size() == 1);
String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();
List<String> params = Arrays.asList(requestBody.split("&"));
String callSid = "";
for (String param : params) {
if (param.contains("CallSid")) {
callSid = param.split("=")[1];
}
}
requests = findAll(getRequestedFor(urlPathMatching("/2222")));
assertTrue(requests.size() == 1);
requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();
params = Arrays.asList(requestBody.split("&"));
assertTrue(params.contains("Transferor=%2B131313"));
assertTrue(params.contains("Transferee=bob"));
assertTrue(params.contains("ReferTarget=alice"));
JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid);
JsonObject jsonObj = cdr.getAsJsonObject();
assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed"));
JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertNotNull(metrics);
liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt();
logger.info("LiveCalls: "+liveCalls);
liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size();
logger.info("LiveCallsArraySize: "+liveCallsArraySize);
assertTrue(liveCalls==0);
assertTrue(liveCallsArraySize==0);
int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt();
int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
assertTrue(maxConcurrentCalls==2);
assertTrue(maxConcurrentIncomingCalls==1);
assertTrue(maxConcurrentOutgoingCalls==1);
}
@Test
public void testTransferToAnyNumber() throws ParseException, InterruptedException, MalformedURLException, SipException {
stubFor(get(urlPathEqualTo("/gottacatchemall"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialGeorgeRcml)));
stubFor(get(urlPathEqualTo("/2222"))
.withQueryParam("ReferTarget", equalTo("alice"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialAliceRcml)));
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080");
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600));
Credential c = new Credential("refertest.restcomm.com", "alice", clientPassword );
alicePhone.addUpdateCredential(c);
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.listenForIncomingCall();
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForIncomingCall();
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]", null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int callResponse = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING);
logger.info("Last response: "+callResponse);
if (callResponse == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(georgeCall.waitForIncomingCall(5000));
assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600));
assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600));
SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest();
String receivedBody = new String(lastReceivedRequest.getRawContent());
assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(georgeCall.waitForAck(5000));
SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "refertest.restcomm.com");
ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000);
assertNotNull(subscription);
assertTrue(subscription.isSubscriptionPending());
assertTrue(subscription.processResponse(1000));
assertTrue(subscription.isSubscriptionPending());
assertNoSubscriptionErrors(subscription);
georgeCall.listenForDisconnect();
assertTrue(georgeCall.waitForDisconnect(10000));
assertTrue(georgeCall.respondToDisconnect());
assertTrue(aliceCall.waitForIncomingCall(5000));
assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600));
assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600));
receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent());
assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(aliceCall.waitForAck(5000));
int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertTrue(liveCalls==2);
assertTrue(liveIncomingCalls==1);
assertTrue(liveOutgoingCalls==1);
assertTrue(liveCallsArraySize==2);
bobCall.listenForDisconnect();
assertTrue(aliceCall.disconnect());
assertTrue(bobCall.waitForDisconnect(5000));
assertTrue(bobCall.respondToDisconnect());
Thread.sleep(10000);
logger.info("About to check the Requests");
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/gottacatchemall")));
assertTrue(requests.size() == 1);
String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();
List<String> params = Arrays.asList(requestBody.split("&"));
String callSid = "";
for (String param : params) {
if (param.contains("CallSid")) {
callSid = param.split("=")[1];
}
}
JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid);
JsonObject jsonObj = cdr.getAsJsonObject();
assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed"));
JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertNotNull(metrics);
liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt();
logger.info("LiveCalls: "+liveCalls);
liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size();
logger.info("LiveCallsArraySize: "+liveCallsArraySize);
assertTrue(liveCalls==0);
assertTrue(liveCallsArraySize==0);
int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt();
int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
assertTrue(maxConcurrentCalls==2);
assertTrue(maxConcurrentIncomingCalls==1);
assertTrue(maxConcurrentOutgoingCalls==1);
}
@Test
public void testTransferToNumberWithPlusSign() throws ParseException, InterruptedException, MalformedURLException, SipException {
stubFor(get(urlPathEqualTo("/1112"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialGeorgeRcml)));
stubFor(get(urlPathEqualTo("/2222"))
.withQueryParam("ReferTarget", equalTo("alice"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialAliceRcml)));
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080");
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600));
Credential c = new Credential("refertest.restcomm.com", "alice", clientPassword );
alicePhone.addUpdateCredential(c);
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.listenForIncomingCall();
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForIncomingCall();
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]", null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int callResponse = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING);
logger.info("Last response: "+callResponse);
if (callResponse == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(georgeCall.waitForIncomingCall(5000));
assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600));
assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600));
SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest();
String receivedBody = new String(lastReceivedRequest.getRawContent());
assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(georgeCall.waitForAck(5000));
SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "refertest.restcomm.com");
ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000);
assertNotNull(subscription);
assertTrue(subscription.isSubscriptionPending());
assertTrue(subscription.processResponse(1000));
assertTrue(subscription.isSubscriptionPending());
assertNoSubscriptionErrors(subscription);
georgeCall.listenForDisconnect();
assertTrue(georgeCall.waitForDisconnect(10000));
assertTrue(georgeCall.respondToDisconnect());
assertTrue(aliceCall.waitForIncomingCall(5000));
assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600));
assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600));
receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent());
assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(aliceCall.waitForAck(5000));
int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertTrue(liveCalls==2);
assertTrue(liveIncomingCalls==1);
assertTrue(liveOutgoingCalls==1);
assertTrue(liveCallsArraySize==2);
bobCall.listenForDisconnect();
assertTrue(aliceCall.disconnect());
assertTrue(bobCall.waitForDisconnect(5000));
assertTrue(bobCall.respondToDisconnect());
Thread.sleep(10000);
logger.info("About to check the Requests");
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1112")));
assertTrue(requests.size() == 1);
String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();
List<String> params = Arrays.asList(requestBody.split("&"));
String callSid = "";
for (String param : params) {
if (param.contains("CallSid")) {
callSid = param.split("=")[1];
}
}
JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid);
JsonObject jsonObj = cdr.getAsJsonObject();
assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed"));
JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertNotNull(metrics);
liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt();
logger.info("LiveCalls: "+liveCalls);
liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size();
logger.info("LiveCallsArraySize: "+liveCallsArraySize);
assertTrue(liveCalls==0);
assertTrue(liveCallsArraySize==0);
int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt();
int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
assertTrue(maxConcurrentCalls==2);
assertTrue(maxConcurrentIncomingCalls==1);
assertTrue(maxConcurrentOutgoingCalls==1);
}
@Test
@Category(FeatureAltTests.class)
public void testTransferHangupByBob() throws ParseException, InterruptedException, MalformedURLException, SipException {
stubFor(get(urlPathEqualTo("/1111"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialGeorgeRcml)));
stubFor(get(urlPathEqualTo("/2222"))
.withQueryParam("ReferTarget", equalTo("alice"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialAliceRcml)));
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080");
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600));
Credential c = new Credential("refertest.restcomm.com", "alice", clientPassword );
alicePhone.addUpdateCredential(c);
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.listenForIncomingCall();
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForIncomingCall();
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, dialRestcommOrg3, null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int callResponse = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING);
logger.info("Last response: "+callResponse);
if (callResponse == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(georgeCall.waitForIncomingCall(5000));
assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600));
assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600));
SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest();
String receivedBody = new String(lastReceivedRequest.getRawContent());
assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(georgeCall.waitForAck(5000));
SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "refertest.restcomm.com");
ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000);
assertNotNull(subscription);
assertTrue(subscription.isSubscriptionPending());
assertTrue(subscription.processResponse(1000));
assertTrue(subscription.isSubscriptionPending());
assertNoSubscriptionErrors(subscription);
georgeCall.listenForDisconnect();
assertTrue(georgeCall.waitForDisconnect(10000));
assertTrue(georgeCall.respondToDisconnect());
assertTrue(aliceCall.waitForIncomingCall(5000));
assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600));
assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600));
receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent());
assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(aliceCall.waitForAck(5000));
int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertTrue(liveCalls==2);
assertTrue(liveIncomingCalls==1);
assertTrue(liveOutgoingCalls==1);
assertTrue(liveCallsArraySize==2);
aliceCall.listenForDisconnect();
assertTrue(bobCall.disconnect());
assertTrue(aliceCall.waitForDisconnect(5000));
assertTrue(aliceCall.respondToDisconnect());
Thread.sleep(10000);
logger.info("About to check the Requests");
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111")));
assertTrue(requests.size() == 1);
String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();
List<String> params = Arrays.asList(requestBody.split("&"));
String callSid = "";
for (String param : params) {
if (param.contains("CallSid")) {
callSid = param.split("=")[1];
}
}
JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid);
JsonObject jsonObj = cdr.getAsJsonObject();
assertTrue(jsonObj.get("status").getAsString().equalsIgnoreCase("completed"));
JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertNotNull(metrics);
liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt();
logger.info("LiveCalls: "+liveCalls);
liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size();
logger.info("LiveCallsArraySize: "+liveCallsArraySize);
assertTrue(liveCalls==0);
assertTrue(liveCallsArraySize==0);
int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt();
int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
assertTrue(maxConcurrentCalls==2);
assertTrue(maxConcurrentIncomingCalls==1);
assertTrue(maxConcurrentOutgoingCalls==1);
}
@Test
public void testTransferByBob() throws ParseException, InterruptedException, MalformedURLException, SipException {
stubFor(get(urlPathEqualTo("/1111"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialGeorgeRcml)));
stubFor(get(urlPathEqualTo("/2222"))
.withQueryParam("ReferTarget", equalTo("alice"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialAliceRcml)));
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080");
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600));
Credential c = new Credential("refertest.restcomm.com", "alice", clientPassword );
alicePhone.addUpdateCredential(c);
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.listenForIncomingCall();
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForIncomingCall();
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, dialRestcommOrg3, null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int callResponse = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING);
logger.info("Last response: "+callResponse);
if (callResponse == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(georgeCall.waitForIncomingCall(6000));
assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600));
assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600));
SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest();
String receivedBody = new String(lastReceivedRequest.getRawContent());
assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(georgeCall.waitForAck(5000));
SipURI referTo = bobSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080");
ReferSubscriber subscription = bobPhone.refer(bobCall.getDialog(), referTo, null, 5000);
assertNotNull(subscription);
assertTrue(subscription.isSubscriptionPending());
assertTrue(subscription.processResponse(1000));
assertTrue(subscription.isSubscriptionPending());
assertNoSubscriptionErrors(subscription);
bobCall.listenForDisconnect();
assertTrue(bobCall.waitForDisconnect(10000));
assertTrue(bobCall.respondToDisconnect());
assertTrue(aliceCall.waitForIncomingCall(5000));
assertTrue(aliceCall.sendIncomingCallResponse(Response.TRYING, "Alice-Trying", 3600));
assertTrue(aliceCall.sendIncomingCallResponse(Response.RINGING, "Alice-Ringing", 3600));
receivedBody = new String(aliceCall.getLastReceivedRequest().getRawContent());
assertTrue(aliceCall.sendIncomingCallResponse(Response.OK, "Alice-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(aliceCall.waitForAck(5000));
int liveCalls = MonitoringServiceTool.getInstance().getStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveIncomingCalls = MonitoringServiceTool.getInstance().getLiveIncomingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveOutgoingCalls = MonitoringServiceTool.getInstance().getLiveOutgoingCallStatistics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
int liveCallsArraySize = MonitoringServiceTool.getInstance().getLiveCallsArraySize(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertTrue(liveCalls==2);
assertTrue(liveOutgoingCalls==2);
assertTrue(liveCallsArraySize==2);
georgeCall.listenForDisconnect();
assertTrue(aliceCall.disconnect());
assertTrue(georgeCall.waitForDisconnect(5000));
assertTrue(georgeCall.respondToDisconnect());
Thread.sleep(10000);
logger.info("About to check the Requests");
List<LoggedRequest> requests = findAll(getRequestedFor(urlPathMatching("/1111")));
assertTrue(requests.size() == 1);
String requestBody = new URL(requests.get(0).getAbsoluteUrl()).getQuery();
List<String> params = Arrays.asList(requestBody.split("&"));
String callSid = "";
for (String param : params) {
if (param.contains("CallSid")) {
callSid = param.split("=")[1];
}
}
JsonObject cdr = RestcommCallsTool.getInstance().getCall(deploymentUrl.toString(), adminAccountSid, adminAuthToken, callSid);
JsonObject jsonObj = cdr.getAsJsonObject();
//This will fail because CDR is not updated because Observers are cleared
// assertEquals("complete", jsonObj.get("status").getAsString());
JsonObject metrics = MonitoringServiceTool.getInstance().getMetrics(deploymentUrl.toString(),adminAccountSid, adminAuthToken);
assertNotNull(metrics);
liveCalls = metrics.getAsJsonObject("Metrics").get("LiveCalls").getAsInt();
logger.info("LiveCalls: "+liveCalls);
liveCallsArraySize = metrics.getAsJsonArray("LiveCallDetails").size();
logger.info("LiveCallsArraySize: "+liveCallsArraySize);
assertTrue(liveCalls==0);
assertTrue(liveCallsArraySize==0);
int maxConcurrentCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentCalls").getAsInt();
int maxConcurrentIncomingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
int maxConcurrentOutgoingCalls = metrics.getAsJsonObject("Metrics").get("MaximumConcurrentIncomingCalls").getAsInt();
assertTrue(maxConcurrentCalls==2);
assertTrue(maxConcurrentIncomingCalls==1);
assertTrue(maxConcurrentOutgoingCalls==1);
}
@Test
@Category(FeatureExpTests.class)
public void testTransferWithAbsentReferUrlAndApplication() throws ParseException, InterruptedException, MalformedURLException, SipException {
stubFor(get(urlPathEqualTo("/1111"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialGeorgeRcml)));
stubFor(get(urlPathEqualTo("/2222"))
.withQueryParam("ReferTarget", equalTo("alice"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialAliceRcml)));
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080");
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600));
Credential c = new Credential("refertest.restcomm.com", "alice", clientPassword );
alicePhone.addUpdateCredential(c);
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.listenForIncomingCall();
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForIncomingCall();
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, "sip:[email protected]", null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int callResponse = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING);
logger.info("Last response: "+callResponse);
if (callResponse == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(georgeCall.waitForIncomingCall(5000));
assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600));
assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600));
SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest();
String receivedBody = new String(lastReceivedRequest.getRawContent());
assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(georgeCall.waitForAck(5000));
SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080");
ReferSubscriber subscription = georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000);
assertNull(subscription);
assertEquals("Received response status: 404, reason: Not found", georgePhone.getErrorMessage());
}
@Test
@Category(FeatureExpTests.class)
public void testTransferWithOutOfDialogRefer() throws ParseException, InterruptedException, MalformedURLException, SipException {
stubFor(get(urlPathEqualTo("/1111"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialGeorgeRcml)));
stubFor(get(urlPathEqualTo("/2222"))
.withQueryParam("ReferTarget", equalTo("alice"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialAliceRcml)));
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080");
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600));
Credential c = new Credential("refertest.restcomm.com", "alice", clientPassword );
alicePhone.addUpdateCredential(c);
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.listenForIncomingCall();
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForIncomingCall();
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, dialRestcommOrg3, null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int callResponse = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(callResponse == Response.TRYING || callResponse == Response.RINGING);
logger.info("Last response: "+callResponse);
if (callResponse == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(georgeCall.waitForIncomingCall(5000));
assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600));
assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600));
SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest();
String receivedBody = new String(lastReceivedRequest.getRawContent());
assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(georgeCall.waitForAck(5000));
SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("alice", "127.0.0.1:5080");
ReferSubscriber subscription = georgePhone.refer(bobContact, referTo, null, 5000, null);
assertNotNull(subscription);
assertFalse(subscription.processResponse(1000));
assertEquals("Received response status: 404, reason: Not found", subscription.getErrorMessage());
}
private String dialJoeRcml = "<Response><Dial><Client>joe</Client></Dial></Response>";
@Test
@Category(FeatureExpTests.class)
public void testTransferIncorrectReferTarget() throws ParseException, InterruptedException, MalformedURLException, SipException {
stubFor(get(urlPathEqualTo("/1111"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialGeorgeRcml)));
stubFor(get(urlPathEqualTo("/2222"))
.withQueryParam("ReferTarget", equalTo("joe"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(dialJoeRcml)));
SipURI uri = aliceSipStack.getAddressFactory().createSipURI(null, "127.0.0.1:5080");
assertTrue(alicePhone.register(uri, "alice", "1234", "sip:[email protected]:5091", 3600, 3600));
Credential c = new Credential("refertest.restcomm.com", "alice", clientPassword );
alicePhone.addUpdateCredential(c);
SipCall georgeCall = georgePhone.createSipCall();
georgeCall.listenForIncomingCall();
SipCall aliceCall = alicePhone.createSipCall();
aliceCall.listenForIncomingCall();
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, dialRestcommOrg3, null, body, "application", "sdp", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
final int response = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(response == Response.TRYING || response == Response.RINGING);
logger.info("Last response: "+response);
if (response == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
logger.info("Last response: "+bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
assertTrue(bobCall.sendInviteOkAck());
assertTrue(georgeCall.waitForIncomingCall(5000));
assertTrue(georgeCall.sendIncomingCallResponse(Response.TRYING, "George-Trying", 3600));
assertTrue(georgeCall.sendIncomingCallResponse(Response.RINGING, "George-Ringing", 3600));
SipRequest lastReceivedRequest = georgeCall.getLastReceivedRequest();
String receivedBody = new String(lastReceivedRequest.getRawContent());
assertTrue(georgeCall.sendIncomingCallResponse(Response.OK, "George-OK", 3600, receivedBody, "application", "sdp",
null, null));
assertTrue(georgeCall.waitForAck(5000));
georgeCall.listenForDisconnect();
bobCall.listenForDisconnect();
SipURI referTo = georgeSipStack.getAddressFactory().createSipURI("joe", "refertest.restcomm.com");
georgePhone.refer(georgeCall.getDialog(), referTo, null, 5000);
assertTrue(georgeCall.waitForDisconnect(5000));
assertTrue(georgeCall.respondToDisconnect());
assertTrue(bobCall.waitForDisconnect(5000));
assertTrue(bobCall.respondToDisconnect());
}
@Deployment(name = "DialAction", managed = true, testable = false)
public static WebArchive createWebArchiveNoGw() {
logger.info("Packaging Test App");
WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war");
final WebArchive restcommArchive = Maven.resolver()
.resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity()
.asSingle(WebArchive.class);
archive = archive.merge(restcommArchive);
archive.delete("/WEB-INF/sip.xml");
archive.delete("/WEB-INF/web.xml");
archive.delete("/WEB-INF/conf/restcomm.xml");
archive.delete("/WEB-INF/data/hsql/restcomm.script");
archive.delete("/WEB-INF/classes/application.conf");
archive.addAsWebInfResource("sip.xml");
archive.addAsWebInfResource("web.xml");
archive.addAsWebInfResource("restcomm_referorg.xml", "conf/restcomm.xml");
archive.addAsWebInfResource("restcomm.script_ReferMessageOrgTest", "data/hsql/restcomm.script");
archive.addAsWebInfResource("akka_application.conf", "classes/application.conf");
logger.info("Packaged Test App");
return archive;
}
}
| 53,867 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
TestMultipartContent.java | /FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/telephony/TestMultipartContent.java | /*
* TeleStax, Open Source Cloud Communications
* Copyright 2011-2014, Telestax Inc and individual contributors
* by the @authors tag.
*
* This program is free software: you can redistribute it and/or modify
* under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package org.restcomm.connect.testsuite.telephony;
import static org.cafesip.sipunit.SipAssert.assertLastOperationSuccess;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URL;
import javax.sip.message.Response;
import org.apache.log4j.Logger;
import org.cafesip.sipunit.Credential;
import org.cafesip.sipunit.SipCall;
import org.cafesip.sipunit.SipPhone;
import org.cafesip.sipunit.SipStack;
import org.jboss.arquillian.container.mss.extension.SipStackTool;
import org.jboss.arquillian.container.test.api.Deployer;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.FixMethodOrder;
import org.junit.runners.MethodSorters;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.restcomm.connect.commons.Version;
import org.restcomm.connect.commons.annotations.SequentialClassTests;
import org.restcomm.connect.commons.annotations.WithInMinsTests;
/**
* Test for Multipart Content type. UFone Issue 31380.
* RESTCOMM-330 https://telestax.atlassian.net/browse/RESTCOMM-330
*
* @author <a href="mailto:[email protected]">gvagenas</a>
*
*/
@RunWith(Arquillian.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Category(SequentialClassTests.class)
public class TestMultipartContent {
private static Logger logger = Logger.getLogger(TestMultipartContent.class);
private static final String version = Version.getVersion();
private static final String multipartBody = "--uniqueBoundary \n"
+ "Content-Type: application/sdp \n"
+ "Content-Disposition: session;handling=required \n"
+ "\n"
+ "v=0\n"
+ "o=CiscoSystemsSIP-GW-UserAgent 7968 329 IN IP4 172.16.30.13\n"
+ "s=SIP Call\n"
+ "c=IN IP4 172.16.30.13\n"
+ "t=0 0\n"
+ "m=audio 30086 RTP/AVP 0 18 101\n"
+ "c=IN IP4 172.16.30.13\n"
+ "a=rtpmap:0 PCMU/8000\n"
+ "a=rtpmap:18 G729/8000\n"
+ "a=fmtp:18 annexb=no\n"
+ "a=rtpmap:101 telephone-event/8000\n"
+ "a=fmtp:101 0-16\n"
+ "\n"
+"--uniqueBoundary\n"
+"Content-Type: application/x-q931\n"
+"Content-Disposition: signal;handling=optional\n"
+"Content-Length: 39\n"
+"\n"
+"�L�������l!�3335500057p�1330\n"
+"\n"
+"--uniqueBoundary\n"
+"Content-Type: application/gtd\n"
+"Content-Disposition: signal;handling=optional\n"
+"\n"
+"IAM,\n"
+"PRN,isdn*,,NET5*,\n"
+"USI,rate,c,s,c,1\n"
+"USI,lay1,alaw\n"
+"TMR,00\n"
+"CPN,02,,1,1330\n"
+"CGN,04,,1,y,4,3335500057\n"
+"CPC,09 \n"
+"FCI,,,,,,,y, \n"
+"GCI,f2ea4c5e9fd211e3ae4b5057a8ed5300\n"
+"\n"
+"--uniqueBoundary-- \n";
@ArquillianResource
private Deployer deployer;
@ArquillianResource
URL deploymentUrl;
private static SipStackTool tool1;
private static SipStackTool tool2;
private static SipStackTool tool3;
private static SipStackTool tool4;
// Bob is a simple SIP Client. Will not register with Restcomm
private SipStack bobSipStack;
private SipPhone bobPhone;
private String bobContact = "sip:[email protected]:5090";
// Alice is a Restcomm Client with VoiceURL. This Restcomm Client can register with Restcomm and whatever will dial the RCML
// of the VoiceURL will be executed.
private SipStack aliceSipStack;
private SipPhone alicePhone;
private String aliceContact = "sip:[email protected]:5091";
// Henrique is a simple SIP Client. Will not register with Restcomm
private SipStack henriqueSipStack;
private SipPhone henriquePhone;
private String henriqueContact = "sip:[email protected]:5092";
// George is a simple SIP Client. Will not register with Restcomm
private SipStack georgeSipStack;
private SipPhone georgePhone;
private String georgeContact = "sip:[email protected]:5070";
private String dialClientWithActionUrl = "sip:[email protected]:5080";
private String dialConf = "sip:[email protected]:5080";
private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf";
private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166";
@BeforeClass
public static void beforeClass() throws Exception {
tool1 = new SipStackTool("DialActionTest1");
tool2 = new SipStackTool("DialActionTest2");
tool3 = new SipStackTool("DialActionTest3");
tool4 = new SipStackTool("DialActionTest4");
}
@Before
public void before() throws Exception {
bobSipStack = tool1.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5090", "127.0.0.1:5080");
bobPhone = bobSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, bobContact);
aliceSipStack = tool2.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5091", "127.0.0.1:5080");
alicePhone = aliceSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, aliceContact);
henriqueSipStack = tool3.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5092", "127.0.0.1:5080");
henriquePhone = henriqueSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, henriqueContact);
georgeSipStack = tool4.initializeSipStack(SipStack.PROTOCOL_UDP, "127.0.0.1", "5070", "127.0.0.1:5080");
georgePhone = georgeSipStack.createSipPhone("127.0.0.1", SipStack.PROTOCOL_UDP, 5080, georgeContact);
}
@After
public void after() throws Exception {
if (bobPhone != null) {
bobPhone.dispose();
}
if (bobSipStack != null) {
bobSipStack.dispose();
}
if (aliceSipStack != null) {
aliceSipStack.dispose();
}
if (alicePhone != null) {
alicePhone.dispose();
}
if (henriqueSipStack != null) {
henriqueSipStack.dispose();
}
if (henriquePhone != null) {
henriquePhone.dispose();
}
if (georgePhone != null) {
georgePhone.dispose();
}
if (georgeSipStack != null) {
georgeSipStack.dispose();
}
}
@Test
public synchronized void testDialConference() throws InterruptedException {
Credential c = new Credential("127.0.0.1", "bob", "1234");
bobPhone.addUpdateCredential(c);
final SipCall bobCall = bobPhone.createSipCall();
bobCall.initiateOutgoingCall(bobContact, dialConf, null, multipartBody, "multipart", "mixed;boundary=uniqueBoundary", null, null);
assertLastOperationSuccess(bobCall);
assertTrue(bobCall.waitForAuthorisation(5000));
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
int responseBob = bobCall.getLastReceivedResponse().getStatusCode();
assertTrue(responseBob == Response.TRYING || responseBob == Response.RINGING);
if (responseBob == Response.TRYING) {
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, bobCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(bobCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, bobCall.getLastReceivedResponse().getStatusCode());
bobCall.sendInviteOkAck();
assertTrue(!(bobCall.getLastReceivedResponse().getStatusCode() >= 400));
// George calls to the conference
final SipCall georgeCall = georgePhone.createSipCall();
georgeCall.initiateOutgoingCall(georgeContact, dialConf, null, multipartBody, "multipart", "mixed;boundary=uniqueBoundary", null, null);
assertLastOperationSuccess(georgeCall);
assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000));
int responseGeorge = georgeCall.getLastReceivedResponse().getStatusCode();
assertTrue(responseGeorge == Response.TRYING || responseGeorge == Response.RINGING);
if (responseGeorge == Response.TRYING) {
assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.RINGING, georgeCall.getLastReceivedResponse().getStatusCode());
}
assertTrue(georgeCall.waitOutgoingCallResponse(5 * 1000));
assertEquals(Response.OK, georgeCall.getLastReceivedResponse().getStatusCode());
georgeCall.sendInviteOkAck();
assertTrue(!(georgeCall.getLastReceivedResponse().getStatusCode() >= 400));
// Wait for the media to play and the call to hangup.
bobCall.listenForDisconnect();
georgeCall.listenForDisconnect();
// Start a new thread for george to wait disconnect
new Thread(new Runnable() {
@Override
public void run() {
assertTrue(georgeCall.waitForDisconnect(30 * 1000));
}
}).start();
// Start a new thread for bob to wait disconnect
new Thread(new Runnable() {
@Override
public void run() {
assertTrue(bobCall.waitForDisconnect(30 * 1000));
}
}).start();
// assertTrue(bobCall.waitForDisconnect(30 * 1000));
try {
Thread.sleep(10 * 1000);
} catch (final InterruptedException exception) {
exception.printStackTrace();
}
}
@Deployment(name = "TestMultipartContent", managed = true, testable = false)
public static WebArchive createWebArchiveNoGw() {
logger.info("Packaging Test App");
WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war");
final WebArchive restcommArchive = Maven.resolver()
.resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity()
.asSingle(WebArchive.class);
archive = archive.merge(restcommArchive);
archive.delete("/WEB-INF/sip.xml");
archive.delete("/WEB-INF/web.xml");
archive.delete("/WEB-INF/conf/restcomm.xml");
archive.delete("/WEB-INF/data/hsql/restcomm.script");
archive.addAsWebInfResource("sip.xml");
archive.addAsWebInfResource("web.xml");
archive.addAsWebInfResource("restcomm.xml", "conf/restcomm.xml");
archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script");
archive.addAsWebResource("dial-conference-entry.xml");
archive.addPackage("org.restcomm.connect.telephony.RestResources");
logger.info("Packaged Test App");
return archive;
}
}
| 11,944 | Java | .java | RestComm/Restcomm-Connect | 239 | 214 | 788 | 2012-08-17T17:47:44Z | 2023-04-14T20:58:19Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.