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
WavNoCacheTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/cache/WavNoCacheTest.java
package org.restcomm.connect.commons.cache; import akka.actor.Actor; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActorFactory; import akka.testkit.TestActorRef; import org.apache.commons.io.FileUtils; import org.apache.shiro.crypto.hash.Sha256Hash; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.commons.cache.DiskCache; import org.restcomm.connect.commons.cache.DiskCacheRequest; import org.restcomm.connect.commons.cache.FileDownloader; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.io.File; import java.net.URI; /** * @author Gennadiy Dubina */ public class WavNoCacheTest { private URI externalUrl = URI.create("http://external/file.wav"); private String externalUrlHash = new Sha256Hash(externalUrl.toString()).toHex(); private String cacheUri = "http://127.0.0.1"; private String cacheDir = "/tmp"; private URI expectedLocal = URI.create(cacheUri + "/" + externalUrlHash + ".wav"); private FileDownloader downloader; private ActorSystem system; @Before public void before() throws Exception { downloader = Mockito.mock(FileDownloader.class); system = ActorSystem.create(); //clean tmp dir final File resultFile = new File(cacheDir + "/" + externalUrlHash + ".wav"); if (resultFile.exists()) { resultFile.delete(); } Mockito.when(downloader.download(Mockito.any(URI.class), Mockito.any(File.class))).then(new Answer<URI>() { @Override public URI answer(InvocationOnMock invocationOnMock) throws Throwable { FileUtils.copyFile(new File("src/test/resources/restcomm.xml"), resultFile); return expectedLocal; } }); } @After public void after() throws Exception { system.shutdown(); } private DiskCache cache(final boolean cacheNo) { final TestActorRef<DiskCache> ref = TestActorRef.create(system, new Props(new UntypedActorFactory() { @Override public Actor create() throws Exception { return new DiskCache(downloader, cacheDir, cacheUri, true, cacheNo); } }), "test"); return ref.underlyingActor(); } @Test public void testWavCached() throws Exception { DiskCache cache = cache(false); URI response1 = cache.cache(new DiskCacheRequest(externalUrl)); Assert.assertEquals(expectedLocal, response1); URI response2 = cache.cache(new DiskCacheRequest(externalUrl)); Assert.assertEquals(expectedLocal, response2); Mockito.verify(downloader, Mockito.times(1)).download(Mockito.any(URI.class), Mockito.any(File.class)); } @Test public void testWavNoCached() throws Exception { DiskCache cache = cache(true); URI response1 = cache.cache(new DiskCacheRequest(externalUrl)); Assert.assertEquals(externalUrl, response1); URI response2 = cache.cache(new DiskCacheRequest(externalUrl)); Assert.assertEquals(externalUrl, response2); Mockito.verify(downloader, Mockito.never()).download(Mockito.any(URI.class), Mockito.any(File.class)); } }
3,352
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DiskCacheTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/test/java/org/restcomm/connect/commons/cache/DiskCacheTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.cache; import static org.junit.Assert.assertTrue; import java.io.File; import java.net.URI; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.restcomm.connect.commons.cache.DiskCache; import org.restcomm.connect.commons.cache.DiskCacheRequest; import org.restcomm.connect.commons.cache.DiskCacheResponse; import org.restcomm.connect.commons.cache.FileDownloader; import scala.concurrent.duration.FiniteDuration; import akka.actor.Actor; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.UntypedActorFactory; import akka.testkit.JavaTestKit; /** * @author [email protected] (Thomas Quintana) */ @Ignore public final class DiskCacheTest { private ActorSystem system; private ActorRef cache; public DiskCacheTest() { super(); } @Before public void before() throws Exception { system = ActorSystem.create(); cache = cache("/tmp", "http://127.0.0.1:8080/restcomm/cache"); } @After public void after() throws Exception { system.shutdown(); } private ActorRef cache(final String location, final String uri) { return system.actorOf(new Props(new UntypedActorFactory() { private static final long serialVersionUID = 1L; @Override public Actor create() throws Exception { return new DiskCache(new FileDownloader(), location, uri); } })); } @Test public void test() { new JavaTestKit(system) { { final ActorRef observer = getRef(); cache.tell(new DiskCacheRequest(URI.create("http://www.mobicents.org/index.html")), observer); final DiskCacheResponse response = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS), DiskCacheResponse.class); assertTrue(response.succeeded()); final File file = new File("/tmp/0877edd3c836d7b38d9615939ff66254fab90b868d75e1b86fcc8d42682d9741.html"); assertTrue(file.exists()); assertTrue(file.length() > 0); final URI result = response.get(); final URI uri = URI .create("http://127.0.0.1:8080/restcomm/cache/0877edd3c836d7b38d9615939ff66254fab90b868d75e1b86fcc8d42682d9741.html"); assertTrue(result.equals(uri)); } }; } @Test public void testHashInTheURI() { final String uriStr = "http://www.mobicents.org/index.html#hash=c32735f2960ef70edb5116e8459c5b65915b3c27ea4773feaa35ce55220f4755"; new JavaTestKit(system) { { final ActorRef observer = getRef(); cache.tell(new DiskCacheRequest(URI.create(uriStr)), observer); final DiskCacheResponse response = this.expectMsgClass(FiniteDuration.create(30, TimeUnit.SECONDS), DiskCacheResponse.class); assertTrue(response.succeeded()); final File file = new File("/tmp/c32735f2960ef70edb5116e8459c5b65915b3c27ea4773feaa35ce55220f4755.html"); assertTrue(file.exists()); assertTrue(file.length() > 0); final URI result = response.get(); final URI uri = URI .create("http://127.0.0.1:8080/restcomm/cache/c32735f2960ef70edb5116e8459c5b65915b3c27ea4773feaa35ce55220f4755.html"); assertTrue(result.equals(uri)); } }; } }
4,497
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Configurable.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/Configurable.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons; import org.apache.commons.configuration.Configuration; /** * @author [email protected] (Thomas Quintana) */ public interface Configurable { void configure(Configuration configuration, Configuration daoManagerConfiguration); }
1,091
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ServiceLocator.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/ServiceLocator.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class ServiceLocator { private static final class SingletonHolder { private static final ServiceLocator instance = new ServiceLocator(); } private final Map<Class<?>, Object> services; private ServiceLocator() { super(); this.services = new ConcurrentHashMap<Class<?>, Object>(); } public <T> T get(final Class<T> klass) { synchronized (klass) { final Object service = services.get(klass); if (service != null) { return klass.cast(service); } else { return null; } } } public static ServiceLocator getInstance() { return SingletonHolder.instance; } public <T> void set(final Class<T> klass, final T instance) { synchronized (klass) { services.put(klass, instance); } } }
1,957
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Version.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/Version.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import org.apache.log4j.Logger; /** * @author jderruelle * @author pslegr * @author gvagenas * */ public class Version { private static Logger logger = Logger.getLogger(Version.class); private static VersionEntity versionEntity; public static void printVersion() { if (logger.isInfoEnabled()) { if (versionEntity == null) versionEntity = generateVersionEntity(); String releaseVersion = versionEntity.getVersion(); String releaseName = versionEntity.getName(); String releaseDate = versionEntity.getDate(); String releaseRevision = versionEntity.getRevision(); String releaseDisclaimer = versionEntity.getDisclaimer(); if (releaseVersion != null) { // Follow the EAP Convention // Release ID: JBoss [EAP] 5.0.1 (build: // SVNTag=JBPAPP_5_0_1 date=201003301050) logger.info("Release ID: Restcomm-Connect " + releaseVersion + " (build: Git Hash=" + releaseRevision + " date=" + releaseDate + ")"); logger.info(releaseName + " Restcomm-Connect " + releaseVersion + " (build: Git Hash=" + releaseRevision + " date=" + releaseDate + ") Started."); } else { logger.warn("Unable to extract the version of Restcomm-Connect currently running"); } if (releaseDisclaimer != null) { logger.info(releaseDisclaimer); } } else { logger.warn("Unable to extract the version of Restcomm-Connect currently running"); } } private static VersionEntity generateVersionEntity() { Properties releaseProperties = new Properties(); try { InputStream in = Version.class .getResourceAsStream("release.properties"); if (in != null) { releaseProperties.load(in); in.close(); String releaseVersion = releaseProperties .getProperty("release.version"); String releaseName = releaseProperties .getProperty("release.name"); String releaseDate = releaseProperties .getProperty("release.date"); String releaseRevision = releaseProperties .getProperty("release.revision"); String releaseDisclaimer = releaseProperties .getProperty("release.disclaimer"); versionEntity = new VersionEntity(releaseVersion,releaseRevision,releaseName,releaseDate, releaseDisclaimer); } else { logger.warn("Unable to extract the version of Restcomm-Connect currently running"); } } catch (IOException e) { logger.warn("Unable to extract the version of Restcomm-Connect currently running",e); } return versionEntity; } public static VersionEntity getVersionEntity() { if (versionEntity != null) { return versionEntity; } else { return generateVersionEntity(); } } public static String getFullVersion() { if (versionEntity == null) versionEntity = generateVersionEntity(); String releaseVersion = versionEntity.getVersion(); String releaseName = versionEntity.getName(); String releaseDate = versionEntity.getDate(); if(releaseDate.equals("${maven.build.timestamp}")) { Date date = new Date(); releaseDate = new SimpleDateFormat("yyyy/MM/dd_HH:mm").format(date); } String releaseRevision = versionEntity.getRevision(); return "Release ID: Restcomm-Connect " + releaseVersion + " (build: Git Hash=" + releaseRevision + " date=" + releaseDate + ")"; } public static String getVersion() { if (versionEntity == null) versionEntity = generateVersionEntity(); return versionEntity.getVersion(); } public static String getRevision() { if (versionEntity == null) versionEntity = generateVersionEntity(); return versionEntity.getRevision(); } }
5,376
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpConnector.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/HttpConnector.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.commons; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public class HttpConnector { private final String scheme; private final String address; private final int port; private final boolean secure; public HttpConnector(final String scheme, final String address, final int port, final boolean secure) { this.scheme = scheme; this.address = address; this.port = port; this.secure = secure; } public String getScheme() { return scheme; } public String getAddress() { return address; } public int getPort() { return port; } public boolean isSecure() { return secure; } }
1,664
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpConnectorList.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/HttpConnectorList.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.commons; import java.util.List; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public class HttpConnectorList { private final List<HttpConnector> connectors; public HttpConnectorList(final List<HttpConnector> connectors) { this.connectors = connectors; } public List<HttpConnector> getConnectors() { return connectors; } }
1,334
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VersionEntity.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/VersionEntity.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.commons; /** * Created by gvagenas on 1/19/16. * @author gvagenas */ public class VersionEntity { private final String version; //Git hash private final String revision; private final String name; private final String date; private final String disclaimer; public VersionEntity(final String version, final String revision, final String name, final String date, final String disclaimer) { this.version = version; this.revision = revision; this.name = name; this.date = date; this.disclaimer = disclaimer; } public String getVersion() { return version; } public String getRevision() { return revision; } public String getName() { return name; } public String getDate() { return date; } public String getDisclaimer() { return disclaimer; } }
1,850
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
LifeCycle.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/LifeCycle.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons; /** * @author [email protected] (Thomas Quintana) */ public interface LifeCycle { void start() throws RuntimeException; void shutdown() throws InterruptedException; }
1,036
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommUntypedActor.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/faulttolerance/RestcommUntypedActor.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.faulttolerance; import akka.actor.SupervisorStrategy; import akka.actor.UntypedActor; /** * @author [email protected] (Oleg Agafonov) */ public abstract class RestcommUntypedActor extends UntypedActor { @Override public SupervisorStrategy supervisorStrategy() { return RestcommSupervisorStrategy.getStrategy(); } }
1,198
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommSupervisorStrategy.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/faulttolerance/RestcommSupervisorStrategy.java
package org.restcomm.connect.commons.faulttolerance; import akka.actor.ActorContext; import akka.actor.ActorRef; import akka.actor.ChildRestartStats; import akka.actor.OneForOneStrategy; import akka.actor.SupervisorStrategy; import akka.actor.SupervisorStrategyConfigurator; import akka.japi.Function; import org.apache.log4j.Logger; import scala.collection.Iterable; import scala.concurrent.duration.Duration; import static akka.actor.SupervisorStrategy.resume; /** * Created by gvagenas on 01/04/2017. */ public class RestcommSupervisorStrategy implements SupervisorStrategyConfigurator { private static Logger logger = Logger.getLogger(RestcommSupervisorStrategy.class); static final SupervisorStrategy.Directive strategy = resume(); static RestcommFaultToleranceStrategy defaultStrategy = new RestcommFaultToleranceStrategy(10, Duration.create("1 minute"), new RestcommFaultToleranceDecider()); @Override public SupervisorStrategy create() { return defaultStrategy; } public static SupervisorStrategy getStrategy() { return defaultStrategy; } private static class RestcommFaultToleranceStrategy extends OneForOneStrategy { public RestcommFaultToleranceStrategy(int maxNrOfRetries, Duration withinTimeRange, Function<Throwable, Directive> function) { super(maxNrOfRetries, withinTimeRange, function); } @Override public boolean handleFailure(ActorContext context, ActorRef child, Throwable cause, ChildRestartStats stats, Iterable<ChildRestartStats> children) { String msg = String.format("RestcommSupervisorStrategy, actor exception handling. Actor path %s, exception cause %s, default exception handling strategy %s", child.path().toString(), cause, strategy.toString()); logger.error(msg); return super.handleFailure(context, child, cause, stats, children); } // @Override // - 3rd the Supervisor Strategy will execute processFailure() method. Useful for cleanup or logging // public void processFailure(ActorContext context, boolean restart, ActorRef child, Throwable cause, ChildRestartStats stats, Iterable<ChildRestartStats> children) { // String msg = String.format("RestcommSupervisor, actor exception handling. Restart %s, actor path %s, cause %s,", restart, child.path().toString(), cause); // logger.error(msg); // super.processFailure(context, restart, child, cause, stats, children); // } } private static class RestcommFaultToleranceDecider implements Function<Throwable, SupervisorStrategy.Directive> { @Override // - 2nd the Supervisor strategy will execute the Decider apply() to check what to do with the exception public SupervisorStrategy.Directive apply(Throwable t) throws Exception { // String msg = String.format("Handling exception %s with default strategy to %s", t.getClass().getName(), strategy.toString()); // logger.error(msg); return strategy; // return resume(); // return restart(); // return stop(); // return escalate(); } } }
3,210
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommSupervisor.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/faulttolerance/RestcommSupervisor.java
package org.restcomm.connect.commons.faulttolerance; import akka.actor.ActorContext; import akka.actor.ActorRef; import akka.actor.ChildRestartStats; import akka.actor.OneForOneStrategy; import akka.actor.Props; import akka.actor.StopChild; import akka.actor.SupervisorStrategy; import akka.actor.Terminated; import akka.actor.UntypedActor; import akka.event.Logging; import akka.event.LoggingAdapter; import akka.japi.Function; import scala.collection.Iterable; import scala.concurrent.duration.Duration; import static akka.actor.SupervisorStrategy.resume; /** * Created by gvagenas on 22/02/2017. */ @Deprecated public class RestcommSupervisor extends UntypedActor { private LoggingAdapter logger = Logging.getLogger(getContext().system(), this); public RestcommSupervisor() {} RestcommFaultToleranceStrategy defaultStrategy = new RestcommFaultToleranceStrategy(10, Duration.create("1 minute"), new RestcommFaultToleranceDecider()); @Override public void onReceive(Object msg) throws Exception { try { final Class<?> klass = msg.getClass(); final ActorRef sender = getSender(); if (logger.isInfoEnabled()) { logger.info(" ********** RestcommSupervisor " + self().path() + " Processing Message: " + klass.getName()); } if (msg instanceof Props) { final ActorRef actor = getContext().actorOf((Props) msg); getContext().watch(actor); if (logger.isDebugEnabled()) { logger.debug("Created and watching actor: " + actor.path().toString()); } sender.tell(actor, getSelf()); } else if (msg instanceof Terminated) { if (logger.isDebugEnabled()) { logger.debug("Received Terminated message for actor {}", ((Terminated) msg).actor()); } } else if (msg instanceof StopChild) { StopChild stop = (StopChild) msg; final ActorRef child = stop.child(); getContext().unwatch(child); getContext().stop(child); if (logger.isDebugEnabled()) { String logmsg = String.format("RestcommSupervisor, actor %s stopped. Sender %s",child.path(), sender.path()); logger.debug(logmsg); } } else { unhandled(msg); } } catch (Exception e) { logger.error("Exception during the OnReceive methid of RestcommSupervisor, {}", e); } } @Override // - 1st the actor will try to get the supervisor strategy public SupervisorStrategy supervisorStrategy() { ActorRef sender = getSender(); return defaultStrategy; } private class RestcommFaultToleranceStrategy extends OneForOneStrategy { public RestcommFaultToleranceStrategy(int maxNrOfRetries, Duration withinTimeRange, Function<Throwable, Directive> function) { super(maxNrOfRetries, withinTimeRange, function); } @Override // - 3rd the Supervisor Strategy will execute processFailure() method. Useful for cleanup or logging public void processFailure(ActorContext context, boolean restart, ActorRef child, Throwable cause, ChildRestartStats stats, Iterable<ChildRestartStats> children) { String msg = String.format("RestcommSupervisor, actor exception handling. Restart %s, actor path %s, cause %s,", restart, child.path().toString(), cause); logger.error(msg); super.processFailure(context, restart, child, cause, stats, children); } } private class RestcommFaultToleranceDecider implements Function<Throwable, SupervisorStrategy.Directive> { @Override // - 2nd the Supervisor strategy will execute the Decider apply() to check what to do with the exception public SupervisorStrategy.Directive apply(Throwable t) throws Exception { logger.error("Handling exception {} will resume", t.getClass().getName()); return resume(); // return restart(); // return stop(); // return escalate(); } } }
4,243
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommRuntimeException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/exceptions/RestcommRuntimeException.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.exceptions; /** * Generic type of runtime exception that is handled centrally using exceptions * mappers. * * @author [email protected] - Orestis Tsakiridis */ public class RestcommRuntimeException extends RuntimeException { public RestcommRuntimeException() { } public RestcommRuntimeException(String message) { super(message); } public RestcommRuntimeException(String message, Throwable cause) { super(message, cause); } public RestcommRuntimeException(Throwable cause) { super(cause); } public RestcommRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
1,610
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CustomHttpClientBuilder.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/common/http/CustomHttpClientBuilder.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.common.http; import java.io.IOException; import java.net.InetSocketAddress; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.util.concurrent.TimeUnit; import org.apache.http.HttpHost; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.utils.HttpClientUtils; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.routing.HttpRoute; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.DefaultHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.conn.util.PublicSuffixMatcher; import org.apache.http.conn.util.PublicSuffixMatcherLoader; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager; import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor; import org.apache.http.nio.conn.NoopIOSessionStrategy; import org.apache.http.nio.conn.SchemeIOSessionStrategy; import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy; import org.apache.http.nio.reactor.IOReactorException; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContexts; import org.restcomm.connect.commons.configuration.sets.MainConfigurationSet; /** * * @author [email protected] (Orestis Tsakiridis) * */ public class CustomHttpClientBuilder { private CustomHttpClientBuilder() { } private static CloseableHttpClient defaultClient = null; private static CloseableHttpAsyncClient closeableHttpAsyncClient = null; public static synchronized void stopDefaultClient() { if (defaultClient != null) { HttpClientUtils.closeQuietly(defaultClient); defaultClient = null; } if (closeableHttpAsyncClient != null) { try { if(closeableHttpAsyncClient.isRunning()) closeableHttpAsyncClient.close(); } catch (IOException e) { } closeableHttpAsyncClient = null; } } public static synchronized CloseableHttpClient buildDefaultClient(MainConfigurationSet config) { if (defaultClient == null) { defaultClient = build(config); } return defaultClient; } public static synchronized CloseableHttpAsyncClient buildCloseableHttpAsyncClient(MainConfigurationSet config) { if (closeableHttpAsyncClient == null) { closeableHttpAsyncClient = buildAsync(config); closeableHttpAsyncClient.start(); } return closeableHttpAsyncClient; } public static CloseableHttpClient build(MainConfigurationSet config) { int timeoutConnection = config.getResponseTimeout(); return build(config, timeoutConnection); } private static CloseableHttpAsyncClient buildAsync(MainConfigurationSet config) { int timeoutConnection = config.getResponseTimeout(); return buildAsync(config, timeoutConnection); } private static CloseableHttpAsyncClient buildAsync(MainConfigurationSet config, int timeout) { HttpAsyncClientBuilder builder = HttpAsyncClients.custom(); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(timeout) .setConnectionRequestTimeout(config.getDefaultHttpConnectionRequestTimeout()) .setSocketTimeout(timeout) .setCookieSpec(CookieSpecs.STANDARD).build(); builder.setDefaultRequestConfig(requestConfig); SslMode mode = config.getSslMode(); SSLIOSessionStrategy sessionStrategy = null; if (mode == SslMode.strict) { sessionStrategy = buildStrictSSLIOSessionStrategy(); } else { sessionStrategy = buildAllowallSSLIOSessionStrategy(); } builder.setSSLStrategy(sessionStrategy); builder.setMaxConnPerRoute(config.getDefaultHttpMaxConnsPerRoute()); builder.setMaxConnTotal(config.getDefaultHttpMaxConns()); //builder.setConnectionTimeToLive(config.getDefaultHttpTTL(), TimeUnit.MILLISECONDS); if (config.getDefaultHttpRoutes() != null && config.getDefaultHttpRoutes().size() > 0) { Registry<SchemeIOSessionStrategy> reg = RegistryBuilder.<SchemeIOSessionStrategy>create() .register("http", NoopIOSessionStrategy.INSTANCE) .register("https", sessionStrategy) .build(); try { final PoolingNHttpClientConnectionManager poolingmgr = new PoolingNHttpClientConnectionManager( new DefaultConnectingIOReactor(), null, reg, null, null, config.getDefaultHttpTTL(), TimeUnit.MILLISECONDS); //ensure conn configuration is set again for new conn manager poolingmgr.setMaxTotal(config.getDefaultHttpMaxConns()); poolingmgr.setDefaultMaxPerRoute(config.getDefaultHttpMaxConnsPerRoute()); for (InetSocketAddress addr : config.getDefaultHttpRoutes().keySet()) { HttpRoute r = new HttpRoute(new HttpHost(addr.getHostName(), addr.getPort())); poolingmgr.setMaxPerRoute(r, config.getDefaultHttpRoutes().get(addr)); } builder.setConnectionManager(poolingmgr); } catch (IOReactorException e) { throw new RuntimeException("Error creating CloseableHttpAsyncClient", e); } } return builder.build(); } private static CloseableHttpClient build(MainConfigurationSet config, int timeout) { HttpClientBuilder builder = HttpClients.custom(); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(timeout) .setConnectionRequestTimeout(config.getDefaultHttpConnectionRequestTimeout()) .setSocketTimeout(timeout) .setCookieSpec(CookieSpecs.STANDARD).build(); builder.setDefaultRequestConfig(requestConfig); SslMode mode = config.getSslMode(); SSLConnectionSocketFactory sslsf = null; if (mode == SslMode.strict) { sslsf = buildStrictFactory(); } else { sslsf = buildAllowallFactory(); } builder.setSSLSocketFactory(sslsf); builder.setMaxConnPerRoute(config.getDefaultHttpMaxConnsPerRoute()); builder.setMaxConnTotal(config.getDefaultHttpMaxConns()); builder.setConnectionTimeToLive(config.getDefaultHttpTTL(), TimeUnit.MILLISECONDS); if (config.getDefaultHttpRoutes() != null && config.getDefaultHttpRoutes().size() > 0) { if (sslsf == null) { //strict mode with no system https properties //taken from apache buider code PublicSuffixMatcher publicSuffixMatcherCopy = PublicSuffixMatcherLoader.getDefault(); DefaultHostnameVerifier hostnameVerifierCopy = new DefaultHostnameVerifier(publicSuffixMatcherCopy); sslsf = new SSLConnectionSocketFactory( SSLContexts.createDefault(), hostnameVerifierCopy); } Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslsf) .build(); final PoolingHttpClientConnectionManager poolingmgr = new PoolingHttpClientConnectionManager( reg, null, null, null, config.getDefaultHttpTTL(), TimeUnit.MILLISECONDS); //ensure conn configuration is set again for new conn manager poolingmgr.setMaxTotal(config.getDefaultHttpMaxConns()); poolingmgr.setDefaultMaxPerRoute(config.getDefaultHttpMaxConnsPerRoute()); for (InetSocketAddress addr : config.getDefaultHttpRoutes().keySet()) { HttpRoute r = new HttpRoute(new HttpHost(addr.getHostName(), addr.getPort())); poolingmgr.setMaxPerRoute(r, config.getDefaultHttpRoutes().get(addr)); } builder.setConnectionManager(poolingmgr); } return builder.build(); } private static String[] getSSLPrototocolsFromSystemProperties() { String protocols = System.getProperty("jdk.tls.client.protocols"); if (protocols == null) { protocols = System.getProperty("https.protocols"); } if (protocols != null) { String[] protocolsArray = protocols.split(","); return protocolsArray; } return null; } private static SSLConnectionSocketFactory buildStrictFactory() { try { SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( SSLContextBuilder.create().build(), getSSLPrototocolsFromSystemProperties(), null, // new String[]{"TLS_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", "TLS_RSA_WITH_AES_128_CBC_SHA256", "TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA256", "TLS_RSA_WITH_AES_256_CBC_SHA"}, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return sslsf; } catch (KeyManagementException | NoSuchAlgorithmException e) { throw new RuntimeException("Error creating HttpClient", e); } } private static SSLConnectionSocketFactory buildAllowallFactory() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build(), getSSLPrototocolsFromSystemProperties(), null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return sslsf; } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new RuntimeException("Error creating HttpClient", e); } } private static SSLIOSessionStrategy buildStrictSSLIOSessionStrategy(){ try { SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy( SSLContextBuilder.create().build(), getSSLPrototocolsFromSystemProperties(), null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return sessionStrategy; } catch (KeyManagementException | NoSuchAlgorithmException e) { throw new RuntimeException("Error creating HttpAsycClient", e); } } private static SSLIOSessionStrategy buildAllowallSSLIOSessionStrategy(){ try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy( builder.build(), getSSLPrototocolsFromSystemProperties(), null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); return sessionStrategy; } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new RuntimeException("Error creating HttpAsycClient", e); } } }
13,511
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateCallType.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/telephony/CreateCallType.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.commons.telephony; public enum CreateCallType { CLIENT, PSTN, SIP, USSD }
1,026
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProxyRule.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/telephony/ProxyRule.java
package org.restcomm.connect.commons.telephony; /** * Created by gvagenas on 26/06/2017. */ public class ProxyRule { private final String fromUri; private final String toUri; private final String username; private final String password; public ProxyRule (final String fromUri, final String toUri, final String username, final String password) { this.fromUri = fromUri; this.toUri = toUri; this.username = username; this.password = password; } public String getFromUri () { return fromUri; } public String getToUri () { return toUri; } public String getPassword () { return password; } public String getUsername () { return username; } }
766
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Sid.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/dao/Sid.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.commons.dao; import java.util.UUID; import java.util.regex.Pattern; import org.apache.shiro.crypto.hash.Md5Hash; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.configuration.RestcommConfiguration; /** * @author [email protected] (Thomas Quintana) * @author [email protected] (Maria Farooq) */ @Immutable public final class Sid { public static final Pattern pattern = Pattern.compile("[a-zA-Z0-9]{34}"); public static final Pattern callSidPattern = Pattern.compile("ID[a-zA-Z0-9]{32}-CA[a-zA-Z0-9]{32}"); private final String id; public enum Type { ACCOUNT, APPLICATION, ANNOUNCEMENT, CALL, CLIENT, CONFERENCE, GATEWAY, INVALID, NOTIFICATION, PHONE_NUMBER, RECORDING, REGISTRATION, SHORT_CODE, SMS_MESSAGE, TRANSCRIPTION, INSTANCE, EXTENSION_CONFIGURATION, GEOLOCATION, ORGANIZATION, PROFILE }; private static final Sid INVALID_SID = new Sid("IN00000000000000000000000000000000"); public Sid(final String id) throws IllegalArgumentException { super(); //https://github.com/RestComm/Restcomm-Connect/issues/1907 if (callSidPattern.matcher(id).matches() || pattern.matcher(id).matches()) { this.id = id; } else { throw new IllegalArgumentException(id + " is an INVALID_SID sid value."); } } @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (getClass() != object.getClass()) { return false; } final Sid other = (Sid) object; if (!toString().equals(other.toString())) { return false; } return true; } // Issue 108: https://bitbucket.org/telestax/telscale-restcomm/issue/108/account-sid-could-be-a-hash-of-the public static Sid generate(final Type type, String string) { String token = new Md5Hash(string).toString(); switch (type) { case ACCOUNT: { return new Sid("AC" + token); } default: { return generate(type); } } } public static Sid generate(final Type type) { final String uuid = UUID.randomUUID().toString().replace("-", ""); switch (type) { case ACCOUNT: { return new Sid("AC" + uuid); } case APPLICATION: { return new Sid("AP" + uuid); } case ANNOUNCEMENT: { return new Sid("AN" + uuid); } case CALL: { //https://github.com/RestComm/Restcomm-Connect/issues/1907 return new Sid(RestcommConfiguration.getInstance().getMain().getInstanceId() + "-CA" + uuid); } case CLIENT: { return new Sid("CL" + uuid); } case CONFERENCE: { return new Sid("CF" + uuid); } case GATEWAY: { return new Sid("GW" + uuid); } case INVALID: { return INVALID_SID; } case NOTIFICATION: { return new Sid("NO" + uuid); } case PHONE_NUMBER: { return new Sid("PN" + uuid); } case RECORDING: { return new Sid("RE" + uuid); } case REGISTRATION: { return new Sid("RG" + uuid); } case SHORT_CODE: { return new Sid("SC" + uuid); } case SMS_MESSAGE: { return new Sid("SM" + uuid); } case TRANSCRIPTION: { return new Sid("TR" + uuid); } case INSTANCE: { return new Sid("ID" + uuid); } case EXTENSION_CONFIGURATION: { return new Sid("EX" + uuid); } case GEOLOCATION: { return new Sid("GL" + uuid); } case ORGANIZATION: { return new Sid("OR" + uuid); } case PROFILE: { return new Sid("PR" + uuid); } default: { return null; } } } @Override public int hashCode() { final int prime = 5; int result = 1; result = prime * result + id.hashCode(); return result; } @Override public String toString() { return id; } }
5,501
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MessageError.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/dao/MessageError.java
package org.restcomm.connect.commons.dao; /** * @author mariafarooq * */ public enum MessageError { QUEUE_OVERFLOW (30001, "Queue overflow"), ACCOUNT_SUSPENDED (30002, "Account suspended"), UNREACHABLE_DESTINATION_HANDSET (30003, "Unreachable destination handset"), MESSAGE_BLOCKED (30004, "Message blocked"), UNKNOWN_DESTINATION_HANDSET (30005, "Unknown destination handset"), LANDLINE_OR_UNREACHABLE_CARRIER (30006, "Landline or unreachable carrier"), CARRIER_VIOLATION (30007, "Carrier violation"), UNKNOWN_ERROR (30008, "Unknown error"), MISSING_SEGMENT (30009, "Missing segment"), MESSAGE_PRICE_EXCEEDS_MAX_PRICE (30010, "Message price exceeds max price."); private final Integer errorCode; private final String errorMessage; private MessageError(final Integer errorCode, final String errorMessage) { this.errorCode = errorCode; this.errorMessage = errorMessage; } public Integer getErrorCode() { return errorCode; } public String getErrorMessage() { return errorMessage; } public static MessageError getErrorValue(final Integer errorCode) { final MessageError[] values = values(); for (final MessageError value : values) { if (value.getErrorCode().equals(errorCode)) { return value; } } throw new IllegalArgumentException(errorCode + " is not a valid errorCode."); } }
1,478
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ObjectInstantiationException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/loader/ObjectInstantiationException.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.loader; /** * @author [email protected] (Thomas Quintana) */ public final class ObjectInstantiationException extends Exception { private static final long serialVersionUID = 1L; public ObjectInstantiationException() { super(); } public ObjectInstantiationException(final String message) { super(message); } public ObjectInstantiationException(final Throwable cause) { super(cause); } public ObjectInstantiationException(final String message, final Throwable cause) { super(message, cause); } }
1,425
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ObjectFactory.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/loader/ObjectFactory.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.loader; /** * @author [email protected] (Thomas Quintana) */ public final class ObjectFactory { private final ClassLoader loader; public ObjectFactory() { super(); loader = getClass().getClassLoader(); } public ObjectFactory(final ClassLoader loader) { super(); this.loader = loader; } public Object getObjectInstance(final String name) throws ObjectInstantiationException { try { final Class<?> klass = loader.loadClass(name); return klass.newInstance(); } catch (final ClassNotFoundException exception) { throw new ObjectInstantiationException(exception); } catch (final InstantiationException exception) { throw new ObjectInstantiationException(exception); } catch (final IllegalAccessException exception) { throw new ObjectInstantiationException(exception); } } }
1,790
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Observe.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/patterns/Observe.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.patterns; import akka.actor.ActorRef; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class Observe extends AbstractObserverMessage { public Observe(final ActorRef observer) { super(observer); } }
1,177
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StopObserving.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/patterns/StopObserving.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.patterns; import akka.actor.ActorRef; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class StopObserving extends AbstractObserverMessage { public StopObserving(final ActorRef observer) { super(observer); } public StopObserving() { this(null); } }
1,246
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AbstractObserverMessage.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/patterns/AbstractObserverMessage.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.patterns; import akka.actor.ActorRef; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @NotThreadSafe public abstract class AbstractObserverMessage { private final ActorRef observer; public AbstractObserverMessage(final ActorRef observer) { super(); this.observer = observer; } public ActorRef observer() { return observer; } }
1,317
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TooManyObserversException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/patterns/TooManyObserversException.java
package org.restcomm.connect.commons.patterns; public final class TooManyObserversException extends Exception { private static final long serialVersionUID = 1L; public TooManyObserversException(String message) { super(message); } public TooManyObserversException(Throwable cause) { super(cause); } public TooManyObserversException(final String message, final Throwable cause) { super(message, cause); } }
461
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StandardResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/patterns/StandardResponse.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.patterns; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @NotThreadSafe public abstract class StandardResponse<T> { private final boolean succeeded; private final Throwable cause; private final String message; private final T object; public StandardResponse() { super(); this.succeeded = true; this.cause = null; this.message = null; this.object = null; } public StandardResponse(final T object) { super(); this.succeeded = true; this.cause = null; this.message = null; this.object = object; } public StandardResponse(final Throwable cause) { super(); this.succeeded = false; this.cause = cause; this.message = null; this.object = null; } public StandardResponse(final Throwable cause, final String message) { super(); this.succeeded = false; this.cause = cause; this.message = message; this.object = null; } public Throwable cause() { return cause; } public String error() { return message; } public T get() { return object; } public boolean succeeded() { return succeeded; } @Override public String toString() { return (new StringBuffer("StandardResponse [succeeded=").append(succeeded).append(", cause=").append(cause) .append(", message=").append(message).append(", object=").append(object).append("]")).toString(); } }
2,485
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Observing.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/patterns/Observing.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.patterns; import akka.actor.ActorRef; /** * @author [email protected] (Thomas Quintana) */ public final class Observing extends StandardResponse<ActorRef> { public Observing(final ActorRef observable) { super(observable); } public Observing(final Throwable cause) { super(cause); } public Observing(Throwable cause, String message) { super(cause, message); } }
1,274
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TransitionFailedException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/TransitionFailedException.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.fsm; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @NotThreadSafe public final class TransitionFailedException extends Exception { private static final long serialVersionUID = 7560694777499972921L; private final Object event; private final Transition transition; public TransitionFailedException(final String message, final Object event, final Transition transition) { super(message); this.event = event; this.transition = transition; } public TransitionFailedException(final Throwable cause, final Object event, final Transition transition) { super(cause); this.event = event; this.transition = transition; } public Object getEvent() { return event; } public Transition getTransition() { return transition; } }
1,766
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TransitionEndListener.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/TransitionEndListener.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2017, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it andor modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but OUT ANY WARRANTY; out even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along this program. If not, see <http:www.gnu.orglicenses> */ package org.restcomm.connect.commons.fsm; /** * @author [email protected] (Oleg Agafonov) */ public interface TransitionEndListener { void onTransitionEnd(State was, State is, Object event); }
998
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
FiniteStateMachine.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/FiniteStateMachine.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.fsm; import static com.google.common.base.Preconditions.checkNotNull; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; import com.google.common.collect.ImmutableMap; /** * @author [email protected] (Thomas Quintana) */ @NotThreadSafe public class FiniteStateMachine { private final ImmutableMap<State, Map<State, Transition>> transitions; private State state; private TransitionEndListener transitionEndListener; public FiniteStateMachine(final State initial, final Set<Transition> transitions) { super(); checkNotNull(initial, "The initial state for a finite state machine can not be null."); checkNotNull(transitions, "A finite state machine can not be created with transitions set to null."); this.state = initial; this.transitions = toImmutableMap(transitions); } public State state() { return state; } public void addTransitionEndListener(TransitionEndListener transitionEndListener) { this.transitionEndListener = transitionEndListener; } public void transition(final Object event, final State target) throws TransitionFailedException, TransitionNotFoundException, TransitionRollbackException { checkNotNull(event, "The message passed can not be null."); checkNotNull(target, "The target state can not be null"); if (transitions.get(state) == null || !transitions.get(state).containsKey(target)) { final StringBuilder buffer = new StringBuilder(); buffer.append("No transition could be found from a(n) ").append(state.getId()).append(" state to a(n) ") .append(target.getId()).append(" state."); throw new TransitionNotFoundException(buffer.toString(), event, state, target); } final Transition transition = transitions.get(state).get(target); final Guard guard = transition.getGuard(); boolean accept = true; if (guard != null) { try { accept = guard.accept(event, transition); } catch (final Exception exception) { throw new TransitionFailedException(exception, event, transition); } } if (accept) { // Execute action before leaving previous state (post-processing) final Action actionOnExit = state.getActionOnExit(); if (actionOnExit != null) { try { actionOnExit.execute(event); } catch (final Exception exception) { throw new TransitionFailedException(exception, event, transition); } } // Execute action before entering new state (pre-processing) final Action actionOnEnter = target.getActionOnEnter(); if (actionOnEnter != null) { try { actionOnEnter.execute(event); } catch (final Exception exception) { throw new TransitionFailedException(exception, event, transition); } } // Move to a new state State source = state; state = target; // Execute action after entering new state (processing) final Action actionOnState = target.getActionOnState(); if (actionOnState != null) { try { actionOnState.execute(event); } catch (final Exception exception) { throw new TransitionFailedException(exception, event, transition); } } if (transitionEndListener != null) { transitionEndListener.onTransitionEnd(source, target, event); } } else { final StringBuilder buffer = new StringBuilder(); buffer.append("The condition guarding a transition from a(n) ").append(transition.getStateOnEnter().getId()) .append(" state to a(n) ").append(transition.getStateOnExit().getId()).append(" state has failed."); throw new TransitionRollbackException(buffer.toString(), event, transition); } } private ImmutableMap<State, Map<State, Transition>> toImmutableMap(final Set<Transition> transitions) { final Map<State, Map<State, Transition>> map = new HashMap<State, Map<State, Transition>>(); for (final Transition transition : transitions) { final State stateOnEnter = transition.getStateOnEnter(); if (!map.containsKey(stateOnEnter)) { map.put(stateOnEnter, new HashMap<State, Transition>()); } final State stateOnExit = transition.getStateOnExit(); map.get(stateOnEnter).put(stateOnExit, transition); } return ImmutableMap.copyOf(map); } }
5,791
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
State.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/State.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.fsm; import static com.google.common.base.Preconditions.*; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public class State { private final Action actionOnEnter; private final Action actionOnState; private final Action actionOnExit; private final String id; public State(final String id, final Action actionOnEnter, final Action actionOnState, final Action actionOnExit) { super(); checkNotNull(id, "A state can not have a null value for id."); this.actionOnEnter = actionOnEnter; this.actionOnState = actionOnState; this.actionOnExit = actionOnExit; this.id = id; } public State(final String id, final Action actionOnEnter, final Action actionOnExit) { this(id, actionOnEnter, null, actionOnExit); } public State(final String id, final Action actionOnState) { this(id, null, actionOnState, null); } @Override public boolean equals(final Object object) { if (object == null) { return false; } else if (this == object) { return true; } else if (getClass() != object.getClass()) { return false; } final State state = (State) object; if (!id.equals(state.getId())) { return false; } return true; } public Action getActionOnEnter() { return actionOnEnter; } public Action getActionOnState() { return actionOnState; } public Action getActionOnExit() { return actionOnExit; } public String getId() { return id; } @Override public int hashCode() { final int prime = 5; int result = 1; result = prime * result + id.hashCode(); return result; } @Override public String toString() { return id; } }
2,804
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Transition.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/Transition.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.fsm; import static com.google.common.base.Preconditions.*; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class Transition { private final Guard guard; private final State stateOnEnter; private final State stateOnExit; public Transition(final State stateOnEnter, final State stateOnExit, final Guard guard) { super(); checkNotNull(stateOnEnter, "A transition can not have a null value for the state on enter."); checkNotNull(stateOnExit, "A transition can not have a null value for the state on exit."); this.guard = guard; this.stateOnEnter = stateOnEnter; this.stateOnExit = stateOnExit; } public Transition(final State stateOnEnter, final State stateOnExit) { this(stateOnEnter, stateOnExit, null); } @Override public boolean equals(final Object object) { if (this == object) { return true; } else if (object == null) { return false; } else if (getClass() != object.getClass()) { return false; } final Transition transition = (Transition) object; if (!stateOnEnter.equals(transition.getStateOnEnter())) { return false; } if (!stateOnExit.equals(transition.getStateOnExit())) { return false; } return true; } public Guard getGuard() { return guard; } public State getStateOnEnter() { return stateOnEnter; } public State getStateOnExit() { return stateOnExit; } @Override public int hashCode() { final int prime = 5; int result = 1; result = prime * result + stateOnEnter.hashCode(); result = prime * result + stateOnExit.hashCode(); return result; } }
2,759
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TransitionNotFoundException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/TransitionNotFoundException.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.fsm; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @NotThreadSafe public class TransitionNotFoundException extends Exception { private static final long serialVersionUID = -3062590067048473837L; private final Object event; private final State currrent; private final State target; public TransitionNotFoundException(final String message, final Object event, final State current, final State target) { super(message); this.event = event; this.currrent = current; this.target = target; } public TransitionNotFoundException(final Throwable cause, final Object event, final State current, final State target) { super(cause); this.event = event; this.currrent = current; this.target = target; } public State getCurrentState() { return currrent; } public Object getEvent() { return event; } public State getTargetState() { return target; } }
1,927
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Guard.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/Guard.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.fsm; /** * @author [email protected] (Thomas Quintana) */ public interface Guard { boolean accept(Object message, Transition transition) throws Exception; }
1,020
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TransitionRollbackException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/TransitionRollbackException.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.fsm; import org.restcomm.connect.commons.annotations.concurrency.NotThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @NotThreadSafe public final class TransitionRollbackException extends Exception { private static final long serialVersionUID = 1290752844732660182L; private final Object event; private final Transition transition; public TransitionRollbackException(final String message, final Object event, final Transition transition) { super(message); this.event = event; this.transition = transition; } public TransitionRollbackException(final Throwable cause, final Object event, final Transition transition) { super(cause); this.event = event; this.transition = transition; } public Object getEvent() { return event; } public Transition getTransition() { return transition; } }
1,772
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Action.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/fsm/Action.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.fsm; /** * @author [email protected] (Thomas Quintana) */ public interface Action { void execute(Object message) throws Exception; }
996
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
S3AccessTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/amazonS3/S3AccessTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.amazonS3; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.HttpMethod; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.S3ClientOptions; import com.amazonaws.services.s3.model.DeleteObjectRequest; import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest; import com.amazonaws.services.s3.model.ObjectMetadata; import com.amazonaws.services.s3.model.PutObjectRequest; import com.amazonaws.services.s3.model.StorageClass; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import org.joda.time.DateTime; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import javax.activation.MimetypesFileTypeMap; import java.io.File; import java.net.URI; import java.net.URISyntaxException; import java.util.Calendar; import java.util.Date; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public class S3AccessTool { private static Logger logger = Logger.getLogger(S3AccessTool.class); private String accessKey; private String securityKey; private String bucketName; private String folder; private String bucketRegion; private boolean reducedRedundancy; private int minutesToRetainPublicUrl; private boolean removeOriginalFile; private boolean testing; private String testingUrl; private AmazonS3 s3client; private int maxDelay; public S3AccessTool(final String accessKey, final String securityKey, final String bucketName, final String folder, final boolean reducedRedundancy, final int minutesToRetainPublicUrl, final boolean removeOriginalFile, final String bucketRegion, final boolean testing, final String testingUrl) { this.accessKey = accessKey; this.securityKey = securityKey; this.bucketName = bucketName; this.folder = folder; this.reducedRedundancy = reducedRedundancy; this.minutesToRetainPublicUrl = minutesToRetainPublicUrl; this.removeOriginalFile = removeOriginalFile; this.bucketRegion = bucketRegion; this.testing = testing; this.testingUrl = testingUrl; this.maxDelay = RestcommConfiguration.getInstance().getMain().getRecordingMaxDelay(); } public AmazonS3 getS3client() { BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, securityKey); if (testing && (!testingUrl.isEmpty() || !testingUrl.equals(""))) { s3client = new AmazonS3Client(awsCreds); s3client.setRegion(Region.getRegion(Regions.fromName(bucketRegion))); s3client.setEndpoint(testingUrl); s3client.setS3ClientOptions(S3ClientOptions.builder().setPathStyleAccess(true).disableChunkedEncoding().build()); } else { s3client = AmazonS3ClientBuilder.standard().withRegion(Regions.fromName(bucketRegion)) .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build(); } return s3client; } public boolean uploadFile(final String fileToUpload) { if (s3client == null) { s3client = getS3client(); } if(logger.isInfoEnabled()){ logger.info("S3 Region: "+bucketRegion.toString()); } try { URI fileUri = URI.create(fileToUpload); File file = new File(fileUri); String bucket = prepareBucket(); if (logger.isInfoEnabled()) { logger.info("File to upload to S3: " + fileUri.toString()); } //For statistics and logs DateTime start, end; double waitDuration; if (fileExists(file)) { start = DateTime.now(); PutObjectRequest putRequest = new PutObjectRequest(bucket, file.getName(), file); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(new MimetypesFileTypeMap().getContentType(file)); putRequest.setMetadata(metadata); if (reducedRedundancy) putRequest.setStorageClass(StorageClass.ReducedRedundancy); s3client.putObject(putRequest); if (removeOriginalFile) { removeLocalFile(file); } end = DateTime.now(); waitDuration = (end.getMillis() - start.getMillis())/1000; if (waitDuration > maxDelay || testing) { if (logger.isInfoEnabled()) { String msg = String.format("File %s uploaded to S3 successfully. Upload time %,.2f sec", fileUri.toString(), waitDuration); logger.info(msg); } } return true; } else { String msg = String.format("Recording file \"%s\" doesn't exists ",file.getPath()); logger.error(msg); return false; } } catch (AmazonServiceException ase) { logger.error("Caught an AmazonServiceException"); logger.error("Error Message: " + ase.getMessage()); logger.error("HTTP Status Code: " + ase.getStatusCode()); logger.error("AWS Error Code: " + ase.getErrorCode()); logger.error("Error Type: " + ase.getErrorType()); logger.error("Request ID: " + ase.getRequestId()); return false; } catch (AmazonClientException ace) { logger.error("Caught an AmazonClientException "); logger.error("Error Message: " + ace.getMessage()); return false; } } private String prepareBucket () { StringBuffer bucket = new StringBuffer(); bucket.append(bucketName); if (folder != null && !folder.isEmpty()) bucket.append("/").append(folder); return bucket.toString(); } private boolean fileExists(final File file) { if (file.exists()) { return true; } else { return FileUtils.waitFor(file, 2); } } public URI getS3Uri(final String fileToUpload) { if (s3client == null) { s3client = getS3client(); } String bucket = prepareBucket(); URI fileUri = URI.create(fileToUpload); File file = new File(fileUri); URI recordingS3Uri = null; try { recordingS3Uri = s3client.getUrl(bucket, file.getName()).toURI(); } catch (URISyntaxException e) { logger.error("Problem during creation of S3 URI"); } if (logger.isInfoEnabled()) { logger.info("Created S3Uri for file: " + fileUri.toString()); } return recordingS3Uri; } public URI getPublicUrl (String fileName) throws URISyntaxException { if (s3client == null) { s3client = getS3client(); } Date date = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.MINUTE, minutesToRetainPublicUrl); if (logger.isInfoEnabled()) { final String msg = String.format("Prepared amazon s3 public url valid for %s minutes for recording: %s",minutesToRetainPublicUrl, fileName); logger.info(msg); } date = cal.getTime(); String bucket = prepareBucket(); GeneratePresignedUrlRequest generatePresignedUrlRequestGET = new GeneratePresignedUrlRequest(bucket, fileName); generatePresignedUrlRequestGET.setMethod(HttpMethod.GET); generatePresignedUrlRequestGET.setExpiration(date); return s3client.generatePresignedUrl(generatePresignedUrlRequestGET).toURI(); } private void removeLocalFile(final File file) { if (!file.delete()) { if(logger.isInfoEnabled()){ logger.info("Error while trying to delete the file: "+file.toString()); } } } public void removeS3Uri(String recordingSid) { if (s3client == null) { s3client = getS3client(); } String bucket = prepareBucket(); String recordingKey = recordingSid.concat(".wav"); if (logger.isInfoEnabled()) { logger.info("Bucket: "+bucket+", object key to remove: "+recordingKey); } //S3 URI: https://hastaging-restcomm-as-a-service.s3.amazonaws.com/REffff84e4fa224d89b213ff25362a2cb1.wav s3client.deleteObject(new DeleteObjectRequest(bucket, recordingKey)); } }
9,745
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RecordingSecurityLevel.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/amazonS3/RecordingSecurityLevel.java
package org.restcomm.connect.commons.amazonS3; /** * Created by gvagenas on 14/03/2017. */ public enum RecordingSecurityLevel { NONE("none"),REDIRECT("redirect"),SECURE("secure"); private final String text; private RecordingSecurityLevel(final String text) { this.text = text; } }
310
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommConfiguration.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/RestcommConfiguration.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.configuration.sets.CacheConfigurationSet; import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet; import org.restcomm.connect.commons.configuration.sets.MainConfigurationSet; import org.restcomm.connect.commons.configuration.sets.impl.CacheConfigurationSetImpl; import org.restcomm.connect.commons.configuration.sets.impl.ConfigurationSet; import org.restcomm.connect.commons.configuration.sets.impl.MainConfigurationSetImpl; import org.restcomm.connect.commons.configuration.sets.impl.MgAsrConfigurationSet; import org.restcomm.connect.commons.configuration.sets.impl.RcmlserverConfigurationSetImpl; import org.restcomm.connect.commons.configuration.sources.ApacheConfigurationSource; /** * Singleton like class that provides access to ConfigurationSets. * Use get+() functions to access configuration sets. * * @author [email protected] (Orestis Tsakiridis) * */ public class RestcommConfiguration { private final Map<String,ConfigurationSet> sets = new ConcurrentHashMap<String,ConfigurationSet>(); public RestcommConfiguration() { // No ConfigurationSets added. You'll have to it manually with addConfigurationSet(). } public RestcommConfiguration(Configuration apacheConf) { // addConfigurationSet("main", new MainConfigurationSet( new ApacheConfigurationSource(apacheConf))); ApacheConfigurationSource apacheCfgSrc = new ApacheConfigurationSource(apacheConf); addConfigurationSet("main", new MainConfigurationSetImpl(apacheCfgSrc)); addConfigurationSet("cache", new CacheConfigurationSetImpl(apacheCfgSrc)); addConfigurationSet("rcmlserver", new RcmlserverConfigurationSetImpl(apacheCfgSrc)); addConfigurationSet("mg-asr", new MgAsrConfigurationSet(apacheCfgSrc, apacheConf)); // addConfigurationSet("identity", new IdentityConfigurationSet( new DbConfigurationSource(dbConf))); // ... } public void addConfigurationSet(String setKey, ConfigurationSet set ) { sets.put(setKey, set); } public <T extends ConfigurationSet> T get(String key, Class <T> type) { return type.cast(sets.get(key)); } public MainConfigurationSet getMain() { return (MainConfigurationSet) sets.get("main"); } /* public void reloadMain() { MainConfigurationSet oldMain = getMain(); MainConfigurationSet newMain = new MainConfigurationSet(oldMain.getSource()); sets.put("main", newMain); } */ // define getters for additional ConfigurationSets here // ... public CacheConfigurationSet getCache() { return (CacheConfigurationSet) sets.get("cache"); } public RcmlserverConfigurationSet getRcmlserver() { return (RcmlserverConfigurationSet) sets.get("rcmlserver"); } public MgAsrConfigurationSet getMgAsr() { return (MgAsrConfigurationSet) sets.get("mg-asr"); } // singleton stuff private static RestcommConfiguration instance; public static RestcommConfiguration createOnce(Configuration apacheConf) { synchronized (RestcommConfiguration.class) { if (instance == null) { instance = new RestcommConfiguration(apacheConf); } } return instance; } public static RestcommConfiguration getInstance() { if (instance == null) throw new IllegalStateException("RestcommConfiguration has not been initialized."); return instance; } }
4,525
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApacheConfigurationSource.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sources/ApacheConfigurationSource.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sources; import org.apache.commons.configuration.Configuration; /** * * @author [email protected] (Orestis Tsakiridis) * */ public class ApacheConfigurationSource implements ConfigurationSource { private final Configuration apacheConfiguration; public ApacheConfigurationSource(Configuration apacheConfiguration) { super(); this.apacheConfiguration = apacheConfiguration; } @Override public String getProperty(String key) { return apacheConfiguration.getString(key); } @Override public String getProperty (String key, String defValue) { return apacheConfiguration.getString(key, defValue); } }
1,550
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConfigurationSource.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sources/ConfigurationSource.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sources; /** * * @author [email protected] (Orestis Tsakiridis) * */ public interface ConfigurationSource { String getProperty(String key); String getProperty (String key, String defValue); }
1,081
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MainConfigurationSet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sets/MainConfigurationSet.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sets; import org.restcomm.connect.commons.common.http.SslMode; import java.net.InetSocketAddress; import java.util.Map; /** * @author [email protected] - Orestis Tsakiridis */ public interface MainConfigurationSet { SslMode getSslMode(); int getResponseTimeout(); Integer getDefaultHttpConnectionRequestTimeout(); Integer getDefaultHttpMaxConns(); Integer getDefaultHttpMaxConnsPerRoute(); Integer getDefaultHttpTTL(); Map<InetSocketAddress,Integer> getDefaultHttpRoutes(); boolean isUseHostnameToResolveRelativeUrls(); String getHostname(); boolean getBypassLbForClients(); void setInstanceId(String instanceId); String getInstanceId(); String getApiVersion(); int getRecordingMaxDelay (); long getConferenceTimeout(); void setConferenceTimeout(long conferenceTimeout); String getClientAlgorithm(); String getClientQOP(); String getClearTextPasswordAlgorithm(); String getRecordingPath(); }
1,873
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RcmlserverConfigurationSet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sets/RcmlserverConfigurationSet.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sets; /** * @author [email protected] - Orestis Tsakiridis */ public interface RcmlserverConfigurationSet { String getApiPath(); String getBaseUrl(); Boolean getNotify(); Integer getTimeout(); // how much to wait for response to a notification request before giving up Integer getTimeoutPerNotification(); // now much more to increase timeout for each notification that is sent }
1,266
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CacheConfigurationSet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sets/CacheConfigurationSet.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sets; /** * @author [email protected] - Orestis Tsakiridis */ public interface CacheConfigurationSet { boolean isNoWavCache(); String getCachePath(); String getCacheUri(); }
1,069
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RcmlserverConfigurationSetImpl.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sets/impl/RcmlserverConfigurationSetImpl.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sets.impl; import org.apache.commons.lang.StringUtils; import org.restcomm.connect.commons.configuration.sets.RcmlserverConfigurationSet; import org.restcomm.connect.commons.configuration.sources.ConfigurationSource; /** * @author [email protected] - Orestis Tsakiridis */ public class RcmlserverConfigurationSetImpl extends ConfigurationSet implements RcmlserverConfigurationSet { private static final String BASE_URL_KEY = "rcmlserver.base-url"; private static final String API_PATH_KEY = "rcmlserver.api-path"; private static final String NOTIFY_KEY = "rcmlserver.notifications"; private static final String TIMEOUT_KEY = "rcmlserver.timeout"; private static final String TIMEOUT_PER_NOTIFICATION_KEY = "rcmlserver.timeout-per-notification"; private String baseUrl = null; private String apiPath = null; private Boolean notify = false; private Integer timeout = 5000; private Integer timeoutPerNotification = 500; public RcmlserverConfigurationSetImpl(ConfigurationSource source) { super(source); String value = source.getProperty(BASE_URL_KEY); if ( !StringUtils.isEmpty(value) ) { value = value.trim(); if (value.endsWith("/")) // remove trailing '/' if present value = value.substring(0,value.length()-2); this.baseUrl = value; } value = source.getProperty(API_PATH_KEY); if ( !StringUtils.isEmpty(value) ) { value = value.trim(); if (value.endsWith("/")) // remove trailing '/' if present value = value.substring(0,value.length()-2); this.apiPath = value; } value = source.getProperty(NOTIFY_KEY); try { this.notify = Boolean.parseBoolean(value); } catch (Exception e) {} value = source.getProperty(TIMEOUT_KEY); try { this.timeout = Integer.parseInt(value); } catch (Exception e) {} value = source.getProperty(TIMEOUT_PER_NOTIFICATION_KEY); try { this.timeoutPerNotification= Integer.parseInt(value); } catch (Exception e) {} } public RcmlserverConfigurationSetImpl(ConfigurationSource source, String baseUrl, Boolean notify, Integer timeout, Integer timeoutPerNotification) { super(source); this.baseUrl = baseUrl; this.notify = notify; this.timeout = timeout; this.timeoutPerNotification = timeoutPerNotification; } @Override public String getBaseUrl() { return baseUrl; } @Override public String getApiPath() { return apiPath; } @Override public Boolean getNotify() { return notify; } @Override public Integer getTimeout() { return this.timeout; } @Override public Integer getTimeoutPerNotification() { return this.timeoutPerNotification; } }
3,798
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MgAsrConfigurationSet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sets/impl/MgAsrConfigurationSet.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sets.impl; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.configuration.sources.ConfigurationSource; import java.util.Collections; import java.util.List; /** * Created by gdubina on 26.06.17. */ public class MgAsrConfigurationSet extends ConfigurationSet { private final List<String> drivers; private final String defaultDriver; private final List<String> languages; private final String defaultLanguage; private final int asrMRT; private final int defaultGatheringTimeout; public MgAsrConfigurationSet(ConfigurationSource source, Configuration config) { super(source); drivers = Collections.unmodifiableList(config.getList("runtime-settings.mg-asr-drivers.driver")); defaultDriver = config.getString("runtime-settings.mg-asr-drivers[@default]"); languages = Collections.unmodifiableList(config.getList("runtime-settings.asr-languages.language")); defaultLanguage = config.getString("runtime-settings.asr-languages[@default]"); asrMRT = config.containsKey("runtime-settings.asr-mrt-timeout") ? config.getInt("runtime-settings.asr-mrt-timeout") : 60; defaultGatheringTimeout = config.containsKey("runtime-settings.default-gathering-timeout") ? config.getInt("runtime-settings.default-gathering-timeout") : 5; } public List<String> getDrivers() { return drivers; } public String getDefaultDriver() { return defaultDriver; } public List<String> getLanguages() { return languages; } public String getDefaultLanguage() { return defaultLanguage; } public int getAsrMRT() { return asrMRT; } public int getDefaultGatheringTimeout() { return defaultGatheringTimeout; } }
2,666
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CacheConfigurationSetImpl.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sets/impl/CacheConfigurationSetImpl.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sets.impl; import org.restcomm.connect.commons.configuration.sets.CacheConfigurationSet; import org.restcomm.connect.commons.configuration.sources.ConfigurationSource; public class CacheConfigurationSetImpl extends ConfigurationSet implements CacheConfigurationSet { public static final String CACHE_NO_WAV_KEY = "runtime-settings.cache-no-wav"; public static final String CACHE_PATH_KEY = "runtime-settings.cache-path"; public static final String CACHE_URI_KEY = "runtime-settings.cache-uri"; private boolean noWavCache; private String cachePath; private String cacheUri; public CacheConfigurationSetImpl (ConfigurationSource source) { super(source); String value = source.getProperty(CACHE_NO_WAV_KEY); // default flag value is "false" if appropriate key "cache-no-wav" is absent in configuration *.xml file noWavCache = (value == null) ? false : Boolean.valueOf(source.getProperty(CACHE_NO_WAV_KEY)); cachePath = source.getProperty(CACHE_PATH_KEY); cacheUri = source.getProperty(CACHE_URI_KEY); } public CacheConfigurationSetImpl(boolean noWavCache, String cachePath, String cacheUri) { super(null); this.noWavCache = noWavCache; this.cachePath = cachePath; this.cacheUri = cacheUri; } @Override public boolean isNoWavCache() { return noWavCache; } @Override public String getCachePath() { return cachePath; } @Override public String getCacheUri() { return cacheUri; } public void setNoWavCache(boolean noWavCache) { this.noWavCache = noWavCache; } public void setCachePath(String cachePath) { this.cachePath = cachePath; } public void setCacheUri(String cacheUri) { this.cacheUri = cacheUri; } }
2,706
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConfigurationSet.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sets/impl/ConfigurationSet.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sets.impl; import org.restcomm.connect.commons.configuration.sources.ConfigurationSource; /** * A logical group of configuration options. It encapsulates storage, initialization * and validation operations. Extend it to add new groups. * * @author [email protected] (Orestis Tsakiridis) * */ public class ConfigurationSet { private final ConfigurationSource source; protected ConfigurationSet(ConfigurationSource source) { super(); this.source = source; } public ConfigurationSource getSource() { return source; } }
1,447
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MainConfigurationSetImpl.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/configuration/sets/impl/MainConfigurationSetImpl.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.configuration.sets.impl; import org.apache.commons.lang.StringUtils; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.common.http.SslMode; import org.restcomm.connect.commons.configuration.sets.MainConfigurationSet; import org.restcomm.connect.commons.configuration.sources.ConfigurationSource; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; /** * Provides a typed interface to a set of configuration options retrieved from a * configuration source. * * To add a new option in this set define its name as static fields and then * initialize, validate it in the constructor. * * @author [email protected] (Orestis Tsakiridis) * */ @Immutable public class MainConfigurationSetImpl extends ConfigurationSet implements MainConfigurationSet { private static final String SSL_MODE_KEY = "http-client.ssl-mode"; private static final String HTTP_RESPONSE_TIMEOUT = "http-client.response-timeout"; private static final String HTTP_CONNECTION_REQUEST_TIMEOUT = "http-client.connection-request-timeout"; private static final String HTTP_MAX_CONN_TOTAL = "http-client.max-conn-total"; private static final String HTTP_MAX_CONN_PER_ROUTE = "http-client.max-conn-per-route"; private static final String HTTP_CONNECTION_TIME_TO_LIVE = "http-client.connection-time-to-live"; private static final String HTTP_ROUTES_HOST = "http-client.routes-host"; private static final String HTTP_ROUTES_PORT = "http-client.routes-port"; private static final String HTTP_ROUTES_CONN = "http-client.routes-conn"; private static final String CONFERENCE_TIMEOUT_KEY = "runtime-settings.conference-timeout"; private static final String CLEAR_TEXT_PASSWORD_ALGORITHM = "cleartext"; private static final String DEFAULT_CLIENT_PASSWORD = "MD5"; private static final String DEFAULT_CLIENT_QOP = "auth"; private static final long CONFERENCE_TIMEOUT_DEFAULT = 14400; //4 hours in seconds private static final SslMode SSL_MODE_DEFAULT = SslMode.strict; private SslMode sslMode; private int responseTimeout; private Integer connectionRequestTimeout; private Integer defaultHttpMaxConns; private Integer defaultHttpMaxConnsPerRoute; private Integer defaultHttpTTL; private Map<InetSocketAddress, Integer> defaultHttpRoutes = new HashMap(); private static final String USE_HOSTNAME_TO_RESOLVE_RELATIVE_URL_KEY = "http-client.use-hostname-to-resolve-relative-url"; private static final String HOSTNAME_TO_USE_FOR_RELATIVE_URLS_KEY = "http-client.hostname"; private static final boolean RESOLVE_RELATIVE_URL_WITH_HOSTNAME_DEFAULT = true; private boolean useHostnameToResolveRelativeUrls; private String hostname; private String instanceId; private String apiVersion; private int recordingMaxDelay; private long conferenceTimeout; private String recordingPath; public static final String BYPASS_LB_FOR_CLIENTS = "bypass-lb-for-clients"; private boolean bypassLbForClients = false; private String clientAlgorithm = DEFAULT_CLIENT_PASSWORD; private String clientQOP = DEFAULT_CLIENT_QOP; public MainConfigurationSetImpl(ConfigurationSource source) { super(source); SslMode sslMode; boolean resolveRelativeUrlWithHostname; String resolveRelativeUrlHostname; boolean bypassLb = false; try { responseTimeout = Integer.parseInt(source.getProperty(HTTP_RESPONSE_TIMEOUT, "5000")); } catch (Exception e) { throw new RuntimeException("Error initializing '" + HTTP_RESPONSE_TIMEOUT + "' configuration setting", e); } try { connectionRequestTimeout = Integer.parseInt(source.getProperty(HTTP_CONNECTION_REQUEST_TIMEOUT,String.valueOf(responseTimeout))); } catch (Exception e) { throw new RuntimeException("Error initializing '" + HTTP_RESPONSE_TIMEOUT + "' configuration setting", e); } try { defaultHttpMaxConns = Integer.parseInt(source.getProperty(HTTP_MAX_CONN_TOTAL, "2000")); } catch (Exception e) { throw new RuntimeException("Error initializing '" + HTTP_MAX_CONN_TOTAL + "' configuration setting", e); } try { defaultHttpMaxConnsPerRoute = Integer.parseInt(source.getProperty(HTTP_MAX_CONN_PER_ROUTE, "100")); } catch (Exception e) { throw new RuntimeException("Error initializing '" + HTTP_MAX_CONN_PER_ROUTE + "' configuration setting", e); } try { defaultHttpTTL = Integer.parseInt(source.getProperty(HTTP_CONNECTION_TIME_TO_LIVE, "30000")); } catch (Exception e) { throw new RuntimeException("Error initializing '" + HTTP_CONNECTION_TIME_TO_LIVE + "' configuration setting", e); } try { String delimiter = ","; String routesHostProp = source.getProperty(HTTP_ROUTES_HOST, ""); if (!routesHostProp.isEmpty()) { String[] routesHostList = routesHostProp.split(delimiter); String routesPortProp = source.getProperty(HTTP_ROUTES_PORT, ""); String[] routesPortList = routesPortProp.split(delimiter); String routesConnProp = source.getProperty(HTTP_ROUTES_CONN, ""); String[] routesConnList = routesConnProp.split(delimiter); for (int i = 0; i < routesHostList.length; i++) { Integer port = Integer.valueOf(routesPortList[i]); Integer conn = Integer.valueOf(routesConnList[i]); InetSocketAddress addr = new InetSocketAddress(routesHostList[i], port); defaultHttpRoutes.put(addr, conn); } } } catch (Throwable e) {//to catch array index out of bounds throw new RuntimeException("Error initializing '" + HTTP_ROUTES_CONN + "' configuration setting", e); } // http-client.ssl-mode try { sslMode = SSL_MODE_DEFAULT; String sslModeRaw = source.getProperty(SSL_MODE_KEY); if (!StringUtils.isEmpty(sslModeRaw)) { sslMode = SslMode.valueOf(sslModeRaw); } } catch (Exception e) { throw new RuntimeException("Error initializing '" + SSL_MODE_KEY + "' configuration setting", e); } this.sslMode = sslMode; // http-client.hostname // http-client.use-hostname-to-resolve-relative-url try { resolveRelativeUrlWithHostname = RESOLVE_RELATIVE_URL_WITH_HOSTNAME_DEFAULT; resolveRelativeUrlWithHostname = Boolean.valueOf(source.getProperty(USE_HOSTNAME_TO_RESOLVE_RELATIVE_URL_KEY)); resolveRelativeUrlHostname = source.getProperty("http-client.hostname"); bypassLb = Boolean.valueOf(source.getProperty(BYPASS_LB_FOR_CLIENTS)); } catch (Exception e) { throw new RuntimeException("Error initializing '" + USE_HOSTNAME_TO_RESOLVE_RELATIVE_URL_KEY + "' configuration setting", e); } this.useHostnameToResolveRelativeUrls = resolveRelativeUrlWithHostname; this.hostname = resolveRelativeUrlHostname; bypassLbForClients = bypassLb; apiVersion = source.getProperty("runtime-settings.api-version"); this.recordingMaxDelay = Integer.parseInt(source.getProperty("runtime-settings.recording-max-delay", "2000")); try{ this.conferenceTimeout = Long.parseLong(source.getProperty(CONFERENCE_TIMEOUT_KEY, ""+CONFERENCE_TIMEOUT_DEFAULT)); }catch(NumberFormatException nfe){ this.conferenceTimeout = CONFERENCE_TIMEOUT_DEFAULT; } recordingPath = source.getProperty("runtime-settings.recordings-path"); clientAlgorithm = source.getProperty("runtime-settings.client-algorithm", DEFAULT_CLIENT_PASSWORD); clientQOP = source.getProperty("runtime-settings.client-qop", DEFAULT_CLIENT_QOP); } public MainConfigurationSetImpl(SslMode sslMode, int responseTimeout, boolean useHostnameToResolveRelativeUrls, String hostname, String instanceId, boolean bypassLbForClients) { super(null); this.sslMode = sslMode; this.responseTimeout = responseTimeout; this.useHostnameToResolveRelativeUrls = useHostnameToResolveRelativeUrls; this.hostname = hostname; this.instanceId = instanceId; this.bypassLbForClients = bypassLbForClients; } @Override public SslMode getSslMode() { return sslMode; } @Override public int getResponseTimeout() { return responseTimeout; } @Override public boolean isUseHostnameToResolveRelativeUrls() { return useHostnameToResolveRelativeUrls; } @Override public String getHostname() { return hostname; } @Override public boolean getBypassLbForClients() { return bypassLbForClients; } @Override public void setInstanceId(String instanceId) { this.instanceId = instanceId; } @Override public String getInstanceId() { return this.instanceId; } public void setSslMode(SslMode sslMode) { this.sslMode = sslMode; } public void setResponseTimeout(int responseTimeout) { this.responseTimeout = responseTimeout; } public void setUseHostnameToResolveRelativeUrls(boolean useHostnameToResolveRelativeUrls) { this.useHostnameToResolveRelativeUrls = useHostnameToResolveRelativeUrls; } public void setHostname(String hostname) { this.hostname = hostname; } public void setBypassLbForClients(boolean bypassLbForClients) { this.bypassLbForClients = bypassLbForClients; } public String getApiVersion() { return apiVersion; } @Override public int getRecordingMaxDelay() { return recordingMaxDelay; } @Override public Integer getDefaultHttpMaxConns() { return defaultHttpMaxConns; } @Override public Integer getDefaultHttpMaxConnsPerRoute() { return defaultHttpMaxConnsPerRoute; } @Override public Integer getDefaultHttpTTL() { return defaultHttpTTL; } @Override public Map<InetSocketAddress, Integer> getDefaultHttpRoutes() { return defaultHttpRoutes; } @Override public Integer getDefaultHttpConnectionRequestTimeout() { return connectionRequestTimeout; } @Override public long getConferenceTimeout() { return conferenceTimeout; } @Override public void setConferenceTimeout(long conferenceTimeout) { this.conferenceTimeout = conferenceTimeout; } @Override public String getClientAlgorithm() { return clientAlgorithm; } @Override public String getClientQOP() { return clientQOP; } @Override public String getClearTextPasswordAlgorithm() { return CLEAR_TEXT_PASSWORD_ALGORITHM; } @Override public String getRecordingPath () { return recordingPath; } }
12,026
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StreamEvent.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/stream/StreamEvent.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2017, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it andor modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but OUT ANY WARRANTY; out even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along this program. If not, see <http:www.gnu.orglicenses> */ package org.restcomm.connect.commons.stream; /** * @author [email protected] (Oleg Agafonov) */ public interface StreamEvent { }
929
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DiskCacheFactory.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/cache/DiskCacheFactory.java
package org.restcomm.connect.commons.cache; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.configuration.sets.CacheConfigurationSet; public final class DiskCacheFactory { private final CacheConfigurationSet cfg; private final FileDownloader downloader; public DiskCacheFactory(Configuration cfg) { this(new RestcommConfiguration(cfg)); } public DiskCacheFactory(RestcommConfiguration cfg) { this.cfg = cfg.getCache(); this.downloader = new FileDownloader(); } public DiskCache getDiskCache() { return new DiskCache(downloader, this.cfg.getCachePath(), this.cfg.getCacheUri(), false, cfg.isNoWavCache()); } // constructor for compatibility with existing cache implementation public DiskCache getDiskCache(final String cachePath, final String cacheUri) { return new DiskCache(downloader, cachePath, cacheUri, true, cfg.isNoWavCache()); } }
1,047
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
FileDownloader.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/cache/FileDownloader.java
package org.restcomm.connect.commons.cache; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.restcomm.connect.commons.common.http.CustomHttpClientBuilder; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.net.URI; import java.net.URISyntaxException; /** * @author Gennadiy Dubina */ public class FileDownloader { public URI download(URI requestUri, File pathToSave) throws IOException, URISyntaxException { final File tmp = new File(pathToSave + "." + "tmp"); InputStream input = null; OutputStream output = null; HttpClient client = null; HttpResponse httpResponse = null; try { if (requestUri.getScheme().equalsIgnoreCase("https")) { //Handle the HTTPS URIs client = CustomHttpClientBuilder.buildDefaultClient(RestcommConfiguration.getInstance().getMain()); /*URI result = new URIBuilder() .setScheme(requestUri.getScheme()) .setHost(requestUri.getHost()) .setPort(requestUri.getPort()) .setPath(requestUri.getPath()) .build(); HttpGet httpRequest = new HttpGet(result); */ HttpGet httpRequest = new HttpGet(requestUri); httpResponse = client.execute(httpRequest); int code = httpResponse.getStatusLine().getStatusCode(); if (code >= 400) { String requestUrl = httpRequest.getRequestLine().getUri(); String errorReason = httpResponse.getStatusLine().getReasonPhrase(); String httpErrorMessage = String.format( "Error while fetching http resource: %s \n Http error code: %d \n Http error message: %s", requestUrl, code, errorReason); throw new IOException(httpErrorMessage); } input = httpResponse.getEntity().getContent(); } else { input = requestUri.toURL().openStream(); } output = new FileOutputStream(tmp); final byte[] buffer = new byte[4096]; int read = 0; do { read = input.read(buffer, 0, 4096); if (read > 0) { output.write(buffer, 0, read); } } while (read != -1); tmp.renameTo(pathToSave); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } if (httpResponse != null) { ((CloseableHttpResponse) httpResponse).close(); httpResponse = null; } } return pathToSave.toURI(); } }
3,192
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DiskCache.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/cache/DiskCache.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.cache; import akka.actor.ActorRef; import akka.event.Logging; import akka.event.LoggingAdapter; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.shiro.crypto.hash.Sha256Hash; import org.restcomm.connect.commons.faulttolerance.RestcommUntypedActor; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /** * @author [email protected] (Thomas Quintana) */ public final class DiskCache extends RestcommUntypedActor { // Logger. private final LoggingAdapter logger = Logging.getLogger(getContext().system(), this); private final String cacheDir; private final String cacheUri; // flag for cache disabling in *.wav files usage case private boolean wavNoCache = false; private FileDownloader downloader; public DiskCache(FileDownloader downloader, String cacheDir, String cacheUri, final boolean create, final boolean wavNoCache) { super(); this.wavNoCache = wavNoCache; this.downloader = downloader; // Format the cache path. if (!cacheDir.endsWith("/")) { cacheDir += "/"; } // Create the cache path if specified. final File path = new File(cacheDir); // if (create) { // path.mkdirs(); // } // Make sure the cache path exists and is a directory. if (!path.exists() || !path.isDirectory()) { // throw new IllegalArgumentException(cacheDir + " is not a valid cache cacheDir."); path.mkdirs(); } // Format the cache URI. this.cacheDir = cacheDir; if (!cacheUri.endsWith("/")) { cacheUri += "/"; } this.cacheUri = cacheUri; } public DiskCache(FileDownloader downloader, final String cacheDir, final String cacheUri, final boolean create) { this(downloader, cacheDir, cacheUri, create, false); } public DiskCache(FileDownloader downloader, final String cacheDir, final String cacheUri) { this(downloader, cacheDir, cacheUri, false); } // constructor for compatibility with existing tests public DiskCache(final String cacheDir, final String cacheUri, final boolean create) { this(new FileDownloader(), cacheDir, cacheUri, create, false); } public URI cache(final DiskCacheRequest request) throws IOException, URISyntaxException { if (StringUtils.isNotEmpty(request.hash())) { return handleHashedRequest(request); } else if ("file".equalsIgnoreCase(request.uri().getScheme())) { return handleLocalFile(request); } else { return handleExternalUrl(request); } } private URI handleHashedRequest(final DiskCacheRequest request) throws FileNotFoundException { // This is a check cache request final String extension = "wav"; final String hash = request.hash(); final String filename = hash + "." + extension; Path p = Paths.get(cacheDir + filename); if (Files.exists(p)) { // return URI.create(matchedFile.getAbsolutePath()); return URI.create(this.cacheUri + filename); } else { throw new FileNotFoundException("File "+filename+" NotFound"); } } private URI handleLocalFile(final DiskCacheRequest request) throws IOException { File origFile = new File(request.uri()); File destFile = new File(cacheDir + origFile.getName()); if (!destFile.exists()) { FileUtils.moveFile(origFile, destFile); } return URI.create(this.cacheUri + destFile.getName()); } private URI handleExternalUrl(final DiskCacheRequest request) throws IOException, URISyntaxException { //Handle all the rest // This is a request to cache a URI String hash; URI uri; URI requestUri = request.uri(); String requestUriText = requestUri.toString(); if (wavNoCache && "wav".equalsIgnoreCase(extension(requestUri))) { return requestUri; }else if (requestUriText.contains("hash")) { String fragment = requestUri.getFragment(); hash = fragment.replace("hash=", ""); String uriStr = requestUriText.replace(fragment, "").replace("#", ""); uri = URI.create(uriStr); } else { uri = requestUri; hash = new Sha256Hash(requestUriText).toHex(); } final String extension = extension(uri).toLowerCase(); File path = null; if (!extension.equalsIgnoreCase("wav")) { path = new File(cacheDir + hash + "." + extension); if (!path.exists()) { downloader.download(uri, path); } return URI.create(this.cacheUri + hash + "." + extension); } else { path = new File(cacheDir + hash + ".wav" ); if (!path.exists()) { downloader.download(uri, path); } return URI.create(this.cacheUri + hash + ".wav"); } } @Override public void onReceive(final Object message) throws Exception { if (!(message instanceof DiskCacheRequest)) { logger.warning("Unexpected request type"); return; } final Class<?> klass = message.getClass(); final ActorRef self = self(); final ActorRef sender = sender(); if (DiskCacheRequest.class.equals(klass)) { DiskCacheResponse response; try { response = new DiskCacheResponse(cache((DiskCacheRequest) message)); } catch (final Exception exception) { if (logger.isDebugEnabled()) { logger.debug("Issue while caching", exception); } response = new DiskCacheResponse(exception); } sender.tell(response, self); } } private static String extension(final URI uri) { final String path = uri.getPath(); return path.substring(path.lastIndexOf(".") + 1); } }
7,167
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HashGenerator.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/cache/HashGenerator.java
package org.restcomm.connect.commons.cache; import org.apache.shiro.crypto.hash.Sha256Hash; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ public class HashGenerator { public static String hashMessage(String first, String second, String third) { return new Sha256Hash(first + second + third).toHex(); } }
347
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DiskCacheRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/cache/DiskCacheRequest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.cache; import java.net.URI; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class DiskCacheRequest { private URI uri; private String hash = null; public DiskCacheRequest(URI uri) { super(); this.uri = uri; } public DiskCacheRequest(String hash) { super(); this.hash = hash; } public URI uri() { return uri; } public String hash() { return hash; } }
1,402
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DiskCacheResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/cache/DiskCacheResponse.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.cache; import java.net.URI; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class DiskCacheResponse extends StandardResponse<URI> { public DiskCacheResponse(final Throwable cause, final String message) { super(cause, message); } public DiskCacheResponse(final Throwable cause) { super(cause); } public DiskCacheResponse(final URI object) { super(object); } @Override public String toString() { if(cause() == null){ return "DiskCacheResponse [" + super.toString() + "]"; } return (new StringBuffer("DiskCacheResponse [succeeded=").append(succeeded()).append(", cause=").append(cause().getMessage()).append(", message=").append(error()).append(", object=").append(get()).append("]")).toString(); } }
1,821
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TomcatConnectorDiscover.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/TomcatConnectorDiscover.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.lang.management.ManagementFactory; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Set; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.Query; import javax.management.ReflectionException; import org.apache.log4j.Logger; import org.restcomm.connect.commons.HttpConnector; import org.restcomm.connect.commons.HttpConnectorList; public class TomcatConnectorDiscover implements HttpConnectorDiscover { private static final Logger LOG = Logger.getLogger(TomcatConnectorDiscover.class); @Override public HttpConnectorList findConnectors() throws MalformedObjectNameException, NullPointerException, UnknownHostException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException { LOG.info("Searching Tomcat HTTP connectors."); HttpConnectorList httpConnectorList = null; MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); Set<ObjectName> tomcatObjs = mbs.queryNames(new ObjectName("*:type=Connector,*"), Query.match(Query.attr("protocol"), Query.value("HTTP/1.1"))); ArrayList<HttpConnector> endPoints = new ArrayList<HttpConnector>(); if (tomcatObjs != null && tomcatObjs.size() > 0) { for (ObjectName obj : tomcatObjs) { String scheme = mbs.getAttribute(obj, "scheme").toString().replaceAll("\"", ""); String port = obj.getKeyProperty("port").replaceAll("\"", ""); String address = obj.getKeyProperty("address").replaceAll("\"", ""); if (LOG.isInfoEnabled()) { LOG.info("Tomcat Http Connector: " + scheme + "://" + address + ":" + port); } HttpConnector httpConnector = new HttpConnector(scheme, address, Integer.parseInt(port), scheme.equalsIgnoreCase("https")); endPoints.add(httpConnector); } } if (endPoints.isEmpty()) { LOG.warn("Coundn't discover any Http Interfaces"); } httpConnectorList = new HttpConnectorList(endPoints); return httpConnectorList; } }
3,239
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientLoginConstrains.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/ClientLoginConstrains.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2018, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package org.restcomm.connect.commons.util; public class ClientLoginConstrains { private static char[] NOT_ALLOWED_CHARS = {'?', '=', '@'}; public static boolean isValidClientLogin (final String login) { for (char ch: ClientLoginConstrains.NOT_ALLOWED_CHARS) { if (login.indexOf(ch) > -1) { return false; } } return true; } }
1,225
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/HttpUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class HttpUtils { private HttpUtils() { super(); } public static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; public static Map<String, String> toMap(final HttpEntity entity) throws IllegalStateException, IOException { String contentType = null; String charset = null; contentType = EntityUtils.getContentMimeType(entity); charset = EntityUtils.getContentCharSet(entity); List<NameValuePair> parameters = null; if (contentType != null && contentType.equalsIgnoreCase(CONTENT_TYPE)) { parameters = URLEncodedUtils.parse(entity); } else { final String content = EntityUtils.toString(entity, HTTP.ASCII); if (content != null && content.length() > 0) { parameters = new ArrayList<NameValuePair>(); URLEncodedUtils.parse(parameters, new Scanner(content), charset); } } final Map<String, String> map = new HashMap<String, String>(); for (final NameValuePair parameter : parameters) { map.put(parameter.getName(), parameter.getValue()); } return map; } public static String toString(final Header[] headers) { final List<NameValuePair> parameters = new ArrayList<NameValuePair>(); for (final Header header : headers) { parameters.add(new BasicNameValuePair(header.getName(), header.getValue())); } return URLEncodedUtils.format(parameters, "UTF-8"); } }
2,998
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
WavUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/WavUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.net.URI; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class WavUtils { private WavUtils() { super(); } public static double getAudioDuration(final URI wavFile) throws UnsupportedAudioFileException, IOException { return getAudioDuration(new File(wavFile)); } public static double getAudioDuration(final File wavFile) throws UnsupportedAudioFileException, IOException { AudioInputStream audio = null; try { if (wavFile != null && wavFile.exists()) { audio = AudioSystem.getAudioInputStream(wavFile); final AudioFormat format = audio.getFormat(); return wavFile.length() / format.getSampleRate() / (format.getSampleSizeInBits() / 8.0) / format.getChannels(); } return 0; } catch (UnsupportedAudioFileException exception) { // Return calculation based on MMS defaults int sampleRate = 8000; int sampleSize = 16; int channels = 1; return wavFile.length() / (sampleRate / 8.0) / sampleSize / channels; } catch (EOFException e) { return 0; } finally { if (audio != null) { audio.close(); } } } }
2,529
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
JBossConnectorDiscover.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/JBossConnectorDiscover.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.lang.management.ManagementFactory; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Set; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.management.ReflectionException; import org.apache.log4j.Logger; import org.restcomm.connect.commons.HttpConnector; import org.restcomm.connect.commons.HttpConnectorList; public class JBossConnectorDiscover implements HttpConnectorDiscover { private static final Logger LOG = Logger.getLogger(JBossConnectorDiscover.class); /** * A list of connectors. Not bound connectors will be discarded. * * @return * @throws MalformedObjectNameException * @throws NullPointerException * @throws UnknownHostException * @throws AttributeNotFoundException * @throws InstanceNotFoundException * @throws MBeanException * @throws ReflectionException */ @Override public HttpConnectorList findConnectors() throws MalformedObjectNameException, NullPointerException, UnknownHostException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException { LOG.info("Searching JBoss HTTP connectors."); HttpConnectorList httpConnectorList = null; MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); Set<ObjectName> jbossObjs = mbs.queryNames(new ObjectName("jboss.as:socket-binding-group=standard-sockets,socket-binding=http*"), null); LOG.info("JBoss Mbean found."); ArrayList<HttpConnector> endPoints = new ArrayList<HttpConnector>(); if (jbossObjs != null && jbossObjs.size() > 0) { LOG.info("JBoss Connectors found:" + jbossObjs.size()); for (ObjectName obj : jbossObjs) { Boolean bound = (Boolean) mbs.getAttribute(obj, "bound"); if (bound) { String scheme = mbs.getAttribute(obj, "name").toString().replaceAll("\"", ""); Integer port = (Integer) mbs.getAttribute(obj, "boundPort"); String address = ((String) mbs.getAttribute(obj, "boundAddress")).replaceAll("\"", ""); if (LOG.isInfoEnabled()) { LOG.info("Jboss Http Connector: " + scheme + "://" + address + ":" + port); } HttpConnector httpConnector = new HttpConnector(scheme, address, port, scheme.equalsIgnoreCase("https")); endPoints.add(httpConnector); } else { LOG.info("JBoss Connector not bound,discarding."); } } } if (endPoints.isEmpty()) { LOG.warn("Coundn't discover any Http Interfaces."); } httpConnectorList = new HttpConnectorList(endPoints); return httpConnectorList; } }
3,918
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RevolvingCounter.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/RevolvingCounter.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class RevolvingCounter { private final long start; private final long limit; private final AtomicLong count; private final Lock lock; public RevolvingCounter(final long limit) { this(0, limit); } public RevolvingCounter(final long start, final long limit) { super(); this.start = start; this.limit = limit; this.count = new AtomicLong(); this.count.set(start); this.lock = new ReentrantLock(); } public long get() { long result = count.getAndIncrement(); if (result >= limit) { while (!lock.tryLock()) { /* Spin */ } if (count.get() >= limit) { result = start; count.set(start + 1); lock.unlock(); } else { lock.unlock(); result = get(); } } return result; } }
2,085
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HexadecimalUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/HexadecimalUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class HexadecimalUtils { private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private HexadecimalUtils() { super(); } public static char[] toHex(final byte[] input) { int position = 0; char[] characters = new char[input.length * 2]; for (int index = 0; index < input.length; index++) { characters[position++] = HEX_DIGITS[(input[index] >> 4) & 0x0F]; characters[position++] = HEX_DIGITS[input[index] & 0x0f]; } return characters; } public static String toHex(final String input) { return new String(toHex(input.getBytes())); } }
1,728
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DigestAuthentication.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/DigestAuthentication.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class DigestAuthentication { private DigestAuthentication() { super(); } private static String A1(final String algorithm, final String user, final String realm, final String password, final String nonce, final String cnonce) { if (algorithm == null || algorithm.trim().length() == 0 || algorithm.trim().equalsIgnoreCase("MD5")) { return user + ":" + realm + ":" + password; } else { if (cnonce == null || cnonce.length() == 0) { throw new NullPointerException("The cnonce parameter may not be null."); } return H(user + ":" + realm + ":" + password, algorithm) + ":" + nonce + ":" + cnonce; } } private static String A2(String algorithm, final String method, final String uri, String body, final String qop) { if (qop == null || qop.trim().length() == 0 || qop.trim().equalsIgnoreCase("auth")) { return method + ":" + uri; } else { if (body == null) body = ""; return method + ":" + uri + ":" + H(body, algorithm); } } public static String response(final String authHeaderAlgorithm, final String user, final String realm, final String password, final String nonce, final String nc, final String cnonce, final String method, final String uri, String body, final String qop) { return response(authHeaderAlgorithm, user, realm, password, RestcommConfiguration.getInstance().getMain().getClientAlgorithm(), nonce, nc, cnonce, method, uri, body, qop); } /** * @param authHeaderAlgorithm * @param user * @param realm * @param password * @param clientPasswordAlgorithm * @param nonce * @param nc * @param cnonce * @param method * @param uri * @param body * @param qop * @return */ public static String response(final String authHeaderAlgorithm, final String user, final String realm, final String password, final String clientPasswordAlgorithm, final String nonce, final String nc, final String cnonce, final String method, final String uri, String body, final String qop) { validate(user, realm, password, nonce, method, uri, authHeaderAlgorithm); String ha1; if (clientPasswordAlgorithm.equalsIgnoreCase("cleartext")) { final String a1 = A1(authHeaderAlgorithm, user, realm, password, nonce, cnonce); ha1 = H(a1, authHeaderAlgorithm); } else { ha1 = password; } final String a2 = A2(authHeaderAlgorithm, method, uri, body, qop); if (cnonce != null && qop != null && nc != null && (qop.equalsIgnoreCase("auth") || qop.equalsIgnoreCase("auth-int"))) { return KD(ha1, nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + H(a2, authHeaderAlgorithm), authHeaderAlgorithm); } else { return KD(ha1, nonce + ":" + H(a2, authHeaderAlgorithm), authHeaderAlgorithm); } } private static String H(final String data, String algorithm) { try { final MessageDigest digest = MessageDigest.getInstance(algorithm); final byte[] result = digest.digest(data.getBytes()); final char[] characters = HexadecimalUtils.toHex(result); return new String(characters); } catch (final NoSuchAlgorithmException exception) { return null; } } private static String KD(final String secret, final String data, String algorithm) { return H(secret + ":" + data, algorithm); } private static void validate(final String user, final String realm, final String password, final String nonce, final String method, final String uri, String algorithm) { if (user == null) { throw new NullPointerException("The user parameter may not be null."); } else if (realm == null) { throw new NullPointerException("The realm parameter may not be null."); } else if (password == null) { throw new NullPointerException("The password parameter may not be null."); } else if (method == null) { throw new NullPointerException("The method parameter may not be null."); } else if (uri == null) { throw new NullPointerException("The uri parameter may not be null."); } else if (nonce == null) { throw new NullPointerException("The nonce parameter may not be null."); } } /** * @param username * @param realm * @param password * @return */ public static String HA1(String username, String realm, String password){ String algorithm = RestcommConfiguration.getInstance().getMain().getClientAlgorithm(); String ha1 = ""; ha1 = DigestAuthentication.H(username+":"+realm+":"+password, algorithm); return ha1; } //USed for unit testing public static String HA1(String username, String realm, String password, String algorithm){ String ha1 = ""; ha1 = DigestAuthentication.H(username+":"+realm+":"+password, algorithm); return ha1; } }
6,374
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IPUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/IPUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.util.regex.Pattern; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class IPUtils { private static final Pattern LOOPBACK = Pattern.compile("(^127\\.0\\.0\\.1)"); private static final Pattern NON_ROUTABLE_CLASS_A = Pattern.compile("(^10\\.\\d{0,3}\\.\\d{0,3}\\.\\d{0,3})"); private static final Pattern NON_ROUTABLE_CLASS_B = Pattern.compile("(^172\\.1[6-9]\\.\\d{0,3}\\.\\d{0,3})|" + "(^172\\.2[0-9]\\.\\d{0,3}\\.\\d{0,3})|(^172\\.3[0-1]\\.\\d{0,3}\\.\\d{0,3})"); private static final Pattern NON_ROUTABLE_CLASS_C = Pattern.compile("(^192\\.168\\.\\d{0,3}\\.\\d{0,3})"); private IPUtils() { super(); } public static boolean isRoutableAddress(final String address) { return !(LOOPBACK.matcher(address).matches() || NON_ROUTABLE_CLASS_A.matcher(address).matches() || NON_ROUTABLE_CLASS_B.matcher(address).matches() || NON_ROUTABLE_CLASS_C.matcher(address).matches()); } }
1,930
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SecurityUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/SecurityUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import org.apache.commons.codec.binary.Base64; /** * @author [email protected] - Orestis Tsakiridis */ public class SecurityUtils { public static String buildBasicAuthHeader(String username, String password) { return "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()); } }
1,174
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SdpUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/SdpUtils.java
package org.restcomm.connect.commons.util; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Vector; import javax.sdp.Connection; import javax.sdp.MediaDescription; import javax.sdp.Origin; import javax.sdp.SdpException; import javax.sdp.SdpFactory; import javax.sdp.SdpParseException; import javax.sdp.SessionDescription; //import ThreadSafe; /** * @author Henrique Rosa ([email protected]) */ //@ThreadSafe public class SdpUtils { /** * Patches an SDP description by trimming and making sure it ends with a new line. * * @param sdpDescription The SDP description to be patched. * @return The patched SDP description * @author hrosa */ public static String endWithNewLine(String sdpDescription) { if (sdpDescription == null || sdpDescription.isEmpty()) { throw new IllegalArgumentException("The SDP description cannot be null or empty"); } return sdpDescription.trim().concat("\n"); } @SuppressWarnings("unchecked") public static String patch(final String contentType, final byte[] data, final String externalIp) throws UnknownHostException, SdpException { final String text = new String(data); String patchedSdp = null; if (contentType.equalsIgnoreCase("application/sdp")) { final SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(text); // Handle the connection at the session level. fix(sdp.getConnection(), externalIp); // https://github.com/Mobicents/RestComm/issues/149 fix(sdp.getOrigin(), externalIp); // Handle the connections at the media description level. final Vector<MediaDescription> descriptions = sdp.getMediaDescriptions(false); for (final MediaDescription description : descriptions) { fix(description.getConnection(), externalIp); } patchedSdp = sdp.toString(); } else { String boundary = contentType.split(";")[1].split("=")[1]; String[] parts = text.split(boundary); String sdpText = null; for (String part : parts) { if (part.contains("application/sdp")) { sdpText = part.replaceAll("Content.*", "").replaceAll("--", "").trim(); } } final SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(sdpText); fix(sdp.getConnection(), externalIp); // https://github.com/Mobicents/RestComm/issues/149 fix(sdp.getOrigin(), externalIp); // Handle the connections at the media description level. final Vector<MediaDescription> descriptions = sdp.getMediaDescriptions(false); for (final MediaDescription description : descriptions) { fix(description.getConnection(), externalIp); } patchedSdp = sdp.toString(); } return patchedSdp; } public static String getSdp(final String contentType, final byte[] data) throws SdpParseException { final String text = new String(data); String sdpResult = null; if (contentType.equalsIgnoreCase("application/sdp")) { final SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(text); sdpResult = sdp.toString(); } else { String boundary = contentType.split(";")[1].split("=")[1]; String[] parts = text.split(boundary); String sdpText = null; for (String part : parts) { if (part.contains("application/sdp")) { sdpText = part.replaceAll("Content.*", "").replaceAll("--", "").trim(); } } final SessionDescription sdp = SdpFactory.getInstance().createSessionDescription(sdpText); sdpResult = sdp.toString(); } return sdpResult; } private static void fix(final Origin origin, final String externalIp) throws UnknownHostException, SdpException { if (origin != null) { if (Connection.IN.equals(origin.getNetworkType())) { if (Connection.IP4.equals(origin.getAddressType())) { final InetAddress address; try { address = DNSUtils.getByName(origin.getAddress()); final String ip = address.getHostAddress(); if (!IPUtils.isRoutableAddress(ip)) { origin.setAddress(externalIp); } } catch (UnknownHostException e) { // TODO do nothing cause domain name is unknown // origin.setAddress(externalIp); to remove } } } } } private static void fix(final Connection connection, final String externalIp) throws UnknownHostException, SdpException { if (connection != null) { if (Connection.IN.equals(connection.getNetworkType())) { if (Connection.IP4.equals(connection.getAddressType())) { final InetAddress address = DNSUtils.getByName(connection.getAddress()); final String ip = address.getHostAddress(); if (!IPUtils.isRoutableAddress(ip)) { connection.setAddress(externalIp); } } } } } public static boolean isWebRTCSDP(final String contentType, final byte[] data) throws SdpParseException { boolean isWebRTC = false; if (contentType.equalsIgnoreCase("application/sdp")) { String sdp = getSdp(contentType, data); if (sdp != null && sdp.contains("RTP/SAVP") || sdp.contains("rtp/savp") || sdp.contains("RTP/SAVPF") || sdp.contains("rtp/savpf")) { isWebRTC = true; } } return isWebRTC; } public static boolean isAudioSDP(final String contentType, final byte[] data) throws SdpParseException { boolean isAudioSdp = false; if (contentType.equalsIgnoreCase("application/sdp")) { String sdp = getSdp(contentType, data); if (sdp != null && sdp.contains("m=audio") || sdp.contains("m=AUDIO") || sdp.contains("m=Audio")) { isAudioSdp = true; } } return isAudioSdp; } public static boolean isVideoSDP(final String contentType, final byte[] data) throws SdpParseException { boolean isVideoSdp = false; if (contentType.equalsIgnoreCase("application/sdp")) { String sdp = getSdp(contentType, data); if (sdp != null && sdp.contains("m=video") || sdp.contains("m=VIDEO") || sdp.contains("m=Video")) { isVideoSdp = true; } } return isVideoSdp; } }
7,077
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpConnectorDiscover.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/HttpConnectorDiscover.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.net.UnknownHostException; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanException; import javax.management.MalformedObjectNameException; import javax.management.ReflectionException; import org.restcomm.connect.commons.HttpConnectorList; interface HttpConnectorDiscover { HttpConnectorList findConnectors() throws MalformedObjectNameException, NullPointerException, UnknownHostException, AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException; }
1,452
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TimeUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/TimeUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class TimeUtils { public static final long SECOND_IN_MILLIS = 1000; public static final long MINUTE_IN_MILLIS = SECOND_IN_MILLIS * 60; public static final long HOURS_IN_MILLIES = MINUTE_IN_MILLIS * 60; private TimeUtils() { super(); } public static int millisToMinutes(final long milliseconds) { final long minute = 60 * 1000; final long remainder = milliseconds % minute; if (remainder != 0) { final long delta = minute - remainder; return (int) ((milliseconds + delta) / minute); } else { return (int) (milliseconds / minute); } } }
1,665
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
StringUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/StringUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.regex.Pattern; import org.restcomm.connect.commons.annotations.concurrency.ThreadSafe; /** * @author [email protected] (Thomas Quintana) */ @ThreadSafe public final class StringUtils { private static final Pattern numberPattern = Pattern.compile("\\d+"); private StringUtils() { super(); } public static String addSuffixIfNotPresent(final String text, final String suffix) { if (text.endsWith(suffix)) { return text; } else { return text + suffix; } } public static boolean isPositiveInteger(final String text) { return numberPattern.matcher(text).matches(); } public static String toString(final InputStream input) throws IOException { final InputStreamReader reader = new InputStreamReader(input); final StringWriter writer = new StringWriter(); final char[] data = new char[512]; int bytesRead = -1; do { bytesRead = reader.read(data); if (bytesRead > 0) { writer.write(data, 0, bytesRead); } } while (bytesRead != -1); return writer.getBuffer().toString(); } }
2,180
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DNSUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/DNSUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.commons.configuration.Configuration; import org.restcomm.connect.commons.util.mock.InetAddressMock; /** * @author [email protected] (Maria Farooq) */ public class DNSUtils { private static boolean initialized = false; private static String dnsUtilImplClassName; private static final String DEFAULT_DNS_UTIL_CLASS_NAME = "java.net.InetAddress"; public static void initializeDnsUtilImplClassName(Configuration conf) { synchronized (DNSUtils.class) { if (!initialized) { String configClass = conf.getString("dns-util[@class]"); dnsUtilImplClassName = (configClass == null || configClass.trim().equals("")) ? DEFAULT_DNS_UTIL_CLASS_NAME : configClass; initialized = true; } } } public static InetAddress getByName(String host) throws UnknownHostException { InetAddress result = null; switch (dnsUtilImplClassName) { case "java.net.InetAddress": result = InetAddress.getByName(host); break; /* we can add implementation of another dns impl as well, for example dn4j etc*/ case "org.restcomm.connect.commons.util.mock.InetAddressMock": //case "org.restcomm.connect.testsuite.mocks.InetAddressMock": result = InetAddressMock.getByName(host); break; default: result = InetAddress.getByName(host); break; } return result == null ? InetAddress.getByName(host): result; } }
2,478
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PcmToWavConverterUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/PcmToWavConverterUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; /** * @author [email protected] (Ricardo Limonta) */ public class PcmToWavConverterUtils { public void rawToWave(final File rawFile, final File waveFile) throws IOException { byte[] rawData = new byte[(int) rawFile.length()]; DataInputStream input = null; try { input = new DataInputStream(new FileInputStream(rawFile)); input.read(rawData); } finally { if (input != null) { input.close(); } } DataOutputStream output = null; try { output = new DataOutputStream(new FileOutputStream(waveFile)); // WAVE header writeString(output, "RIFF"); // chunk id writeInt(output, 36 + rawData.length); // chunk size writeString(output, "WAVE"); // format writeString(output, "fmt "); // subchunk 1 id writeInt(output, 16); // subchunk 1 size writeShort(output, (short) 1); // audio format (1 = PCM) writeShort(output, (short) 1); // number of channels writeInt(output, 8000); // sample rate writeInt(output, 8 * 2); // byte rate writeShort(output, (short) 2); // block align writeShort(output, (short) 16); // bits per sample writeString(output, "data"); // subchunk 2 id writeInt(output, rawData.length); // subchunk 2 size // Audio data (conversion big endian -> little endian) short[] shorts = new short[rawData.length / 2]; ByteBuffer.wrap(rawData).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shorts); ByteBuffer bytes = ByteBuffer.allocate(shorts.length * 2); for (short s : shorts) { bytes.putShort(s); } output.write(fullyReadFileToBytes(rawFile)); } finally { if (output != null) { output.close(); } } } byte[] fullyReadFileToBytes(File f) throws IOException { int size = (int) f.length(); byte[] bytes = new byte[size]; byte[] tmpBuff = new byte[size]; FileInputStream fis = new FileInputStream(f); try { int read = fis.read(bytes, 0, size); if (read < size) { int remain = size - read; while (remain > 0) { read = fis.read(tmpBuff, 0, remain); System.arraycopy(tmpBuff, 0, bytes, size - remain, read); remain -= read; } } } catch (IOException e) { throw e; } finally { fis.close(); } return bytes; } private void writeInt(final DataOutputStream output, final int value) throws IOException { output.write(value >> 0); output.write(value >> 8); output.write(value >> 16); output.write(value >> 24); } private void writeShort(final DataOutputStream output, final short value) throws IOException { output.write(value >> 0); output.write(value >> 8); } private void writeString(final DataOutputStream output, final String value) throws IOException { for (int i = 0; i < value.length(); i++) { output.write(value.charAt(i)); } } }
4,453
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
InetAddressMock.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/util/mock/InetAddressMock.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.util.mock; import java.net.InetAddress; import java.net.UnknownHostException; /** * @author [email protected] (Maria Farooq) */ public class InetAddressMock { public static InetAddress getByName(String host) throws UnknownHostException { return InetAddress.getByName("127.0.0.1"); } }
1,161
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BrokenTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/BrokenTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; /** * Test fails consistently. * Test should be investigated and fixed as unplanned in current Sprint, * to allow potential Releases to be deployed. * @author Jaime * @author mariafarooq */ public interface BrokenTests { }
1,092
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
UnstableTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/UnstableTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; /** * Test fails and success with same code in consecutive testsuite runs. * When a test is detected to be unstable in Ci environment, * it should be run locally and marked as broken if fails consistently. * Unstable tests are tech debt and they need to be * investigated after proper Product Backlog prioritization. * @author Jaime * @author mariafarooq * */ public interface UnstableTests { }
1,268
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NewTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/NewTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; public interface NewTests { }
893
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
FeatureAltTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/FeatureAltTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; /** * Result positive: An Alternate Flow is a step or a sequence of * steps that achieves the use case’s goal following different * steps than described in the main success scenario. * But the goal is achieved finally. * @author Jaime * @author mariafarooq * */ public interface FeatureAltTests { }
1,173
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ParallelMethodTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/ParallelMethodTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; public interface ParallelMethodTests { }
905
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ParallelClassTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/ParallelClassTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; public @interface ParallelClassTests { }
906
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ParallelTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/ParallelTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; public interface ParallelTests { }
898
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SequentialClassTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/SequentialClassTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; public interface SequentialClassTests { }
906
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
WithInMinsTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/WithInMinsTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; public interface WithInMinsTests { }
900
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
WithInMillisTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/WithInMillisTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; public interface WithInMillisTests { }
902
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
WithInSecsTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/WithInSecsTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; public interface WithInSecsTests { }
900
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Experimental.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/Experimental.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; /** * @author [email protected] (Thomas Quintana) */ public @interface Experimental { }
960
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
FeatureExpTests.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/FeatureExpTests.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations; /** * Result negative: An Exception is anything that leads to NOT achieving the use case’s goal. * @author Jaime * @author mariafarooq * */ public interface FeatureExpTests { }
1,047
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ThreadSafe.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/concurrency/ThreadSafe.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations.concurrency; /** * @author [email protected] (Thomas Quintana) */ public @interface ThreadSafe { }
970
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NotThreadSafe.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/concurrency/NotThreadSafe.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations.concurrency; /** * @author [email protected] (Thomas Quintana) */ public @interface NotThreadSafe { }
973
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
Immutable.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/annotations/concurrency/Immutable.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.commons.annotations.concurrency; /** * @author [email protected] (Thomas Quintana) */ public @interface Immutable { }
969
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
PushNotificationServerHelper.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.commons/src/main/java/org/restcomm/connect/commons/push/PushNotificationServerHelper.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.commons.push; import akka.actor.ActorSystem; import akka.dispatch.Futures; import com.google.gson.Gson; import org.apache.commons.configuration.Configuration; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.log4j.Logger; import org.restcomm.connect.commons.common.http.CustomHttpClientBuilder; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import scala.concurrent.ExecutionContext; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Callable; /** * @author [email protected] (Oleg Agafonov) */ public class PushNotificationServerHelper { private static final Logger logger = Logger.getLogger(PushNotificationServerHelper.class); private final HttpClient httpClient = CustomHttpClientBuilder.buildDefaultClient(RestcommConfiguration.getInstance().getMain()); private final ExecutionContext dispatcher; private final boolean pushNotificationServerEnabled; private String pushNotificationServerUrl; private long pushNotificationServerDelay; public PushNotificationServerHelper(final ActorSystem actorSystem, final Configuration configuration) { this.dispatcher = actorSystem.dispatchers().lookup("restcomm-blocking-dispatcher"); final Configuration runtime = configuration.subset("runtime-settings"); this.pushNotificationServerEnabled = runtime.getBoolean("push-notification-server-enabled", false); if (this.pushNotificationServerEnabled) { this.pushNotificationServerUrl = runtime.getString("push-notification-server-url"); this.pushNotificationServerDelay = runtime.getLong("push-notification-server-delay"); } } public long sendPushNotificationIfNeeded(final String pushClientIdentity) { if (!pushNotificationServerEnabled || pushClientIdentity == null) { return 0; } if (logger.isDebugEnabled()) { logger.debug("Push server notification to client with identity: '" + pushClientIdentity + "' added to queue."); } Futures.future(new Callable<Void>() { @Override public Void call() throws Exception { Map<String, String> params = new HashMap<>(); params.put("Identity", pushClientIdentity); HttpPost httpPost = new HttpPost(pushNotificationServerUrl); try { httpPost.setEntity(new StringEntity(new Gson().toJson(params), ContentType.APPLICATION_JSON)); if (logger.isDebugEnabled()) { logger.debug("Sending push server notification to client with identity: " + pushClientIdentity); } HttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { logger.warn("Error while sending push server notification to client with identity: " + pushClientIdentity + ", response: " + httpResponse.getEntity()); } } catch (Exception e) { logger.error("Exception while sending push server notification, " + e); } finally { httpPost.releaseConnection(); } return null; } }, dispatcher); return pushNotificationServerDelay; } }
4,579
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NotificationsDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/NotificationsDaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.junit.Assert.*; import java.io.InputStream; import java.net.URI; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.dao.NotificationsDao; import org.restcomm.connect.dao.common.Sorting; import org.restcomm.connect.dao.entities.Notification; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.NotificationFilter; /** * @author [email protected] (Thomas Quintana) */ public final class NotificationsDaoTest { private static MybatisDaoManager manager; protected static Sid instanceId = Sid.generate(Sid.Type.INSTANCE); public NotificationsDaoTest() { super(); } @Before public void before() { final InputStream data = getClass().getResourceAsStream("/mybatis.xml"); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); XMLConfiguration xmlConfiguration = new XMLConfiguration(); xmlConfiguration.setDelimiterParsingDisabled(true); xmlConfiguration.setAttributeSplittingDisabled(true); try { xmlConfiguration.load("restcomm.xml"); RestcommConfiguration.createOnce(xmlConfiguration); RestcommConfiguration.getInstance().getMain().setInstanceId(instanceId.toString()); } catch (ConfigurationException e) { e.printStackTrace(); } } @After public void after() { manager.shutdown(); } @Test public void createReadDelete() { final Sid sid = Sid.generate(Sid.Type.NOTIFICATION); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid call = Sid.generate(Sid.Type.CALL); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final String method = "GET"; final Notification.Builder builder = Notification.builder(); builder.setSid(sid); builder.setAccountSid(account); builder.setCallSid(call); builder.setApiVersion("2012-04-24"); builder.setLog(0); builder.setErrorCode(11100); builder.setMoreInfo(url); builder.setMessageText("hello world!"); builder.setMessageDate(DateTime.now()); builder.setRequestUrl(url); builder.setRequestMethod(method); builder.setRequestVariables("hello world!"); builder.setResponseHeaders("hello world!"); builder.setResponseBody("hello world!"); builder.setUri(url); Notification notification = builder.build(); final NotificationsDao notifications = manager.getNotificationsDao(); // Create a new notification in the data store. notifications.addNotification(notification); // Read the notification from the data store. Notification result = notifications.getNotification(sid); // Verify the results. assertTrue(result.getSid().equals(notification.getSid())); assertTrue(result.getAccountSid().equals(notification.getAccountSid())); assertTrue(result.getCallSid().equals(notification.getCallSid())); assertTrue(result.getApiVersion().equals(notification.getApiVersion())); assertTrue(result.getLog() == notification.getLog()); assertTrue(result.getErrorCode().equals(notification.getErrorCode())); assertTrue(result.getMoreInfo().equals(notification.getMoreInfo())); assertTrue(result.getMessageText().equals(notification.getMessageText())); assertTrue(result.getMessageDate().equals(notification.getMessageDate())); assertTrue(result.getRequestUrl().equals(notification.getRequestUrl())); assertTrue(result.getRequestMethod().equals(notification.getRequestMethod())); assertTrue(result.getRequestVariables().equals(notification.getRequestVariables())); assertTrue(result.getResponseHeaders().equals(notification.getResponseHeaders())); assertTrue(result.getResponseBody().equals(notification.getResponseBody())); assertTrue(result.getUri().equals(notification.getUri())); // Delete the notification. notifications.removeNotification(sid); // Validate that the notification was removed. assertTrue(notifications.getNotification(sid) == null); } @Test public void testByAccount() { final Sid sid = Sid.generate(Sid.Type.NOTIFICATION); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid call = Sid.generate(Sid.Type.CALL); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final String method = "GET"; final Notification.Builder builder = Notification.builder(); builder.setSid(sid); builder.setAccountSid(account); builder.setCallSid(call); builder.setApiVersion("2012-04-24"); builder.setLog(0); builder.setErrorCode(11100); builder.setMoreInfo(url); builder.setMessageText("hello world!"); builder.setMessageDate(DateTime.now()); builder.setRequestUrl(url); builder.setRequestMethod(method); builder.setRequestVariables("hello world!"); builder.setResponseHeaders("hello world!"); builder.setResponseBody("hello world!"); builder.setUri(url); Notification notification = builder.build(); final NotificationsDao notifications = manager.getNotificationsDao(); // Create a new notification in the data store. notifications.addNotification(notification); // Read the notification from the data store. assertTrue(notifications.getNotifications(account).size() == 1); // Delete the notification. notifications.removeNotifications(account); // Validate that the notification was removed. assertTrue(notifications.getNotifications(account).size() == 0); } @Test public void testByCall() { final Sid sid = Sid.generate(Sid.Type.NOTIFICATION); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid call = Sid.generate(Sid.Type.CALL); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final String method = "GET"; final Notification.Builder builder = Notification.builder(); builder.setSid(sid); builder.setAccountSid(account); builder.setCallSid(call); builder.setApiVersion("2012-04-24"); builder.setLog(0); builder.setErrorCode(11100); builder.setMoreInfo(url); builder.setMessageText("hello world!"); builder.setMessageDate(DateTime.now()); builder.setRequestUrl(url); builder.setRequestMethod(method); builder.setRequestVariables("hello world!"); builder.setResponseHeaders("hello world!"); builder.setResponseBody("hello world!"); builder.setUri(url); Notification notification = builder.build(); final NotificationsDao notifications = manager.getNotificationsDao(); // Create a new notification in the data store. notifications.addNotification(notification); // Read the notification from the data store. assertTrue(notifications.getNotificationsByCall(call).size() == 1); // Delete the notification. notifications.removeNotificationsByCall(call); // Validate that the notification was removed. assertTrue(notifications.getNotificationsByCall(call).size() == 0); } @Test public void testByLogLevel() { final Sid sid = Sid.generate(Sid.Type.NOTIFICATION); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid call = Sid.generate(Sid.Type.CALL); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final String method = "GET"; final Notification.Builder builder = Notification.builder(); builder.setSid(sid); builder.setAccountSid(account); builder.setCallSid(call); builder.setApiVersion("2012-04-24"); builder.setLog(0); builder.setErrorCode(11100); builder.setMoreInfo(url); builder.setMessageText("hello world!"); builder.setMessageDate(DateTime.now()); builder.setRequestUrl(url); builder.setRequestMethod(method); builder.setRequestVariables("hello world!"); builder.setResponseHeaders("hello world!"); builder.setResponseBody("hello world!"); builder.setUri(url); Notification notification = builder.build(); final NotificationsDao notifications = manager.getNotificationsDao(); // Create a new notification in the data store. notifications.addNotification(notification); // Read the notification from the data store (remember that there are already notifications in the test DB, so we expect 4 existing already with log level 0 plus this one) assertTrue(notifications.getNotificationsByLogLevel(0).size() == 5); // Delete the notification. notifications.removeNotification(sid); // Validate that the notification was removed. assertTrue(notifications.getNotification(sid) == null); } @Test public void testByMessageDate() { final Sid sid = Sid.generate(Sid.Type.NOTIFICATION); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid call = Sid.generate(Sid.Type.CALL); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final String method = "GET"; final Notification.Builder builder = Notification.builder(); builder.setSid(sid); builder.setAccountSid(account); builder.setCallSid(call); builder.setApiVersion("2012-04-24"); builder.setLog(0); builder.setErrorCode(11100); builder.setMoreInfo(url); builder.setMessageText("hello world!"); final DateTime now = DateTime.now(); builder.setMessageDate(now); builder.setRequestUrl(url); builder.setRequestMethod(method); builder.setRequestVariables("hello world!"); builder.setResponseHeaders("hello world!"); builder.setResponseBody("hello world!"); builder.setUri(url); Notification notification = builder.build(); final NotificationsDao notifications = manager.getNotificationsDao(); // Create a new notification in the data store. notifications.addNotification(notification); // Read the notification from the data store. assertTrue(notifications.getNotificationsByMessageDate(now).size() == 1); // Delete the notification. notifications.removeNotification(sid); // Validate that the notification was removed. assertTrue(notifications.getNotification(sid) == null); } @Test public void filterWithDateSorting() throws ParseException { NotificationsDao dao = manager.getNotificationsDao(); NotificationFilter.Builder builder = new NotificationFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("ACae6e420f425248d6a26948c17a9e2acf"); builder.byAccountSidSet(accountSidSet); builder.sortedByDate(Sorting.Direction.ASC); NotificationFilter filter = builder.build(); List<Notification> notifications = dao.getNotifications(filter); assertEquals(10, notifications.size()); final DateTime min = DateTime.parse("2013-08-30T16:28:33.403"); final DateTime max = DateTime.parse("2013-09-02T16:28:33.403"); assertEquals(0, min.compareTo(notifications.get(0).getDateCreated())); assertEquals(0, max.compareTo(notifications.get(notifications.size() - 1).getDateCreated())); builder.sortedByDate(Sorting.Direction.DESC); filter = builder.build(); notifications = dao.getNotifications(filter); assertEquals(0, max.compareTo(notifications.get(0).getDateCreated())); assertEquals(0, min.compareTo(notifications.get(notifications.size() - 1).getDateCreated())); } @Test public void filterWithLogSorting() throws ParseException { NotificationsDao dao = manager.getNotificationsDao(); NotificationFilter.Builder builder = new NotificationFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("ACae6e420f425248d6a26948c17a9e2acf"); builder.byAccountSidSet(accountSidSet); builder.sortedByLog(Sorting.Direction.ASC); NotificationFilter filter = builder.build(); List<Notification> notifications = dao.getNotifications(filter); assertEquals(10, notifications.size()); assertEquals("0", notifications.get(0).getLog().toString()); assertEquals("1", notifications.get(notifications.size() - 1).getLog().toString()); builder.sortedByLog(Sorting.Direction.DESC); filter = builder.build(); notifications = dao.getNotifications(filter); assertEquals("1", notifications.get(0).getLog().toString()); assertEquals("0", notifications.get(notifications.size() - 1).getLog().toString()); } @Test public void filterWithErrorCodeSorting() throws ParseException { NotificationsDao dao = manager.getNotificationsDao(); NotificationFilter.Builder builder = new NotificationFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("ACae6e420f425248d6a26948c17a9e2acf"); builder.byAccountSidSet(accountSidSet); builder.sortedByErrorCode(Sorting.Direction.ASC); NotificationFilter filter = builder.build(); List<Notification> notifications = dao.getNotifications(filter); assertEquals(10, notifications.size()); assertEquals("0", notifications.get(0).getErrorCode().toString()); assertEquals("100", notifications.get(notifications.size() - 1).getErrorCode().toString()); builder.sortedByErrorCode(Sorting.Direction.DESC); filter = builder.build(); notifications = dao.getNotifications(filter); assertEquals("100", notifications.get(0).getErrorCode().toString()); assertEquals("0", notifications.get(notifications.size() - 1).getErrorCode().toString()); } @Test public void filterWithCallSidSorting() throws ParseException { NotificationsDao dao = manager.getNotificationsDao(); NotificationFilter.Builder builder = new NotificationFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("ACae6e420f425248d6a26948c17a9e2acf"); builder.byAccountSidSet(accountSidSet); builder.sortedByCallSid(Sorting.Direction.ASC); NotificationFilter filter = builder.build(); List<Notification> notifications = dao.getNotifications(filter); assertEquals(10, notifications.size()); assertEquals("CA5EB00000000000000000000000000002", notifications.get(0).getCallSid().toString()); assertEquals("CA5EB00000000000000000000000000009", notifications.get(notifications.size() - 1).getCallSid().toString()); builder.sortedByCallSid(Sorting.Direction.DESC); filter = builder.build(); notifications = dao.getNotifications(filter); assertEquals("CA5EB00000000000000000000000000009", notifications.get(0).getCallSid().toString()); assertEquals("CA5EB00000000000000000000000000002", notifications.get(notifications.size() - 1).getCallSid().toString()); } @Test public void filterWithMessageTextSorting() throws ParseException { NotificationsDao dao = manager.getNotificationsDao(); NotificationFilter.Builder builder = new NotificationFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("ACae6e420f425248d6a26948c17a9e2acf"); builder.byAccountSidSet(accountSidSet); builder.sortedByMessageText(Sorting.Direction.ASC); NotificationFilter filter = builder.build(); List<Notification> notifications = dao.getNotifications(filter); assertEquals(10, notifications.size()); assertEquals("Another fictitious message for testing", notifications.get(0).getMessageText()); assertEquals("Workspace migration skipped in 2016-12-28 21:12:25.758", notifications.get(notifications.size() - 1).getMessageText()); builder.sortedByMessageText(Sorting.Direction.DESC); filter = builder.build(); notifications = dao.getNotifications(filter); assertEquals("Workspace migration skipped in 2016-12-28 21:12:25.758", notifications.get(0).getMessageText()); assertEquals("Another fictitious message for testing", notifications.get(notifications.size() - 1).getMessageText()); } }
18,289
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GatewaysDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/GatewaysDaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.io.InputStream; import java.net.URI; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.dao.GatewaysDao; import org.restcomm.connect.dao.entities.Gateway; import org.restcomm.connect.commons.dao.Sid; /** * @author [email protected] (Thomas Quintana) */ public final class GatewaysDaoTest { private static MybatisDaoManager manager; public GatewaysDaoTest() { super(); } @Before public void before() { final InputStream data = getClass().getResourceAsStream("/mybatis.xml"); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() { manager.shutdown(); } @Test public void createReadUpdateDelete() { final Sid sid = Sid.generate(Sid.Type.GATEWAY); final URI uri = URI.create("hello-world.xml"); final Gateway.Builder builder = Gateway.builder(); builder.setSid(sid); builder.setFriendlyName("Service Provider"); builder.setPassword("1234"); builder.setProxy("sip:127.0.0.1:5080"); builder.setRegister(true); builder.setUserName("alice"); builder.setTimeToLive(3600); builder.setUri(uri); Gateway gateway = builder.build(); final GatewaysDao gateways = manager.getGatewaysDao(); // Create a new gateway in the data store. gateways.addGateway(gateway); // Read the gateway from the data store. Gateway result = gateways.getGateway(sid); // Validate the results. assertTrue(result.getSid().equals(gateway.getSid())); assertTrue(result.getFriendlyName().equals(gateway.getFriendlyName())); assertTrue(result.getPassword().equals(gateway.getPassword())); assertTrue(result.getProxy().equals(gateway.getProxy())); assertTrue(result.register() == gateway.register()); assertTrue(result.getUserName().equals(gateway.getUserName())); assertTrue(result.getTimeToLive() == gateway.getTimeToLive()); assertTrue(result.getUri().equals(gateway.getUri())); // Update the gateway. gateway = gateway.setFriendlyName("Provider Service"); gateway = gateway.setPassword("4321"); gateway = gateway.setProxy("sip:127.0.0.1:5070"); gateway = gateway.setRegister(false); gateway = gateway.setTimeToLive(0); gateway = gateway.setUserName("bob"); gateways.updateGateway(gateway); // Read the updated gateway from the data store. result = gateways.getGateway(sid); // Validate the results. assertTrue(result.getSid().equals(gateway.getSid())); assertTrue(result.getFriendlyName().equals(gateway.getFriendlyName())); assertTrue(result.getPassword().equals(gateway.getPassword())); assertTrue(result.getProxy().equals(gateway.getProxy())); assertTrue(result.register() == gateway.register()); assertTrue(result.getUserName().equals(gateway.getUserName())); assertTrue(result.getTimeToLive() == gateway.getTimeToLive()); assertTrue(result.getUri().equals(gateway.getUri())); // Delete the gateway. gateways.removeGateway(sid); // Validate that the client was removed. assertTrue(gateways.getGateway(sid) == null); assertTrue(gateways.getGateways().size() == 0); } }
4,577
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GeolocationsDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/GeolocationsDaoTest.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 java.io.InputStream; import java.net.URI; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import static org.junit.Assert.*; import org.junit.Test; import org.restcomm.connect.dao.GeolocationDao; import org.restcomm.connect.dao.entities.Geolocation; import org.restcomm.connect.dao.entities.Geolocation.GeolocationType; import org.restcomm.connect.commons.dao.Sid; /** * @author <a href="mailto:[email protected]"> Fernando Mendioroz </a> * */ public class GeolocationsDaoTest { private static MybatisDaoManager manager; public GeolocationsDaoTest() { super(); } @Before public void before() { final InputStream data = getClass().getResourceAsStream("/mybatis.xml"); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() { manager.shutdown(); } @Test public void geolocationCreateReadUpdateDelete() { final Sid sid = Sid.generate(Sid.Type.GEOLOCATION); final Sid accountSid = Sid.generate(Sid.Type.ACCOUNT); URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/geolocation-hello-world.xml"); final Geolocation.Builder builder = Geolocation.builder(); builder.setSid(sid); DateTime currentDateTime = DateTime.now(); builder.setDateUpdated(currentDateTime); builder.setAccountSid(accountSid); builder.setSource("mlpclient1"); builder.setDeviceIdentifier("device1"); builder.setGeolocationType(GeolocationType.Immediate); builder.setResponseStatus("successfull"); builder.setCause("NA"); builder.setCellId("12345"); builder.setLocationAreaCode("978"); builder.setMobileCountryCode(748); builder.setMobileNetworkCode("03"); builder.setNetworkEntityAddress((long) 59848779); builder.setAgeOfLocationInfo(0); builder.setDeviceLatitude("105.638643"); builder.setDeviceLongitude("172.4394389"); builder.setAccuracy((long) 7845); builder.setInternetAddress("2001:0:9d38:6ab8:30a5:1c9d:58c6:5898"); builder.setPhysicalAddress("D8-97-BA-19-02-D8"); builder.setFormattedAddress("Avenida Brasil 2681, 11500, Montevideo, Uruguay"); builder.setLocationTimestamp(currentDateTime); builder.setEventGeofenceLatitude("-33.426280"); builder.setEventGeofenceLongitude("-70.566560"); builder.setRadius((long) 1500); builder.setGeolocationPositioningType("Network"); builder.setLastGeolocationResponse("true"); builder.setApiVersion("2012-04-24"); builder.setUri(url); Geolocation geolocation = builder.build(); final GeolocationDao geolocations = manager.getGeolocationDao(); // Create a new Geolocation in the data store. geolocations.addGeolocation(geolocation); // Read the Geolocation from the data store. Geolocation result = geolocations.getGeolocation(sid); // Validate the results. assertTrue(result.getSid().equals(geolocation.getSid())); assertTrue(result.getAccountSid().equals(geolocation.getAccountSid())); assertTrue(result.getDateUpdated().equals(geolocation.getDateUpdated())); assertTrue(result.getSource().equals(geolocation.getSource())); assertTrue(result.getDeviceIdentifier().equals(geolocation.getDeviceIdentifier())); assertTrue(result.getGeolocationType().equals(geolocation.getGeolocationType())); assertTrue(result.getResponseStatus().equals(geolocation.getResponseStatus())); assertTrue(result.getCause() == geolocation.getCause()); assertTrue(result.getCellId().equals(geolocation.getCellId())); assertTrue(result.getLocationAreaCode().equals(geolocation.getLocationAreaCode())); assertTrue(result.getMobileCountryCode().equals(geolocation.getMobileCountryCode())); assertTrue(result.getMobileNetworkCode().equals(geolocation.getMobileNetworkCode())); assertTrue(result.getNetworkEntityAddress().equals(geolocation.getNetworkEntityAddress())); assertTrue(result.getAgeOfLocationInfo().equals(geolocation.getAgeOfLocationInfo())); assertTrue(result.getDeviceLatitude().equals(geolocation.getDeviceLatitude())); assertTrue(result.getDeviceLongitude().equals(geolocation.getDeviceLongitude())); assertTrue(result.getAccuracy().equals(geolocation.getAccuracy())); assertTrue(result.getInternetAddress().equals(geolocation.getInternetAddress())); assertTrue(result.getPhysicalAddress().equals(geolocation.getPhysicalAddress())); assertTrue(result.getFormattedAddress().equals(geolocation.getFormattedAddress())); assertTrue(result.getLocationTimestamp().equals(geolocation.getLocationTimestamp())); assertTrue(result.getEventGeofenceLatitude().equals(geolocation.getEventGeofenceLatitude())); assertTrue(result.getEventGeofenceLongitude().equals(geolocation.getEventGeofenceLongitude())); assertTrue(result.getRadius() == geolocation.getRadius()); assertTrue(result.getGeolocationPositioningType().equals(geolocation.getGeolocationPositioningType())); assertTrue(result.getLastGeolocationResponse().equals(geolocation.getLastGeolocationResponse())); assertTrue(result.getApiVersion().equals(geolocation.getApiVersion())); assertTrue(result.getUri().equals(geolocation.getUri())); // Update the Geolocation // deviceIdentifier, statusCallback and geolocationType can not be updated once created URI url2 = URI.create("http://127.0.0.1:8080/restcomm/demos/geolocation-hello.xml"); geolocation = geolocation.setDateUpdated(currentDateTime); geolocation = geolocation.setSource("ble001"); geolocation = geolocation.setResponseStatus("failed"); geolocation = geolocation.setCause("API not compliant"); geolocation = geolocation.setCellId("00010"); geolocation = geolocation.setLocationAreaCode("0A1"); geolocation = geolocation.setMobileCountryCode(1); geolocation = geolocation.setMobileNetworkCode("33"); geolocation = geolocation.setAgeOfLocationInfo(1); geolocation = geolocation.setDeviceLatitude("-1.638643"); geolocation = geolocation.setDeviceLongitude("-172.4394389"); geolocation = geolocation.setAccuracy((long) 9876352); geolocation = geolocation.setInternetAddress("200.0.91.253"); geolocation = geolocation.setPhysicalAddress("A1-DD-0A-27-92-00"); geolocation = geolocation.setFormattedAddress("27NW Street, 23456, Greenwich, Ireland"); geolocation = geolocation.setLocationTimestamp(currentDateTime); geolocation = geolocation.setEventGeofenceLatitude("33.426280"); geolocation = geolocation.setEventGeofenceLongitude("70.426280"); geolocation = geolocation.setRadius((long) 99999); geolocation = geolocation.setGeolocationPositioningType("GPS"); geolocation = geolocation.setLastGeolocationResponse("false"); geolocation = geolocation.setUri(url2); // Update the Geolocation in the data store g geolocations.updateGeolocation(geolocation); // Read the updated Geolocation from the data store result = geolocations.getGeolocation(sid); // Validate the results assertTrue(result.getDateUpdated().equals(geolocation.getDateUpdated())); assertTrue(result.getAccountSid().equals(geolocation.getAccountSid())); assertTrue(result.getSource().equals(geolocation.getSource())); assertTrue(result.getResponseStatus().equals(geolocation.getResponseStatus())); assertTrue(result.getCause() == geolocation.getCause()); assertTrue(result.getCellId().equals(geolocation.getCellId())); assertTrue(result.getLocationAreaCode().equals(geolocation.getLocationAreaCode())); assertTrue(result.getMobileCountryCode().equals(geolocation.getMobileCountryCode())); assertTrue(result.getMobileNetworkCode().equals(geolocation.getMobileNetworkCode())); assertTrue(result.getNetworkEntityAddress().equals(geolocation.getNetworkEntityAddress())); assertTrue(result.getAgeOfLocationInfo().equals(geolocation.getAgeOfLocationInfo())); assertTrue(result.getDeviceLatitude().equals(geolocation.getDeviceLatitude())); assertTrue(result.getDeviceLongitude().equals(geolocation.getDeviceLongitude())); assertTrue(result.getAccuracy().equals(geolocation.getAccuracy())); assertTrue(result.getInternetAddress().equals(geolocation.getInternetAddress())); assertTrue(result.getPhysicalAddress().equals(geolocation.getPhysicalAddress())); assertTrue(result.getFormattedAddress().equals(geolocation.getFormattedAddress())); assertTrue(result.getLocationTimestamp().equals(geolocation.getLocationTimestamp())); assertTrue(result.getEventGeofenceLatitude().equals(geolocation.getEventGeofenceLatitude())); assertTrue(result.getEventGeofenceLongitude().equals(geolocation.getEventGeofenceLongitude())); assertTrue(result.getRadius().equals(geolocation.getRadius())); assertTrue(result.getGeolocationPositioningType().equals(geolocation.getGeolocationPositioningType())); assertTrue(result.getLastGeolocationResponse().equals(geolocation.getLastGeolocationResponse())); // Delete the Geolocation record geolocations.removeGeolocation(sid); // Validate the Geolocation record was removed. assertTrue(geolocations.getGeolocation(sid) == null); } @Test public void geolocationReadDeleteByAccountSid() { final Sid sid = Sid.generate(Sid.Type.GEOLOCATION); final Sid accountSid = Sid.generate(Sid.Type.ACCOUNT); URI url = URI.create("geolocation-hello-world.xml"); final Geolocation.Builder builder = Geolocation.builder(); builder.setSid(sid); DateTime currentDateTime = DateTime.now(); builder.setDateUpdated(currentDateTime); builder.setAccountSid(accountSid); builder.setSource("mlpClient1"); builder.setDeviceIdentifier("59899770937"); builder.setGeolocationType(GeolocationType.Immediate); builder.setResponseStatus("successfull"); builder.setCause("NA"); builder.setCellId("12345"); builder.setLocationAreaCode("978"); builder.setMobileCountryCode(748); builder.setMobileNetworkCode("03"); builder.setNetworkEntityAddress((long) 59848779); builder.setAgeOfLocationInfo(0); builder.setDeviceLatitude("105.638643"); builder.setDeviceLongitude("172.4394389"); builder.setAccuracy((long) 7845); builder.setInternetAddress("2001:0:9d38:6ab8:30a5:1c9d:58c6:5898"); builder.setPhysicalAddress("D8-97-BA-19-02-D8"); builder.setFormattedAddress("Avenida Brasil 2681, 11500, Montevideo, Uruguay"); builder.setLocationTimestamp(currentDateTime); builder.setEventGeofenceLatitude("-33.426280"); builder.setEventGeofenceLongitude("-70.566560"); builder.setRadius((long) 1500); builder.setGeolocationPositioningType("Network"); builder.setLastGeolocationResponse("true"); builder.setApiVersion("2012-04-24"); builder.setUri(url); final Geolocation geolocation = builder.build(); final GeolocationDao geolocations = manager.getGeolocationDao(); // Create a new Geolocation in the data store. geolocations.addGeolocation(geolocation); // Get all the Geolocations for a specific account. assertTrue(geolocations.getGeolocations(accountSid) != null); // Remove the Geolocations for a specific account. geolocations.removeGeolocation(accountSid); // Validate that the Geolocation were removed. assertTrue(geolocations.getGeolocation(accountSid) == null); } }
13,290
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CallDetailRecordsDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/CallDetailRecordsDaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import java.io.FileInputStream; import java.io.InputStream; import java.math.BigDecimal; import java.net.URI; import java.text.ParseException; import java.util.ArrayList; import java.util.Currency; import java.util.List; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.CallDetailRecordsDao; import org.restcomm.connect.dao.entities.CallDetailRecord; import org.restcomm.connect.dao.entities.CallDetailRecordFilter; import junit.framework.Assert; import static org.junit.Assert.assertNull; import org.junit.FixMethodOrder; import org.junit.Rule; import org.junit.rules.TestName; import org.junit.runners.MethodSorters; import org.restcomm.connect.dao.common.Sorting; /** * @author [email protected] (Thomas Quintana) */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class CallDetailRecordsDaoTest extends DaoTest { @Rule public TestName name = new TestName(); private static MybatisDaoManager manager; public CallDetailRecordsDaoTest() { super(); } @Before public void before() throws Exception { //use testmethod name to further ensure uniqueness of tmp dir sandboxRoot = createTempDir("cdrTest" + name.getMethodName()); String mybatisFilesPath = getClass().getResource("/callDetailRecordsDao").getFile(); setupSandbox(mybatisFilesPath, sandboxRoot); String mybatisXmlPath = sandboxRoot.getPath() + "/mybatis_updated.xml"; final InputStream data = new FileInputStream(mybatisXmlPath); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() { manager.shutdown(); removeTempDir(sandboxRoot.getAbsolutePath()); } @Test public void createReadUpdateDelete() { final Sid sid = Sid.generate(Sid.Type.CALL); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid parent = Sid.generate(Sid.Type.CALL); final Sid phone = Sid.generate(Sid.Type.PHONE_NUMBER); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(sid); builder.setInstanceId(instanceId.toString()); builder.setParentCallSid(parent); builder.setDateCreated(DateTime.now()); builder.setAccountSid(account); builder.setTo("+12223334444"); builder.setFrom("+17778889999"); builder.setPhoneNumberSid(phone); builder.setStatus("queued"); builder.setStartTime(DateTime.now()); builder.setEndTime(DateTime.now()); builder.setDuration(1); builder.setPrice(new BigDecimal("0.00")); builder.setPriceUnit(Currency.getInstance("USD")); builder.setDirection("outbound-api"); builder.setApiVersion("2012-04-24"); builder.setCallerName("Alice"); builder.setUri(url); CallDetailRecord cdr = builder.build(); final CallDetailRecordsDao cdrs = manager.getCallDetailRecordsDao(); // Create a new CDR in the data store. cdrs.addCallDetailRecord(cdr); // Read the CDR from the data store. CallDetailRecord result = cdrs.getCallDetailRecord(sid); // Validate the results. assertTrue(result.getSid().equals(cdr.getSid())); assertTrue(result.getParentCallSid().equals(cdr.getParentCallSid())); assertTrue(result.getDateCreated().equals(cdr.getDateCreated())); assertTrue(result.getAccountSid().equals(cdr.getAccountSid())); assertTrue(result.getTo().equals(cdr.getTo())); assertTrue(result.getFrom().equals(cdr.getFrom())); assertTrue(result.getPhoneNumberSid().equals(cdr.getPhoneNumberSid())); assertTrue(result.getStatus().equals(cdr.getStatus())); assertTrue(result.getStartTime().equals(cdr.getStartTime())); assertTrue(result.getEndTime().equals(cdr.getEndTime())); assertTrue(result.getDuration().equals(cdr.getDuration())); assertTrue(result.getPrice().equals(cdr.getPrice())); assertTrue(result.getPriceUnit().equals(cdr.getPriceUnit())); assertTrue(result.getDirection().equals(cdr.getDirection())); assertTrue(result.getApiVersion().equals(cdr.getApiVersion())); assertTrue(result.getCallerName().equals(cdr.getCallerName())); assertTrue(result.getUri().equals(cdr.getUri())); // Update the CDR. cdr = cdr.setDuration(2); cdr = cdr.setPrice(new BigDecimal("1.00")); cdr = cdr.setStatus("in-progress"); cdrs.updateCallDetailRecord(cdr); // Read the updated CDR from the data store. result = cdrs.getCallDetailRecord(sid); // Validate the results. assertTrue(result.getStatus().equals(cdr.getStatus())); assertTrue(result.getDuration().equals(cdr.getDuration())); assertTrue(result.getPrice().equals(cdr.getPrice())); assertTrue(result.getPriceUnit().equals(cdr.getPriceUnit())); // Delete the CDR. cdrs.removeCallDetailRecord(sid); // Validate that the CDR was removed. assertNull(cdrs.getCallDetailRecord(sid)); } @Test public void testReadDeleteByAccount() { final Sid sid = Sid.generate(Sid.Type.CALL); final String instanceId = Sid.generate(Sid.Type.INSTANCE).toString(); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid parent = Sid.generate(Sid.Type.CALL); final Sid phone = Sid.generate(Sid.Type.PHONE_NUMBER); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(sid); builder.setInstanceId(instanceId); builder.setParentCallSid(parent); builder.setDateCreated(DateTime.now()); builder.setAccountSid(account); builder.setTo("+12223334444"); builder.setFrom("+17778889999"); builder.setPhoneNumberSid(phone); builder.setStatus("queued"); builder.setStartTime(DateTime.now()); builder.setEndTime(DateTime.now()); builder.setDuration(1); builder.setPrice(new BigDecimal("0.00")); builder.setPriceUnit(Currency.getInstance("JPY")); builder.setDirection("outbound-api"); builder.setApiVersion("2012-04-24"); builder.setCallerName("Alice"); builder.setUri(url); CallDetailRecord cdr = builder.build(); final CallDetailRecordsDao cdrs = manager.getCallDetailRecordsDao(); // Create a new CDR in the data store. cdrs.addCallDetailRecord(cdr); // Validate the results. assertEquals(1, cdrs.getCallDetailRecordsByAccountSid(account).size()); // Delete the CDR. cdrs.removeCallDetailRecords(account); // Validate that the CDRs were removed. assertEquals(0, cdrs.getCallDetailRecordsByAccountSid(account).size()); } public void testReadByRecipient() { final Sid sid = Sid.generate(Sid.Type.CALL); final String instanceId = Sid.generate(Sid.Type.INSTANCE).toString(); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid parent = Sid.generate(Sid.Type.CALL); final Sid phone = Sid.generate(Sid.Type.PHONE_NUMBER); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(sid); builder.setInstanceId(instanceId); builder.setParentCallSid(parent); builder.setDateCreated(DateTime.now()); builder.setAccountSid(account); builder.setTo("+12223334444"); builder.setFrom("+17778889999"); builder.setPhoneNumberSid(phone); builder.setStatus("queued"); builder.setStartTime(DateTime.now()); builder.setEndTime(DateTime.now()); builder.setDuration(1); builder.setPrice(new BigDecimal("0.00")); builder.setPriceUnit(Currency.getInstance("EUR")); builder.setDirection("outbound-api"); builder.setApiVersion("2012-04-24"); builder.setCallerName("Alice"); builder.setUri(url); CallDetailRecord cdr = builder.build(); final CallDetailRecordsDao cdrs = manager.getCallDetailRecordsDao(); // Create a new CDR in the data store. cdrs.addCallDetailRecord(cdr); // Validate the results. assertEquals(1, cdrs.getCallDetailRecordsByRecipient("+12223334444").size()); // Delete the CDR. cdrs.removeCallDetailRecord(sid); // Validate that the CDRs were removed. assertNull(cdrs.getCallDetailRecord(sid) == null); } public void testReadBySender() { final Sid sid = Sid.generate(Sid.Type.CALL); final String instanceId = Sid.generate(Sid.Type.INSTANCE).toString(); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid parent = Sid.generate(Sid.Type.CALL); final Sid phone = Sid.generate(Sid.Type.PHONE_NUMBER); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(sid); builder.setInstanceId(instanceId); builder.setParentCallSid(parent); builder.setDateCreated(DateTime.now()); builder.setAccountSid(account); builder.setTo("+12223334444"); builder.setFrom("+17778889999"); builder.setPhoneNumberSid(phone); builder.setStatus("queued"); builder.setStartTime(DateTime.now()); builder.setEndTime(DateTime.now()); builder.setDuration(1); builder.setPrice(new BigDecimal("0.00")); builder.setPriceUnit(Currency.getInstance("USD")); builder.setDirection("outbound-api"); builder.setApiVersion("2012-04-24"); builder.setCallerName("Alice"); builder.setUri(url); CallDetailRecord cdr = builder.build(); final CallDetailRecordsDao cdrs = manager.getCallDetailRecordsDao(); // Create a new CDR in the data store. cdrs.addCallDetailRecord(cdr); // Validate the results. assertEquals(1, cdrs.getCallDetailRecordsByRecipient("+17778889999").size()); // Delete the CDR. cdrs.removeCallDetailRecord(sid); // Validate that the CDRs were removed. assertNull(cdrs.getCallDetailRecord(sid)); } public void testReadByStatus() { final Sid sid = Sid.generate(Sid.Type.CALL); final String instanceId = Sid.generate(Sid.Type.INSTANCE).toString(); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid parent = Sid.generate(Sid.Type.CALL); final Sid phone = Sid.generate(Sid.Type.PHONE_NUMBER); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(sid); builder.setInstanceId(instanceId); builder.setParentCallSid(parent); builder.setDateCreated(DateTime.now()); builder.setAccountSid(account); builder.setTo("+12223334444"); builder.setFrom("+17778889999"); builder.setPhoneNumberSid(phone); builder.setStatus("queued"); builder.setStartTime(DateTime.now()); builder.setEndTime(DateTime.now()); builder.setDuration(1); builder.setPrice(new BigDecimal("0.00")); builder.setPriceUnit(Currency.getInstance("CZK")); builder.setDirection("outbound-api"); builder.setApiVersion("2012-04-24"); builder.setCallerName("Alice"); builder.setUri(url); CallDetailRecord cdr = builder.build(); final CallDetailRecordsDao cdrs = manager.getCallDetailRecordsDao(); // Create a new CDR in the data store. cdrs.addCallDetailRecord(cdr); // Validate the results. assertEquals(1, cdrs.getCallDetailRecordsByStatus("queued").size()); // Delete the CDR. cdrs.removeCallDetailRecord(sid); // Validate that the CDRs were removed. assertNull(cdrs.getCallDetailRecord(sid)); } @Test public void testReadByStartTime() { final Sid sid = Sid.generate(Sid.Type.CALL); final String instanceId = Sid.generate(Sid.Type.INSTANCE).toString(); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid parent = Sid.generate(Sid.Type.CALL); final Sid phone = Sid.generate(Sid.Type.PHONE_NUMBER); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(sid); builder.setInstanceId(instanceId); builder.setParentCallSid(parent); builder.setDateCreated(DateTime.now()); builder.setAccountSid(account); builder.setTo("+12223334444"); builder.setFrom("+17778889999"); builder.setPhoneNumberSid(phone); builder.setStatus("queued"); final DateTime now = DateTime.now(); builder.setStartTime(now); builder.setEndTime(now); builder.setDuration(1); builder.setPrice(new BigDecimal("0.00")); builder.setPriceUnit(Currency.getInstance("AUD")); builder.setDirection("outbound-api"); builder.setApiVersion("2012-04-24"); builder.setCallerName("Alice"); builder.setUri(url); CallDetailRecord cdr = builder.build(); final CallDetailRecordsDao cdrs = manager.getCallDetailRecordsDao(); // Create a new CDR in the data store. cdrs.addCallDetailRecord(cdr); // Validate the results. assertEquals(1, cdrs.getCallDetailRecordsByStartTime(now).size()); // Delete the CDR. cdrs.removeCallDetailRecord(sid); // Validate that the CDRs were removed. assertNull(cdrs.getCallDetailRecord(sid)); } @Test public void testReadByEndTime() { final Sid sid = Sid.generate(Sid.Type.CALL); final String instanceId = Sid.generate(Sid.Type.INSTANCE).toString(); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid parent = Sid.generate(Sid.Type.CALL); final Sid phone = Sid.generate(Sid.Type.PHONE_NUMBER); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(sid); builder.setInstanceId(instanceId); builder.setParentCallSid(parent); builder.setDateCreated(DateTime.now()); builder.setAccountSid(account); builder.setTo("+12223334444"); builder.setFrom("+17778889999"); builder.setPhoneNumberSid(phone); builder.setStatus("queued"); final DateTime now = DateTime.now(); builder.setStartTime(now); builder.setEndTime(now); builder.setDuration(1); builder.setPrice(new BigDecimal("0.00")); builder.setPriceUnit(Currency.getInstance("AUD")); builder.setDirection("outbound-api"); builder.setApiVersion("2012-04-24"); builder.setCallerName("Alice"); builder.setUri(url); builder.setMsId("msId"); CallDetailRecord cdr = builder.build(); final CallDetailRecordsDao cdrs = manager.getCallDetailRecordsDao(); int beforeAdding = cdrs.getCallDetailRecordsByEndTime(now).size(); // Create a new CDR in the data store. cdrs.addCallDetailRecord(cdr); // Validate the results, including the ones matching in the script(10) assertEquals(beforeAdding + 1, cdrs.getCallDetailRecordsByEndTime(now).size()); // Delete the CDR. cdrs.removeCallDetailRecord(sid); // Validate that the CDRs were removed. assertNull(cdrs.getCallDetailRecord(sid)); } public void testReadByParentCall() { final Sid sid = Sid.generate(Sid.Type.CALL); final String instanceId = Sid.generate(Sid.Type.INSTANCE).toString(); final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid parent = Sid.generate(Sid.Type.CALL); final Sid phone = Sid.generate(Sid.Type.PHONE_NUMBER); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final CallDetailRecord.Builder builder = CallDetailRecord.builder(); builder.setSid(sid); builder.setInstanceId(instanceId); builder.setParentCallSid(parent); builder.setDateCreated(DateTime.now()); builder.setAccountSid(account); builder.setTo("+12223334444"); builder.setFrom("+17778889999"); builder.setPhoneNumberSid(phone); builder.setStatus("queued"); builder.setStartTime(DateTime.now()); builder.setEndTime(DateTime.now()); builder.setDuration(1); builder.setPrice(new BigDecimal("0.00")); builder.setPriceUnit(Currency.getInstance("GBP")); builder.setDirection("outbound-api"); builder.setApiVersion("2012-04-24"); builder.setCallerName("Alice"); builder.setUri(url); CallDetailRecord cdr = builder.build(); final CallDetailRecordsDao cdrs = manager.getCallDetailRecordsDao(); // Create a new CDR in the data store. cdrs.addCallDetailRecord(cdr); // Validate the results. assertEquals(1, cdrs.getCallDetailRecordsByParentCall(parent).size()); // Delete the CDR. cdrs.removeCallDetailRecord(sid); // Validate that the CDRs were removed. assertNull(cdrs.getCallDetailRecord(sid)); } @Test public void retrieveAccountCdrsRecursively() throws ParseException { CallDetailRecordsDao dao = manager.getCallDetailRecordsDao(); /* Sample data summary 100 calls in total 12 calls belong to AC00000000000000000000000000000000 5 calls belong to AC11111111111111111111111111111111 8 calls belong to AC22222222222222222222222222222222 */ // read from a single account but using the 'accountSidSet' interface List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("AC00000000000000000000000000000000"); CallDetailRecordFilter filter = new CallDetailRecordFilter(null, accountSidSet, null, null, null, null, null, null, null, null, null); Assert.assertEquals(12, dao.getTotalCallDetailRecords(filter).intValue()); // read cdrs of three accounts accountSidSet.add("AC00000000000000000000000000000000"); accountSidSet.add("AC11111111111111111111111111111111"); accountSidSet.add("AC22222222222222222222222222222222"); Assert.assertEquals(25, dao.getTotalCallDetailRecords(filter).intValue()); // pass an empty accountSid set accountSidSet.clear(); Assert.assertEquals(0, dao.getTotalCallDetailRecords(filter).intValue()); // if both an accountSid and a accountSid set are passed, only accountSidSet is taken into account filter = new CallDetailRecordFilter("ACae6e420f425248d6a26948c17a9e2acf", accountSidSet, null, null, null, null, null, null, null, null, null); accountSidSet.add("AC00000000000000000000000000000000"); accountSidSet.add("AC11111111111111111111111111111111"); accountSidSet.add("AC22222222222222222222222222222222"); Assert.assertEquals(25, dao.getTotalCallDetailRecords(filter).intValue()); // if no (null) accountSidSet is passed the method still works filter = new CallDetailRecordFilter("AC00000000000000000000000000000000", null, null, null, null, null, null, null, null, null, null); Assert.assertEquals(12, dao.getTotalCallDetailRecords(filter).intValue()); } @Test public void filterWithDateSorting() throws ParseException { CallDetailRecordsDao dao = manager.getCallDetailRecordsDao(); CallDetailRecordFilter.Builder builder = new CallDetailRecordFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("AC00000000000000000000000000000000"); builder.byAccountSidSet(accountSidSet); builder.sortedByDate(Sorting.Direction.ASC); CallDetailRecordFilter filter = builder.build(); List<CallDetailRecord> callDetailRecords = dao.getCallDetailRecords(filter); assertEquals(12, callDetailRecords.size()); final DateTime min = DateTime.parse("2013-07-30T15:08:21.228"); final DateTime max = DateTime.parse("2013-09-10T14:03:36.496"); assertEquals(min.compareTo(callDetailRecords.get(0).getDateCreated()), 0); assertEquals(max.compareTo(callDetailRecords.get(11).getDateCreated()), 0); builder.sortedByDate(Sorting.Direction.DESC); filter = builder.build(); callDetailRecords = dao.getCallDetailRecords(filter); assertEquals(max.compareTo(callDetailRecords.get(0).getDateCreated()), 0); assertEquals(min.compareTo(callDetailRecords.get(11).getDateCreated()), 0); } @Test public void filterWithFromSorting() throws ParseException { CallDetailRecordsDao dao = manager.getCallDetailRecordsDao(); CallDetailRecordFilter.Builder builder = new CallDetailRecordFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("AC00000000000000000000000000000000"); builder.byAccountSidSet(accountSidSet); builder.sortedByFrom(Sorting.Direction.ASC); CallDetailRecordFilter filter = builder.build(); List<CallDetailRecord> callDetailRecords = dao.getCallDetailRecords(filter); assertEquals(12, callDetailRecords.size()); assertEquals("+1011420534008567", callDetailRecords.get(0).getFrom()); assertEquals("Anonymous", callDetailRecords.get(11).getFrom()); builder.sortedByFrom(Sorting.Direction.DESC); filter = builder.build(); callDetailRecords = dao.getCallDetailRecords(filter); assertEquals("Anonymous", callDetailRecords.get(0).getFrom()); assertEquals("+1011420534008567", callDetailRecords.get(11).getFrom()); } @Test public void filterWithToSorting() throws ParseException { CallDetailRecordsDao dao = manager.getCallDetailRecordsDao(); CallDetailRecordFilter.Builder builder = new CallDetailRecordFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("AC00000000000000000000000000000000"); builder.byAccountSidSet(accountSidSet); builder.sortedByTo(Sorting.Direction.ASC); CallDetailRecordFilter filter = builder.build(); List<CallDetailRecord> callDetailRecords = dao.getCallDetailRecords(filter); assertEquals(12, callDetailRecords.size()); assertEquals("+13052406432", callDetailRecords.get(0).getTo()); assertEquals("+17863580884", callDetailRecords.get(11).getTo()); builder.sortedByTo(Sorting.Direction.DESC); filter = builder.build(); callDetailRecords = dao.getCallDetailRecords(filter); assertEquals("+17863580884", callDetailRecords.get(0).getTo()); assertEquals("+13052406432", callDetailRecords.get(11).getTo()); } @Test public void filterWithDirectionSorting() throws ParseException { CallDetailRecordsDao dao = manager.getCallDetailRecordsDao(); CallDetailRecordFilter.Builder builder = new CallDetailRecordFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("AC00000000000000000000000000000000"); builder.byAccountSidSet(accountSidSet); builder.sortedByDirection(Sorting.Direction.ASC); CallDetailRecordFilter filter = builder.build(); List<CallDetailRecord> callDetailRecords = dao.getCallDetailRecords(filter); assertEquals(12, callDetailRecords.size()); assertEquals("inbound", callDetailRecords.get(0).getDirection()); assertEquals("outbound", callDetailRecords.get(11).getDirection()); builder.sortedByDirection(Sorting.Direction.DESC); filter = builder.build(); callDetailRecords = dao.getCallDetailRecords(filter); assertEquals("outbound", callDetailRecords.get(0).getDirection()); assertEquals("inbound", callDetailRecords.get(11).getDirection()); } @Test public void filterWithStatusSorting() throws ParseException { CallDetailRecordsDao dao = manager.getCallDetailRecordsDao(); CallDetailRecordFilter.Builder builder = new CallDetailRecordFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("AC00000000000000000000000000000000"); builder.byAccountSidSet(accountSidSet); builder.sortedByStatus(Sorting.Direction.ASC); CallDetailRecordFilter filter = builder.build(); List<CallDetailRecord> callDetailRecords = dao.getCallDetailRecords(filter); assertEquals(12, callDetailRecords.size()); assertEquals("completed", callDetailRecords.get(0).getStatus()); assertEquals("in-progress", callDetailRecords.get(11).getStatus()); builder.sortedByStatus(Sorting.Direction.DESC); filter = builder.build(); callDetailRecords = dao.getCallDetailRecords(filter); assertEquals("in-progress", callDetailRecords.get(0).getStatus()); assertEquals("completed", callDetailRecords.get(11).getStatus()); } @Test public void filterWithDurationSorting() throws ParseException { CallDetailRecordsDao dao = manager.getCallDetailRecordsDao(); CallDetailRecordFilter.Builder builder = new CallDetailRecordFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("AC00000000000000000000000000000000"); builder.byAccountSidSet(accountSidSet); builder.sortedByDuration(Sorting.Direction.ASC); CallDetailRecordFilter filter = builder.build(); List<CallDetailRecord> callDetailRecords = dao.getCallDetailRecords(filter); assertEquals(12, callDetailRecords.size()); assertEquals("1", callDetailRecords.get(0).getDuration().toString()); assertEquals("44", callDetailRecords.get(11).getDuration().toString()); builder.sortedByDuration(Sorting.Direction.DESC); filter = builder.build(); callDetailRecords = dao.getCallDetailRecords(filter); assertEquals("44", callDetailRecords.get(0).getDuration().toString()); assertEquals("1", callDetailRecords.get(11).getDuration().toString()); } @Test public void filterWithPriceSorting() throws ParseException { CallDetailRecordsDao dao = manager.getCallDetailRecordsDao(); CallDetailRecordFilter.Builder builder = new CallDetailRecordFilter.Builder(); List<String> accountSidSet = new ArrayList<String>(); accountSidSet.add("AC00000000000000000000000000000000"); builder.byAccountSidSet(accountSidSet); builder.sortedByPrice(Sorting.Direction.ASC); CallDetailRecordFilter filter = builder.build(); List<CallDetailRecord> callDetailRecords = dao.getCallDetailRecords(filter); assertEquals(12, callDetailRecords.size()); assertEquals("0.00", callDetailRecords.get(0).getPrice().toString()); assertEquals("120.00", callDetailRecords.get(11).getPrice().toString()); builder.sortedByPrice(Sorting.Direction.DESC); filter = builder.build(); callDetailRecords = dao.getCallDetailRecords(filter); assertEquals("120.00", callDetailRecords.get(0).getPrice().toString()); assertEquals("0.00", callDetailRecords.get(11).getPrice().toString()); } }
29,394
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApplicationRetrievalTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/ApplicationRetrievalTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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 junit.framework.Assert; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.ApplicationsDao; import org.restcomm.connect.dao.entities.Application; import java.io.FileInputStream; import java.io.InputStream; import java.util.List; /** * @author [email protected] - Orestis Tsakiridis */ public class ApplicationRetrievalTest extends DaoTest { private static MybatisDaoManager manager; public ApplicationRetrievalTest() { super(); } @Before public void before() throws Exception { sandboxRoot = createTempDir("applicationRetrievalTest"); String mybatisFilesPath = getClass().getResource("/applicationsDao").getFile(); setupSandbox(mybatisFilesPath, sandboxRoot); String mybatisXmlPath = sandboxRoot.getPath() + "/mybatis_updated.xml"; final InputStream data = new FileInputStream(mybatisXmlPath); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() throws Exception { manager.shutdown(); removeTempDir(sandboxRoot.getAbsolutePath()); } @Test public void retrieveApplications() { ApplicationsDao dao = manager.getApplicationsDao(); List<Application> apps = dao.getApplications(new Sid("ACae6e420f425248d6a26948c17a9e2acf")); Assert.assertEquals(5, apps.size()); } /** * PN00000000000000000000000000000001 is bound to AP73926e7113fa4d95981aa96b76eca854 (sms) * PN00000000000000000000000000000002 is bound to AP73926e7113fa4d95981aa96b76eca854 (both sms+ussd) * PN00000000000000000000000000000003 is bound to AP00000000000000000000000000000005. The number belong sto other account * AP00000000000000000000000000000006 belongs to other account */ @Test public void retrieveApplicationsAndTheirNumbers() { ApplicationsDao dao = manager.getApplicationsDao(); List<Application> apps = dao.getApplicationsWithNumbers(new Sid("ACae6e420f425248d6a26948c17a9e2acf")); Assert.assertEquals(5, apps.size()); Assert.assertNotNull(searchApplicationBySid(new Sid("AP73926e7113fa4d95981aa96b76eca854"),apps).getNumbers()); // applications bound with many numbers are property returned Assert.assertEquals("Three (3) numbers should be bound to this application", 3, searchApplicationBySid(new Sid("AP73926e7113fa4d95981aa96b76eca854"),apps).getNumbers().size()); // applications bound with no numbers are properly returned Assert.assertNull(searchApplicationBySid(new Sid("AP00000000000000000000000000000004"),apps).getNumbers()); // applications bound to numbers that belong to different account should not be returned (for now at least) Assert.assertNull(searchApplicationBySid(new Sid("AP00000000000000000000000000000005"),apps).getNumbers()); } private Application searchApplicationBySid(Sid sid, List<Application> apps) { if (apps != null) { int i = 0; while (i < apps.size()) { if (apps.get(i).getSid().equals(sid)) return apps.get(i); i++; } } return null; // nothing found } }
4,421
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
DaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/DaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.ConfigurationException; import org.apache.commons.configuration.XMLConfiguration; import org.apache.commons.io.FileUtils; import org.restcomm.connect.commons.configuration.RestcommConfiguration; import org.restcomm.connect.commons.dao.Sid; import java.io.File; import java.io.IOException; import java.util.Random; /** * @author [email protected] - Orestis Tsakiridis */ public class DaoTest { File sandboxRoot; // rot directory where mybatis files will be created in protected static Sid instanceId = Sid.generate(Sid.Type.INSTANCE); /** * Create a temporary directory with random name inside the system temporary directory. * Provide a prefix that will be used when creating the name too. * * @param prefix * @return */ public File createTempDir(String prefix) { String tempDirLocation = generateTempDirName(prefix); File tempDir = new File(tempDirLocation); tempDir.mkdir(); return tempDir; } private String generateTempDirName(String prefix) { String tempDirLocationRoot = System.getProperty("java.io.tmpdir"); Random ran = new Random(); return tempDirLocationRoot + "/" + prefix + ran.nextInt(10000); } /** * Remove a temporary directory. Use this to couple createTempDir(). * * @param tempDirLocation */ public void removeTempDir(String tempDirLocation) { File tempDir = new File(tempDirLocation); FileUtils.deleteQuietly(tempDir); } public static void setupSandbox(String mybatisFilesSource, File sandboxDir) throws IOException { File mybatisDir = new File(mybatisFilesSource); FileUtils.copyDirectory(mybatisDir, sandboxDir); // replace mybatis descriptors path inside sandbox mybatis.xml String mybatisXmlPath = sandboxDir.getAbsolutePath() + "/mybatis.xml"; String content = FileUtils.readFileToString(new File(mybatisXmlPath)); content = content.replaceAll("MYBATIS_SANDBOX_PATH",sandboxDir.getAbsolutePath()); FileUtils.writeStringToFile(new File(sandboxDir.getAbsolutePath() + "/mybatis_updated.xml"),content); XMLConfiguration xmlConfiguration = new XMLConfiguration(); xmlConfiguration.setDelimiterParsingDisabled(true); xmlConfiguration.setAttributeSplittingDisabled(true); try { xmlConfiguration.load("restcomm.xml"); RestcommConfiguration.createOnce(xmlConfiguration); RestcommConfiguration.getInstance().getMain().setInstanceId(instanceId.toString()); } catch (ConfigurationException e) { e.printStackTrace(); } } }
3,540
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ApplicationsDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/ApplicationsDaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.io.InputStream; import java.net.URI; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.dao.ApplicationsDao; import org.restcomm.connect.dao.entities.Application; import org.restcomm.connect.commons.dao.Sid; /** * @author [email protected] (Thomas Quintana) */ public final class ApplicationsDaoTest { private static MybatisDaoManager manager; public ApplicationsDaoTest() { super(); } @Before public void before() { final InputStream data = getClass().getResourceAsStream("/mybatis.xml"); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() { manager.shutdown(); } @Test public void createReadUpdateDelete() { final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid sid = Sid.generate(Sid.Type.APPLICATION); URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); Application.Kind kind = Application.Kind.VOICE; final Application.Builder builder = Application.builder(); builder.setSid(sid); builder.setFriendlyName("Test Application"); builder.setAccountSid(account); builder.setApiVersion("2012-04-24"); builder.setHasVoiceCallerIdLookup(false); builder.setUri(url); builder.setRcmlUrl(url); builder.setKind(kind); Application application = builder.build(); final ApplicationsDao applications = manager.getApplicationsDao(); // Create a new application in the data store. applications.addApplication(application); // Read the application from the data store. Application result = applications.getApplication(sid); // Validate the results. assertTrue(result.getSid().equals(application.getSid())); assertTrue(result.getFriendlyName().equals(application.getFriendlyName())); assertTrue(result.getAccountSid().equals(application.getAccountSid())); assertTrue(result.getApiVersion().equals(application.getApiVersion())); assertFalse(result.hasVoiceCallerIdLookup()); assertTrue(result.getUri().equals(application.getUri())); assertTrue(result.getRcmlUrl().equals(application.getRcmlUrl())); assertTrue(result.getKind().toString().equals(application.getKind().toString())); // Update the application. url = URI.create("http://127.0.0.1:8080/restcomm/demos/world-hello.xml"); kind = Application.Kind.SMS; application = application.setFriendlyName("Application Test"); application = application.setVoiceCallerIdLookup(true); application = application.setRcmlUrl(url); application = application.setKind(kind); applications.updateApplication(application); // Read the updated application from the data store. result = applications.getApplication(sid); // Validate the results. assertTrue(result.getSid().equals(application.getSid())); assertTrue(result.getFriendlyName().equals(application.getFriendlyName())); assertTrue(result.getAccountSid().equals(application.getAccountSid())); assertTrue(result.getApiVersion().equals(application.getApiVersion())); assertTrue(result.hasVoiceCallerIdLookup()); assertTrue(result.getUri().equals(application.getUri())); assertTrue(result.getRcmlUrl().equals(application.getRcmlUrl())); assertTrue(result.getKind().toString().equals(application.getKind().toString())); // Delete the application. applications.removeApplication(sid); // Validate that the application was removed. assertTrue(applications.getApplication(sid) == null); } @Test public void removeByAccountSid() { final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid sid = Sid.generate(Sid.Type.APPLICATION); URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); Application.Kind kind = Application.Kind.VOICE; final Application.Builder builder = Application.builder(); builder.setSid(sid); builder.setFriendlyName("Test Application"); builder.setAccountSid(account); builder.setApiVersion("2012-04-24"); builder.setHasVoiceCallerIdLookup(false); builder.setUri(url); builder.setRcmlUrl(url); builder.setKind(kind); Application application = builder.build(); final ApplicationsDao applications = manager.getApplicationsDao(); // Create a new application in the data store. applications.addApplication(application); assertTrue(applications.getApplications(account).size() == 1); // Delete the application. applications.removeApplications(account); assertTrue(applications.getApplications(account).size() == 0); } }
6,103
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ClientsDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/ClientsDaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import static org.junit.Assert.*; import org.junit.Test; import org.restcomm.connect.dao.AccountsDao; import org.restcomm.connect.dao.ClientsDao; import org.restcomm.connect.dao.entities.Account; import org.restcomm.connect.dao.entities.Client; import org.restcomm.connect.commons.dao.Sid; /** * @author [email protected] (Thomas Quintana) * @author maria farooq */ public final class ClientsDaoTest extends DaoTest { private static MybatisDaoManager manager; private final String realm = "org1.restcomm.com"; public ClientsDaoTest() { super(); } @Before public void before() throws IOException { sandboxRoot = createTempDir("accountsTest"); String mybatisFilesPath = getClass().getResource("/accountsDao").getFile(); setupSandbox(mybatisFilesPath, sandboxRoot); final InputStream data = getClass().getResourceAsStream("/mybatis.xml"); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() { manager.shutdown(); } @Test public void createReadUpdateDelete() { final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid sid = Sid.generate(Sid.Type.CLIENT); Sid application = Sid.generate(Sid.Type.APPLICATION); URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); String method = "GET"; final Client.Builder builder = Client.builder(); builder.setSid(sid); builder.setAccountSid(account); builder.setApiVersion("2012-04-24"); builder.setFriendlyName("Alice"); builder.setLogin("alice"); builder.setPassword("alice", "1234", realm, ""); builder.setStatus(Client.ENABLED); builder.setVoiceUrl(url); builder.setVoiceMethod(method); builder.setVoiceFallbackUrl(url); builder.setVoiceFallbackMethod(method); builder.setVoiceApplicationSid(application); builder.setUri(url); builder.setPushClientIdentity(sid.toString()); Client client = builder.build(); final ClientsDao clients = manager.getClientsDao(); // Create a new client in the data store. clients.addClient(client); // Read the client from the data store. Client result = clients.getClient(sid); // Validate the results. assertTrue(result.getSid().equals(client.getSid())); assertTrue(result.getAccountSid().equals(client.getAccountSid())); assertTrue(result.getApiVersion().equals(client.getApiVersion())); assertTrue(result.getFriendlyName().equals(client.getFriendlyName())); assertTrue(result.getLogin().equals(client.getLogin())); assertTrue(result.getPassword().equals(client.getPassword())); assertTrue(result.getStatus() == client.getStatus()); assertTrue(result.getVoiceUrl().equals(client.getVoiceUrl())); assertTrue(result.getVoiceMethod().equals(client.getVoiceMethod())); assertTrue(result.getVoiceFallbackUrl().equals(client.getVoiceFallbackUrl())); assertTrue(result.getVoiceFallbackMethod().equals(client.getVoiceFallbackMethod())); assertTrue(result.getVoiceApplicationSid().equals(client.getVoiceApplicationSid())); assertTrue(result.getUri().equals(client.getUri())); assertTrue(result.getPushClientIdentity().equals(client.getPushClientIdentity())); // Update the client. application = Sid.generate(Sid.Type.APPLICATION); url = URI.create("http://127.0.0.1:8080/restcomm/demos/world-hello.xml"); method = "POST"; String newClientIdentity = "newClientIdentity"; client = client.setFriendlyName("Bob"); client = client.setPassword(client.getLogin(), "4321", realm); client = client.setStatus(Client.DISABLED); client = client.setVoiceApplicationSid(application); client = client.setVoiceUrl(url); client = client.setVoiceMethod(method); client = client.setVoiceFallbackUrl(url); client = client.setVoiceFallbackMethod(method); client = client.setPushClientIdentity(newClientIdentity); clients.updateClient(client); // Read the updated client from the data store. result = clients.getClient(sid); // Validate the results. assertTrue(result.getFriendlyName().equals(client.getFriendlyName())); assertTrue(result.getLogin().equals(client.getLogin())); assertTrue(result.getPassword().equals(client.getPassword())); assertTrue(result.getStatus() == client.getStatus()); assertTrue(result.getVoiceUrl().equals(client.getVoiceUrl())); assertTrue(result.getVoiceMethod().equals(client.getVoiceMethod())); assertTrue(result.getVoiceFallbackUrl().equals(client.getVoiceFallbackUrl())); assertTrue(result.getVoiceFallbackMethod().equals(client.getVoiceFallbackMethod())); assertTrue(result.getVoiceApplicationSid().equals(client.getVoiceApplicationSid())); assertTrue(result.getPushClientIdentity().equals(newClientIdentity)); // Delete the client. clients.removeClient(sid); // Validate that the client was removed. assertTrue(clients.getClient(sid) == null); } @Test public void readByUser() { AccountsDao dao = manager.getAccountsDao(); Sid accountSid = Sid.generate(Sid.Type.ACCOUNT); final Sid org = Sid.generate(Sid.Type.ORGANIZATION); try { dao.addAccount(new Account(accountSid, new DateTime(), new DateTime(), "[email protected]", "Top Level Account", new Sid("AC00000000000000000000000000000000"),Account.Type.FULL,Account.Status.ACTIVE,"77f8c12cc7b8f8423e5c38b035249166","Administrator",new URI("/2012-04-24/Accounts/AC00000000000000000000000000000000"), org)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } final Sid sid = Sid.generate(Sid.Type.CLIENT); Sid application = Sid.generate(Sid.Type.APPLICATION); URI url = URI.create("hello-world.xml"); String method = "GET"; final Client.Builder builder = Client.builder(); builder.setSid(sid); builder.setAccountSid(accountSid); builder.setApiVersion("2012-04-24"); builder.setFriendlyName("Tom"); builder.setLogin("tom"); builder.setPassword("tom", "1234", realm, ""); builder.setStatus(Client.ENABLED); builder.setVoiceUrl(url); builder.setVoiceMethod(method); builder.setVoiceFallbackUrl(url); builder.setVoiceFallbackMethod(method); builder.setVoiceApplicationSid(application); builder.setUri(url); final Client client = builder.build(); final ClientsDao clients = manager.getClientsDao(); // Create a new client in the data store. clients.addClient(client); // Read the client from the data store using the user name. final Client result = clients.getClient("tom", org); // Validate the result. assertTrue(result.getSid().equals(client.getSid())); assertTrue(result.getAccountSid().equals(client.getAccountSid())); assertTrue(result.getApiVersion().equals(client.getApiVersion())); assertTrue(result.getFriendlyName().equals(client.getFriendlyName())); assertTrue(result.getLogin().equals(client.getLogin())); assertTrue(result.getPassword().equals(client.getPassword())); assertTrue(result.getStatus() == client.getStatus()); assertTrue(result.getVoiceUrl().equals(client.getVoiceUrl())); assertTrue(result.getVoiceMethod().equals(client.getVoiceMethod())); assertTrue(result.getVoiceFallbackUrl().equals(client.getVoiceFallbackUrl())); assertTrue(result.getVoiceFallbackMethod().equals(client.getVoiceFallbackMethod())); assertTrue(result.getVoiceApplicationSid().equals(client.getVoiceApplicationSid())); assertTrue(result.getUri().equals(client.getUri())); // Delete the client. clients.removeClient(sid); // Validate that the client was removed. assertTrue(clients.getClient(sid) == null); } @Test public void readDeleteByAccountSid() { final Sid account = Sid.generate(Sid.Type.ACCOUNT); final Sid sid = Sid.generate(Sid.Type.CLIENT); Sid application = Sid.generate(Sid.Type.APPLICATION); URI url = URI.create("hello-world.xml"); String method = "GET"; final Client.Builder builder = Client.builder(); builder.setSid(sid); builder.setAccountSid(account); builder.setApiVersion("2012-04-24"); builder.setFriendlyName("Tom"); builder.setLogin("tom"); builder.setPassword("tom", "1234", realm, ""); builder.setStatus(Client.ENABLED); builder.setVoiceUrl(url); builder.setVoiceMethod(method); builder.setVoiceFallbackUrl(url); builder.setVoiceFallbackMethod(method); builder.setVoiceApplicationSid(application); builder.setUri(url); final Client client = builder.build(); final ClientsDao clients = manager.getClientsDao(); // Create a new client in the data store. clients.addClient(client); // Get all the clients for a specific account. assertTrue(clients.getClients(account).size() == 1); // Remove all the clients for a specific account. clients.removeClients(account); // Validate that the clients were removed. assertTrue(clients.getClients(account).size() == 0); } }
10,999
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ConfDetailRecordsDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/ConfDetailRecordsDaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.junit.Assert.assertEquals; import java.io.InputStream; import java.net.URI; import java.util.Properties; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.Rule; import org.junit.rules.TestName; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.entities.ConferenceDetailRecord; import org.restcomm.connect.dao.entities.ConferenceRecordCountFilter; public class ConfDetailRecordsDaoTest extends DaoTest { @Rule public TestName testName = new TestName(); //RUNNING_INITIALIZING, RUNNING_MODERATOR_ABSENT, RUNNING_MODERATOR_PRESENT, STOPPING, COMPLETED, FAILED @Rule public TestName name = new TestName(); private static MybatisDaoManager manager; public ConfDetailRecordsDaoTest() { super(); } @Before public void before() { final InputStream data = getClass().getResourceAsStream("/mybatis.xml"); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); Properties props = new Properties(); props.setProperty("testcase", testName.getMethodName()); final SqlSessionFactory factory = builder.build(data, props); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() { manager.shutdown(); } @Test public void testCountByMsIdAnStatus() throws Exception { final Sid accountSid = Sid.generate(Sid.Type.ACCOUNT); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final Sid sid = Sid.generate(Sid.Type.CONFERENCE); final ConferenceDetailRecord.Builder builder = ConferenceDetailRecord.builder(); builder.setAccountSid(accountSid); builder.setApiVersion("2012-04-24"); builder.setDateCreated(DateTime.now()); builder.setFriendlyName("myconf"); builder.setMasterConfernceEndpointId("masterConEndId"); builder.setMasterIVREndpointId("masterIvrId"); builder.setMasterMsId("masterMsId"); builder.setSid(sid); builder.setStatus("RUNNING_INITIALIZING"); builder.setUri(url); ConferenceDetailRecord cdr = builder.build(); manager.getConferenceDetailRecordsDao().addConferenceDetailRecord(cdr); final Sid sid2 = Sid.generate(Sid.Type.CONFERENCE); final ConferenceDetailRecord.Builder builder2 = ConferenceDetailRecord.builder(); builder2.setAccountSid(accountSid); builder2.setApiVersion("2012-04-24"); builder2.setDateCreated(DateTime.now()); builder2.setFriendlyName("myconf"); builder2.setMasterConfernceEndpointId("masterConEndId"); builder2.setMasterIVREndpointId("masterIvrId"); builder2.setMasterMsId("masterMsId"); builder2.setSid(sid2); builder2.setStatus("RUNNING_MODERATOR_PRESENT"); builder2.setUri(url); ConferenceDetailRecord cdr2 = builder2.build(); manager.getConferenceDetailRecordsDao().addConferenceDetailRecord(cdr2); final Sid sid3 = Sid.generate(Sid.Type.CONFERENCE); final ConferenceDetailRecord.Builder builder3 = ConferenceDetailRecord.builder(); builder3.setAccountSid(accountSid); builder3.setApiVersion("2012-04-24"); builder3.setDateCreated(DateTime.now()); builder3.setFriendlyName("myconf"); builder3.setMasterConfernceEndpointId("masterConEndId"); builder3.setMasterIVREndpointId("masterIvrId"); builder3.setMasterMsId("masterMsId"); builder3.setSid(sid3); builder3.setStatus("COMPLETED"); builder3.setUri(url); ConferenceDetailRecord cdr3 = builder3.build(); manager.getConferenceDetailRecordsDao().addConferenceDetailRecord(cdr3); ConferenceRecordCountFilter filter = ConferenceRecordCountFilter.builder(). byAccountSid(accountSid.toString()). byMasterMsId("masterMsId") .byStatus("RUNNING%").build(); Integer confCount = manager.getConferenceDetailRecordsDao().countByFilter(filter); assertEquals(Integer.valueOf(2), confCount); } @Test public void testAddRead() throws Exception { final Sid accountSid = Sid.generate(Sid.Type.ACCOUNT); final Sid sid = Sid.generate(Sid.Type.CONFERENCE); final URI url = URI.create("http://127.0.0.1:8080/restcomm/demos/hello-world.xml"); final ConferenceDetailRecord.Builder builder = ConferenceDetailRecord.builder(); builder.setAccountSid(sid); builder.setApiVersion("2012-04-24"); builder.setDateCreated(DateTime.now()); builder.setFriendlyName("myconf"); builder.setMasterConfernceEndpointId("masterConEndId"); builder.setMasterIVREndpointId("masterIvrId"); builder.setMasterMsId("masterMsId"); builder.setSid(sid); builder.setStatus("RUNNING_INITIALIZING"); builder.setUri(url); ConferenceDetailRecord cdr = builder.build(); manager.getConferenceDetailRecordsDao().addConferenceDetailRecord(cdr); ConferenceDetailRecord cdrResult = manager.getConferenceDetailRecordsDao().getConferenceDetailRecord(sid); assertEquals(cdr.getFriendlyName(), cdrResult.getFriendlyName()); } }
6,332
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OrganizationsDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/OrganizationsDaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.io.FileInputStream; import java.io.InputStream; import java.net.URISyntaxException; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.OrganizationsDao; import org.restcomm.connect.dao.entities.Organization; import junit.framework.Assert; public class OrganizationsDaoTest extends DaoTest { private static MybatisDaoManager manager; public OrganizationsDaoTest() { super(); } @Before public void before() throws Exception { sandboxRoot = createTempDir("organizationsTest"); String mybatisFilesPath = getClass().getResource("/organizationsDao").getFile(); setupSandbox(mybatisFilesPath, sandboxRoot); String mybatisXmlPath = sandboxRoot.getPath() + "/mybatis_updated.xml"; final InputStream data = new FileInputStream(mybatisXmlPath); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() throws Exception { manager.shutdown(); removeTempDir(sandboxRoot.getAbsolutePath()); } @Test public void addOrganizationsTest() throws IllegalArgumentException, URISyntaxException { OrganizationsDao dao = manager.getOrganizationsDao(); Sid sid = Sid.generate(Sid.Type.ORGANIZATION); dao.addOrganization(new Organization(sid, "test.restcomm.com", new DateTime(), new DateTime(), Organization.Status.ACTIVE)); Organization organization = dao.getOrganization(sid); Assert.assertNotNull("Organization not found",organization); Assert.assertNotNull(organization.getSid()); } @Test public void addOrganizationsTestWithDot() throws IllegalArgumentException, URISyntaxException { OrganizationsDao dao = manager.getOrganizationsDao(); Sid sid = Sid.generate(Sid.Type.ORGANIZATION); dao.addOrganization(new Organization(sid, "test.restcomm.com.", new DateTime(), new DateTime(), Organization.Status.ACTIVE)); Organization organization = dao.getOrganization(sid); Assert.assertEquals("test.restcomm.com",organization.getDomainName()); } @Test public void readOrganization() { OrganizationsDao dao = manager.getOrganizationsDao(); Organization organization = dao.getOrganization(new Sid("ORafbe225ad37541eba518a74248f0ac4d")); Assert.assertNotNull("Organization not found",organization); } @Test public void readOrganizationByDomainDomain() { OrganizationsDao dao = manager.getOrganizationsDao(); Organization organization = dao.getOrganizationByDomainName("test2.restcomm.com"); Assert.assertNotNull("Organization not found",organization); organization = dao.getOrganizationByDomainName("test2.restcomm.com."); Assert.assertNotNull("Organization not found",organization); } }
4,065
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
ProfilesDaoTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.dao/src/test/java/org/restcomm/connect/dao/mybatis/ProfilesDaoTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a 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.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URISyntaxException; import java.sql.SQLException; import java.util.Arrays; import java.util.Calendar; import java.util.List; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.dao.ProfilesDao; import org.restcomm.connect.dao.entities.Profile; import junit.framework.Assert; public class ProfilesDaoTest extends DaoTest { private static MybatisDaoManager manager; private static final String jsonProfile = "{ \"FACEnablement\": { \"destinations\": { \"allowedPrefixes\": [\"US\", \"Canada\"] }, \"outboundPSTN\": { }, \"inboundPSTN\": { }, \"outboundSMS\": { }, \"inboundSMS\": { } }}"; private static final String jsonUpdateProfile = "{ \"FACEnablement\": { \"destinations\": { \"allowedPrefixes\": [\"US\", \"Canada\", \"Pakitsan\"] }, \"outboundPSTN\": { }, \"inboundPSTN\": { }, \"outboundSMS\": { }, \"inboundSMS\": { } }}"; public ProfilesDaoTest() { super(); } @Before public void before() throws Exception { sandboxRoot = createTempDir("organizationsTest"); String mybatisFilesPath = getClass().getResource("/organizationsDao").getFile(); setupSandbox(mybatisFilesPath, sandboxRoot); String mybatisXmlPath = sandboxRoot.getPath() + "/mybatis_updated.xml"; final InputStream data = new FileInputStream(mybatisXmlPath); final SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); final SqlSessionFactory factory = builder.build(data); manager = new MybatisDaoManager(); manager.start(factory); } @After public void after() throws Exception { manager.shutdown(); removeTempDir(sandboxRoot.getAbsolutePath()); } @Test public void ProfileCRUDTest() throws IllegalArgumentException, URISyntaxException, IOException, SQLException { ProfilesDao dao = manager.getProfilesDao(); Profile profile = new Profile(Sid.generate(Sid.Type.PROFILE).toString(), jsonProfile, Calendar.getInstance().getTime(), Calendar.getInstance().getTime()); // Add Profile dao.addProfile(profile); // Read Profile Profile resultantProfile = dao.getProfile(profile.getSid()); Assert.assertNotNull(resultantProfile); Assert.assertEquals(profile.getSid(), resultantProfile.getSid()); // Assert.assertTrue(Arrays.equals(profile.getProfileDocument(), resultantProfile.getProfileDocument())); //Read Profile List List<Profile> profilelist = dao.getAllProfiles(); Assert.assertNotNull(profilelist); Assert.assertEquals(1, profilelist.size()); // Update Profile Profile updatedProfile = profile.setProfileDocument(jsonUpdateProfile); dao.updateProfile(updatedProfile); resultantProfile = dao.getProfile(updatedProfile.getSid()); Assert.assertNotNull(resultantProfile); Assert.assertEquals(updatedProfile.getSid(), resultantProfile.getSid()); // Assert.assertTrue(Arrays.equals(updatedProfile.getProfileDocument(), resultantProfile.getProfileDocument())); // Delete Profile dao.deleteProfile(updatedProfile.getSid().toString()); resultantProfile = dao.getProfile(profile.getSid()); Assert.assertNull(resultantProfile); } }
4,421
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z