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
BandwidthIncomingPhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/provisioning/number/bandwidth/BandwidthIncomingPhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.bandwidth; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import java.net.URL; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static junit.framework.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.annotations.UnstableTests; /** * Created by sbarstow on 10/14/14. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class BandwidthIncomingPhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(BandwidthIncomingPhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; static boolean numberBought = false; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 private static JsonObject jsonRespone; @Test @Category(value={UnstableTests.class}) public void testBuyNumber() { String ordersUrl = "/v1.0/accounts/12345/orders.*"; stubFor(post(urlMatching(ordersUrl)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/xml") .withBody(BandwidthIncomingPhoneNumbersEndpointTestUtils.validOrderResponseXml))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; System.out.println(provisioningURL); WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); numberBought = true; String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); this.jsonRespone = jsonResponse; System.out.println(jsonResponse.toString()); assertTrue(BandwidthIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(), BandwidthIncomingPhoneNumbersEndpointTestUtils.jSonResultPurchaseNumber)); } @Test @Category(value={UnstableTests.class}) public void testCancelNumber() { String ordersUrl = "/v1.0/accounts/12345/orders.*"; stubFor(post(urlMatching(ordersUrl)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/xml") .withBody(BandwidthIncomingPhoneNumbersEndpointTestUtils.validOrderResponseXml))); String disconnectUrl = "/v1.0/accounts/12345/disconnects.*"; stubFor(post(urlMatching(disconnectUrl)) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/xml") .withBody(BandwidthIncomingPhoneNumbersEndpointTestUtils.validDisconnectOrderResponseXml))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; System.out.println(provisioningURL); WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); JsonObject jsonResponse; if (clientResponse.getStatus()==200) { assertEquals(200, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); System.out.println(jsonResponse.toString()); assertTrue(BandwidthIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(), BandwidthIncomingPhoneNumbersEndpointTestUtils.jSonResultDeletePurchaseNumber)); } else { jsonResponse = this.jsonRespone; } String phoneNumberSid = jsonResponse.get("sid").getAsString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); } @Deployment(name = "BandwidthAvailablePhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_bandwidth_test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
9,074
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BandwidthAvailablePhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/provisioning/number/bandwidth/BandwidthAvailablePhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.bandwidth; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import java.net.URL; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Created by sbarstow on 10/7/14. */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class BandwidthAvailablePhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(BandwidthAvailablePhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; static boolean accountUpdated = false; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/AvailablePhoneNumbers/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 @Test public void testReturnAreaCodeSearch(){ stubFor(get(urlMatching("/v1.0/accounts/12345/availableNumbers.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(BandwidthAvailablePhoneNumbersEndpointTestUtils.areaCode201SearchResult))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("AreaCode","201").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); System.out.println(BandwidthAvailablePhoneNumbersEndpointTestUtils.firstJSonResult201AreaCode); assertTrue(jsonResponse.size() == 1); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(BandwidthAvailablePhoneNumbersEndpointTestUtils.firstJSonResult201AreaCode)); } @Test @Category(FeatureExpTests.class) public void testSearchAreaCode205() { stubFor(get(urlMatching("/v1.0/accounts/12345/availableNumbers.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(BandwidthAvailablePhoneNumbersEndpointTestUtils.areaCode205SearchResult))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("AreaCode","201").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); } @Test public void testReturnZipCodeSearch(){ stubFor(get(urlMatching("/v1.0/accounts/12345/availableNumbers.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(BandwidthAvailablePhoneNumbersEndpointTestUtils.zipCode27601SearchResult))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("AreaCode","201").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); assertTrue(jsonResponse.size() == 1); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(BandwidthAvailablePhoneNumbersEndpointTestUtils.firstJSONResult27601ZipCode )); } @Test @Category(FeatureAltTests.class) public void testReturnEmptyResultsSearch() { stubFor(get(urlMatching("/v1.0/accounts/12345/availableNumbers.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(BandwidthAvailablePhoneNumbersEndpointTestUtils.emptySearchResult))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); assertTrue(jsonResponse.size() == 0); } @Test @Category(FeatureExpTests.class) public void testMalformedSearchResultXml() { stubFor(get(urlMatching("/v1.0/accounts/12345/availableNumbers.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(BandwidthAvailablePhoneNumbersEndpointTestUtils.emptySearchResult))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); assertTrue(jsonResponse.size() == 0); } @Test public void testSearchForTollFreeNumbers() { stubFor(get(urlMatching("/v1.0/accounts/12345/availableNumbers.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text-json") .withBody(BandwidthAvailablePhoneNumbersEndpointTestUtils.validTollFreeSearchResult))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/TollFree.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("RangeSize","2").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 2); System.out.println(jsonResponse.get(0).getAsJsonObject().toString()); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(BandwidthAvailablePhoneNumbersEndpointTestUtils.validTollFreeJsonResult)); } @Test @Category(FeatureExpTests.class) public void testSearchForTollFreeNumbersInvalidPattern() { stubFor(get(urlMatching("/v1.0/accounts/12345/availableNumbers.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text-json") .withBody(BandwidthAvailablePhoneNumbersEndpointTestUtils.invalidTollFreeSearchResult))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/TollFree.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("RangeSize","2").queryParam("Contains", "7**").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 0); } @Deployment(name = "BandwidthAvailablePhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_bandwidth_test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
13,194
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NexmoIncomingPhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/provisioning/number/nexmo/NexmoIncomingPhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.nexmo; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.net.URL; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import junit.framework.Assert; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureExpTests; /** * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class NexmoIncomingPhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(NexmoIncomingPhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; static boolean accountUpdated = false; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 /* * Check the list of available Countries */ @Test public void testGetAvailableCountries() { // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/AvailableCountries.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.accept("application/json").get(ClientResponse.class); Assert.assertEquals(200, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse.toString()); System.out.println(jsonResponse.size()); assertTrue(jsonResponse.size() == 250); } /* * https://docs.nexmo.com/index.php/developer-api/number-buy */ @Test public void testPurchasePhoneNumberSuccess() { stubFor(post(urlMatching("/nexmo/number/buy/.*/.*/US/14156902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlMatching("/nexmo/number/update/.*/.*/US/14156902867.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); Assert.assertEquals(200, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); System.out.println(jsonResponse.toString()); assertTrue(NexmoIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),NexmoIncomingPhoneNumbersEndpointTestUtils.jSonResultPurchaseNumber)); } /* * https://docs.nexmo.com/index.php/developer-api/number-cancel */ @Test public void testDeletePhoneNumberSuccess() { stubFor(post(urlMatching("/nexmo/number/buy/.*/.*/ES/34911067000")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlMatching("/nexmo/number/update/.*/.*/ES/34911067000.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlMatching("/nexmo/number/cancel/.*/.*/ES/34911067000")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+34911067000"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); Assert.assertEquals(200, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); logger.info("testDeletePhoneNumberSuccess response for buyNumber: "+response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info("testDeletePhoneNumberSuccess jsonResponse for buyNumber: "+jsonResponse.toString()); assertTrue(NexmoIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),NexmoIncomingPhoneNumbersEndpointTestUtils.jSonResultDeletePurchaseNumber)); String phoneNumberSid = jsonResponse.get("sid").getAsString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); logger.info("testDeletePhoneNumberSuccess delete response: "+clientResponse); assertTrue(clientResponse.getStatus() == 204); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. * If Twilio cannot find a phone number to match your request, you will receive an HTTP 400 with Twilio error code 21452. */ @Test @Category(FeatureExpTests.class) public void testPurchasePhoneNumberNoPhoneNumberFound() { stubFor(post(urlMatching("/nexmo/number/buy/.*/.*/US/14156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902860"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertEquals(400, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); // JsonParser parser = new JsonParser(); // String jsonResponse = parser.parse(response).getAsString(); // assertTrue(jsonResponse.toString().equalsIgnoreCase("21452")); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#instance-post-example-1 * Set the VoiceUrl and SmsUrl on a phone number * * https://docs.nexmo.com/index.php/developer-api/number-update */ @Test public void testUpdatePhoneNumberSuccess() { stubFor(post(urlMatching("/nexmo/number/buy/.*/.*/FR/33911067000")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlMatching("/nexmo/number/update/.*/.*/FR/33911067000.*voiceCallbackValue=%2B33911067000%40127.0.0.1%3A5080.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlMatching("/nexmo/number/cancel/.*/.*/FR/33911067000")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(NexmoIncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+33911067000"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); Assert.assertEquals(200, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); System.out.println(jsonResponse.toString()); assertTrue(NexmoIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),NexmoIncomingPhoneNumbersEndpointTestUtils.jSonResultUpdatePurchaseNumber)); String phoneNumberSid = jsonResponse.get("sid").getAsString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); formData = new MultivaluedMapImpl(); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice2.xml"); formData.add("SmsUrl", "http://demo.telestax.com/docs/sms2.xml"); formData.add("VoiceMethod", "POST"); formData.add("SMSMethod", "GET"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); System.out.println(jsonResponse.toString()); assertTrue(NexmoIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),NexmoIncomingPhoneNumbersEndpointTestUtils.jSonResultUpdateSuccessPurchaseNumber)); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); } @Deployment(name = "NexmoIncomingPhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_nexmo_test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
17,409
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NexmoAvailablePhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/provisioning/number/nexmo/NexmoAvailablePhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.nexmo; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching; import static org.junit.Assert.assertTrue; import java.net.URL; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; /** * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class NexmoAvailablePhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(NexmoAvailablePhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); //"7.4.0-SNAPSHOT"; @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; static boolean accountUpdated = false; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/AvailablePhoneNumbers/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 /* * Testing https://docs.nexmo.com/index.php/developer-api/number-search Example 1 */ @Test public void testSearchESPhoneNumbers700Pattern() { stubFor(get(urlMatching("/nexmo/number/search/.*/.*/ES\\?pattern=.*700.*")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(NexmoAvailablePhoneNumbersEndpointTestUtils.jsonResponseES700))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "ES/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("Contains","700").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 1); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(NexmoAvailablePhoneNumbersEndpointTestUtils.jsonResultES700)); } /* * Testing https://docs.nexmo.com/index.php/developer-api/number-search Example 2 */ @Test public void testSearchUSPhoneNumbersRangeIndexAndSize() { stubFor(get(urlMatching("/nexmo/number/search/.*/.*/US\\?index=2&size=5")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(NexmoAvailablePhoneNumbersEndpointTestUtils.jsonResponseUSRange))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("RangeSize","5").queryParam("RangeIndex","2").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 5); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(NexmoAvailablePhoneNumbersEndpointTestUtils.jsonResultUSRange)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-1 * available local phone numbers in the United States in the 510 area code. */ @Test @Category(FeatureAltTests.class) public void testSearchUSLocalPhoneNumbersWith501AreaCode() { stubFor(get(urlMatching("/nexmo/number/search/.*/.*/US\\?pattern=1501&search_pattern=0")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(NexmoAvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("AreaCode","501").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 6); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(NexmoAvailablePhoneNumbersEndpointTestUtils.firstJSonResult501AreaCode)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-1 * available local phone numbers in the United States in the 510 area code. */ @Test @Category(FeatureAltTests.class) public void testSearchCALocalPhoneNumbersWith450AreaCode() { stubFor(get(urlMatching("/nexmo/number/search/.*/.*/CA\\?pattern=1450&search_pattern=0")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(NexmoAvailablePhoneNumbersEndpointTestUtils.bodyCA450AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "CA/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("AreaCode","450").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 10); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(NexmoAvailablePhoneNumbersEndpointTestUtils.firstJSonResultCA450AreaCode)); } /* * */ @Test public void testSearchCALocalPhoneNumbersWithContainsAreaCode() { stubFor(get(urlMatching("/nexmo/number/search/.*/.*/CA\\?pattern=418&search_pattern=1")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/json") .withBody(NexmoAvailablePhoneNumbersEndpointTestUtils.bodyCA418AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "CA/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("Contains","418").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 10); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(NexmoAvailablePhoneNumbersEndpointTestUtils.firstJSonResultCA418AreaCode)); } // @Test // public void testSearchUSPhoneNumbersSMSOnly() { //// stubFor(get(urlMatching("/nexmo/number/search/.*/.*/US\\?index=2&size=5")) //// .willReturn(aResponse() //// .withStatus(200) //// .withHeader("Content-Type", "text/json") //// .withBody(NexmoAvailablePhoneNumbersEndpointTestUtils.jsonResponseUSRange))); // // Get Account using admin email address and user email address // Client jerseyClient = Client.create(); // jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); // // String provisioningURL = deploymentUrl + baseURL + "SK/Local.json"; // WebResource webResource = jerseyClient.resource(provisioningURL); // // ClientResponse clientResponse = webResource.queryParam("SmsEnabled","true").accept("application/json") // .get(ClientResponse.class); // assertTrue(clientResponse.getStatus() == 200); // String response = clientResponse.getEntity(String.class); // System.out.println(response); // assertTrue(!response.trim().equalsIgnoreCase("[]")); // JsonParser parser = new JsonParser(); // JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); // // System.out.println(jsonResponse); // // assertTrue(jsonResponse.size() == 5); // System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); // assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(NexmoAvailablePhoneNumbersEndpointTestUtils.jsonResultUSRange)); // } @Deployment(name = "NexmoAvailablePhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version " + version); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_nexmo_test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
14,772
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoxboneIncomingPhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/provisioning/number/voxbone/VoxboneIncomingPhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.voxbone; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertTrue; import java.net.URL; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.BrokenTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.UnstableTests; /** * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class VoxboneIncomingPhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(VoxboneIncomingPhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; static boolean accountUpdated = false; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 /* * Check the list of available Countries * http://www.voxbone.com/apidoc/resource_InventoryServiceRest.html#path__country.html */ @Test public void testGetAvailableCountries() { stubFor(put(urlEqualTo("/test/configuration/voiceuri")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.VoiceURIJSonResponse))); stubFor(get(urlEqualTo("/test/inventory/country?pageNumber=0&pageSize=300")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.listCountries))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/AvailableCountries.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.accept("application/json").get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse.toString()); System.out.println(jsonResponse.size()); assertTrue(jsonResponse.size() == 57); } /* * */ @Test @Category(BrokenTests.class) public void testPurchaseAndDeletePhoneNumberSuccess() { stubFor(put(urlEqualTo("/test/configuration/voiceuri")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.VoiceURIJSonResponse))); stubFor(put(urlEqualTo("/test/ordering/cart")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.purchaseOrderingCartSuccessResponse))); stubFor(post(urlEqualTo("/test/ordering/cart/30018/product")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.addToCartSuccessResponse))); stubFor(get(urlEqualTo("/test/ordering/cart/30018/checkout?cartIdentifier=30018")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.checkoutCartSuccessResponse))); stubFor(get(urlEqualTo("/test/inventory/did?orderReference=62252DS997341&pageNumber=0&pageSize=50")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.inventoryDidSuccessResponse))); stubFor(post(urlEqualTo("/test/configuration/configuration")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.updateDidSuccessResponse))); stubFor(post(urlEqualTo("/test/ordering/cancel")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.cancelDidSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "22073"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "USA-ACKLEY-641"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); System.out.println(jsonResponse.toString()); assertTrue(VoxboneIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),VoxboneIncomingPhoneNumbersEndpointTestUtils.jSonResultPurchaseNumber)); String phoneNumberSid = jsonResponse.get("sid").getAsString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); } /* */ // @Test // public void testDeletePhoneNumberSuccess() { // stubFor(post(urlMatching("/nexmo/number/buy/.*/.*/ES/34911067000")) // .willReturn(aResponse() // .withStatus(200) // .withHeader("Content-Type", "application/json") // .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // // stubFor(post(urlMatching("/nexmo/number/update/.*/.*/ES/34911067000.*")) // .willReturn(aResponse() // .withStatus(200) // .withHeader("Content-Type", "application/json") // .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // // stubFor(post(urlMatching("/nexmo/number/cancel/.*/.*/ES/34911067000")) // .willReturn(aResponse() // .withStatus(200) // .withHeader("Content-Type", "application/json") // .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // // Get Account using admin email address and user email address // Client jerseyClient = Client.create(); // jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); // // String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; // WebResource webResource = jerseyClient.resource(provisioningURL); // // MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); // formData.add("PhoneNumber", "+34911067000"); // formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); // formData.add("FriendlyName", "My Company Line"); // formData.add("VoiceMethod", "GET"); // ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); // assertTrue(clientResponse.getStatus() == 200); // String response = clientResponse.getEntity(String.class); // System.out.println(response); // assertTrue(!response.trim().equalsIgnoreCase("[]")); // JsonParser parser = new JsonParser(); // JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); // // System.out.println(jsonResponse.toString()); // assertTrue(VoxboneIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),VoxboneIncomingPhoneNumbersEndpointTestUtils.jSonResultDeletePurchaseNumber)); // // String phoneNumberSid = jsonResponse.get("sid").getAsString(); // provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; // webResource = jerseyClient.resource(provisioningURL); // clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); // assertTrue(clientResponse.getStatus() == 204); // } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. * If Twilio cannot find a phone number to match your request, you will receive an HTTP 400 with Twilio error code 21452. */ @Test @Category(FeatureExpTests.class) public void testPurchasePhoneNumberNoPhoneNumberFound() { stubFor(put(urlEqualTo("/test/configuration/voiceuri")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.VoiceURIJSonResponse))); stubFor(put(urlEqualTo("/test/ordering/cart")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.orderingCartSuccessResponse))); stubFor(post(urlEqualTo("/test/ordering/cart/30007/product")) .willReturn(aResponse() .withStatus(400) .withHeader("Content-Type", "application/json"))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902860"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 400); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); String jsonResponse = parser.parse(response).getAsString(); assertTrue(jsonResponse.toString().equalsIgnoreCase("21452")); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#instance-post-example-1 * Set the VoiceUrl and SmsUrl on a phone number */ // @Test // public void testUpdatePhoneNumberSuccess() { // stubFor(post(urlMatching("/nexmo/number/buy/.*/.*/FR/33911067000")) // .willReturn(aResponse() // .withStatus(200) // .withHeader("Content-Type", "application/json") // .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // // stubFor(post(urlMatching("/nexmo/number/update/.*/.*/FR/33911067000.*")) // .willReturn(aResponse() // .withStatus(200) // .withHeader("Content-Type", "application/json") // .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // // stubFor(post(urlMatching("/nexmo/number/cancel/.*/.*/FR/33911067000")) // .willReturn(aResponse() // .withStatus(200) // .withHeader("Content-Type", "application/json") // .withBody(VoxboneIncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // // Get Account using admin email address and user email address // Client jerseyClient = Client.create(); // jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); // // String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; // WebResource webResource = jerseyClient.resource(provisioningURL); // // MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); // formData.add("PhoneNumber", "+33911067000"); // formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); // formData.add("FriendlyName", "My Company Line"); // formData.add("VoiceMethod", "GET"); // ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); // assertTrue(clientResponse.getStatus() == 200); // String response = clientResponse.getEntity(String.class); // System.out.println(response); // assertTrue(!response.trim().equalsIgnoreCase("[]")); // JsonParser parser = new JsonParser(); // JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); // // System.out.println(jsonResponse.toString()); // assertTrue(VoxboneIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),VoxboneIncomingPhoneNumbersEndpointTestUtils.jSonResultUpdatePurchaseNumber)); // // String phoneNumberSid = jsonResponse.get("sid").getAsString(); // provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; // webResource = jerseyClient.resource(provisioningURL); // formData = new MultivaluedMapImpl(); // formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice2.xml"); // formData.add("SmsUrl", "http://demo.telestax.com/docs/sms2.xml"); // formData.add("VoiceMethod", "POST"); // formData.add("SMSMethod", "GET"); // clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); // assertTrue(clientResponse.getStatus() == 200); // response = clientResponse.getEntity(String.class); // System.out.println(response); // assertTrue(!response.trim().equalsIgnoreCase("[]")); // parser = new JsonParser(); // jsonResponse = parser.parse(response).getAsJsonObject(); // System.out.println(jsonResponse.toString()); // assertTrue(VoxboneIncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),VoxboneIncomingPhoneNumbersEndpointTestUtils.jSonResultUpdateSuccessPurchaseNumber)); // // provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; // webResource = jerseyClient.resource(provisioningURL); // clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); // assertTrue(clientResponse.getStatus() == 204); // } @Deployment(name = "VoxboneIncomingPhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_voxbone_test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
20,688
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoxboneAvailablePhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/provisioning/number/voxbone/VoxboneAvailablePhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.voxbone; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.put; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertTrue; import java.net.URL; import junit.framework.Assert; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import org.restcomm.connect.commons.Version; /** * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class VoxboneAvailablePhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(VoxboneAvailablePhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; static boolean accountUpdated = false; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/AvailablePhoneNumbers/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-1 * available local phone numbers in the United States in the 510 area code. */ @Test public void testSearchUSLocalPhoneNumbersWith501AreaCode() { stubFor(put(urlEqualTo("/test/configuration/voiceuri")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.VoiceURIJSonResponse))); stubFor(get(urlEqualTo("/test/inventory/didgroup?countryCodeA3=USA&areaCode=501&pageNumber=0&pageSize=50")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource. queryParam("AreaCode","501"). accept("application/json") .get(ClientResponse.class); Assert.assertEquals(200, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 15); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(VoxboneAvailablePhoneNumbersEndpointTestUtils.firstJSonResult501AreaCode)); } /* * Testing https://docs.nexmo.com/index.php/developer-api/number-search Example 1 */ @Test public void testSearchESPhoneNumbers700Pattern() { stubFor(put(urlEqualTo("/test/configuration/voiceuri")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.VoiceURIJSonResponse))); stubFor(get(urlEqualTo("/test/inventory/didgroup?countryCodeA3=ESP&pageNumber=0&pageSize=50")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.jsonResponseES700))); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "ES/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("Contains","700").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 48); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(VoxboneAvailablePhoneNumbersEndpointTestUtils.jsonResultES700)); } /* * Testing https://docs.nexmo.com/index.php/developer-api/number-search Example 2 */ @Test public void testSearchUSPhoneNumbersRangeIndexAndSize() { stubFor(put(urlEqualTo("/test/configuration/voiceuri")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.VoiceURIJSonResponse))); stubFor(get(urlEqualTo("/test/inventory/didgroup?countryCodeA3=USA&pageNumber=2&pageSize=5")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody(VoxboneAvailablePhoneNumbersEndpointTestUtils.jsonResponseUSRange))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("RangeSize","5").queryParam("RangeIndex","2").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 5); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(VoxboneAvailablePhoneNumbersEndpointTestUtils.jsonResultUSRange)); } @Deployment(name = "VoxboneAvailablePhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_voxbone_test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
10,470
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IncomingPhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/provisioning/number/vi/IncomingPhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.vi; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertEquals; import java.net.URL; import java.util.HashMap; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.runner.RunWith; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import org.junit.experimental.categories.Category; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.dao.Sid; import org.restcomm.connect.commons.annotations.BrokenTests; import org.restcomm.connect.commons.annotations.FeatureAltTests; import org.restcomm.connect.commons.annotations.FeatureExpTests; import org.restcomm.connect.commons.annotations.UnstableTests; /** * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class IncomingPhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(IncomingPhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; static boolean accountUpdated = false; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/"; private String migrateURL = "2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acg/"; private String adminOrg2Username = "[email protected]"; private String adminOrg2AccountSid = "ACae6e420f425248d6a26948c17a9e2acg"; private String adminOrg2AuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURLOrg2 = "2012-04-24/Accounts/" + adminOrg2AccountSid + "/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 /* * https://github.com/RestComm/Restcomm-Connect/issues/2389 * try deleting a number that does not exist */ @Test @Category(FeatureExpTests.class) public void testDeletePhoneNumberNotFound() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4196902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4196902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("4196902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); String phoneNumberSid = Sid.generate(Sid.Type.PHONE_NUMBER).toString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); logger.info("clientResponse: "+clientResponse.getStatus()); assertTrue(clientResponse.getStatus() == 404); } /* * https://github.com/RestComm/Restcomm-Connect/issues/2389 * try updating a number that does not exist */ @Test @Category(FeatureExpTests.class) public void testUpdatePhoneNumberNotFound() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4206902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4206902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("4206902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); String phoneNumberSid = Sid.generate(Sid.Type.PHONE_NUMBER).toString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); formData = new MultivaluedMapImpl(); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice2.xml"); formData.add("SmsUrl", "http://demo.telestax.com/docs/sms2.xml"); formData.add("VoiceMethod", "POST"); formData.add("SMSMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); logger.info("clientResponse.getStatus(): "+clientResponse.getStatus()); assertTrue(clientResponse.getStatus() == 404); } @Test @Category(BrokenTests.class) public void getIncomingPhoneNumbersList() { JsonObject firstPage = RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbers(deploymentUrl.toString(), adminAccountSid, adminAuthToken); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageNumbersArray = firstPage.get("incomingPhoneNumbers").getAsJsonArray(); int firstPageNumbersArraySize = firstPageNumbersArray.size(); assertTrue(firstPageNumbersArraySize == 50); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 49); JsonObject secondPage = (JsonObject) RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbers(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 2, null, true); JsonArray secondPageNumbersArray = secondPage.get("incomingPhoneNumbers").getAsJsonArray(); assertTrue(secondPageNumbersArray.size() == 50); assertTrue(secondPage.get("start").getAsInt() == 100); assertTrue(secondPage.get("end").getAsInt() == 149); JsonObject lastPage = (JsonObject) RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbers(deploymentUrl.toString(), adminAccountSid, adminAuthToken, firstPage.get("num_pages").getAsInt(), null, true); JsonArray lastPageNumbersArray = lastPage.get("incomingPhoneNumbers").getAsJsonArray(); assertTrue(lastPageNumbersArray.get(lastPageNumbersArray.size() - 1).getAsJsonObject().get("sid").getAsString() .equals("PHae6e420f425248d6a26948c17a9e2ap8")); assertTrue(lastPageNumbersArray.size() == 1); assertTrue(lastPage.get("start").getAsInt() == 500); assertTrue(lastPage.get("end").getAsInt() == 501); assertTrue(totalSize == 501); } @Test @Category(BrokenTests.class) public void getIncomingPhoneNumbersListUsingPageSize() { JsonObject firstPage = (JsonObject) RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbers(deploymentUrl.toString(), adminAccountSid, adminAuthToken, null, 100, true); int totalSize = firstPage.get("total").getAsInt(); JsonArray firstPageNumbersArray = firstPage.get("incomingPhoneNumbers").getAsJsonArray(); int firstPageNumbersArraySize = firstPageNumbersArray.size(); assertTrue(firstPageNumbersArraySize == 100); assertTrue(firstPage.get("start").getAsInt() == 0); assertTrue(firstPage.get("end").getAsInt() == 99); JsonObject secondPage = (JsonObject) RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbers(deploymentUrl.toString(), adminAccountSid, adminAuthToken, 2, 100, true); JsonArray secondPageNumbersArray = secondPage.get("incomingPhoneNumbers").getAsJsonArray(); assertTrue(secondPageNumbersArray.size() == 100); assertTrue(secondPage.get("start").getAsInt() == 200); assertTrue(secondPage.get("end").getAsInt() == 299); JsonObject lastPage = (JsonObject) RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbers(deploymentUrl.toString(), adminAccountSid, adminAuthToken, firstPage.get("num_pages").getAsInt(), 100, true); JsonArray lastPageNumbersArray = lastPage.get("incomingPhoneNumbers").getAsJsonArray(); assertEquals("PHae6e420f425248d6a26948c17a9e2ap8",lastPageNumbersArray.get(lastPageNumbersArray.size() - 1).getAsJsonObject().get("sid").getAsString()); assertTrue(lastPageNumbersArray.size() == 1); assertTrue(lastPage.get("start").getAsInt() == 500); assertTrue(lastPage.get("end").getAsInt() == 501); assertTrue(totalSize == 501); } /* * Check the list of available Countries */ @Test public void testGetAvailableCountries() { // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/AvailableCountries.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.accept("application/json").get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); logger.info(jsonResponse.toString()); assertTrue(jsonResponse.size() == 1); logger.info(jsonResponse.get(0).getAsString()); assertTrue(jsonResponse.get(0).getAsString().equals("US")); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. If a phone number is found for your request, * Twilio will add it to your account and bill you for the first month's cost of the phone number. */ @Test public void testPurchasePhoneNumberSuccess() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4156902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4156902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultPurchaseNumber)); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. * If Twilio cannot find a phone number to match your request, you will receive an HTTP 400 with Twilio error code 21452. */ @Test @Category(FeatureExpTests.class) public void testPurchasePhoneNumberNoPhoneNumberFound() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); if(logger.isDebugEnabled()) logger.debug("clientResponse for buying unavailable number: " + clientResponse); assertEquals(400, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); String jsonResponse = parser.parse(response).getAsString(); assertTrue(jsonResponse.toString().equalsIgnoreCase("21452")); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. If a phone number is found for your request, * Twilio will add it to your account and bill you for the first month's cost of the phone number. */ @Test public void testPurchaseLocalPhoneNumberSuccess() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4166902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4166902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14166902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultLocalPurchaseNumber)); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. * If Twilio cannot find a phone number to match your request, you will receive an HTTP 400 with Twilio error code 21452. */ @Test @Category(FeatureExpTests.class) public void testPurchaseLocalPhoneNumberNoPhoneNumberFound() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); if(logger.isDebugEnabled()) logger.debug("clientResponse for buying unavailable number: " + clientResponse); assertEquals(400, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); String jsonResponse = parser.parse(response).getAsString(); assertTrue(jsonResponse.toString().equalsIgnoreCase("21452")); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. If a phone number is found for your request, * Twilio will add it to your account and bill you for the first month's cost of the phone number. */ @Test public void testPurchaseTollFreePhoneNumberSuccess() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4176902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4176902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/TollFree.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14176902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultTollFreePurchaseNumber)); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. * If Twilio cannot find a phone number to match your request, you will receive an HTTP 400 with Twilio error code 21452. */ @Test @Category(FeatureExpTests.class) public void testPurchaseTollFreePhoneNumberNoPhoneNumberFound() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/TollFree.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); if(logger.isDebugEnabled()) logger.debug("clientResponse for buying unavailable number: " + clientResponse); assertEquals(400, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); String jsonResponse = parser.parse(response).getAsString(); assertTrue(jsonResponse.toString().equalsIgnoreCase("21452")); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. If a phone number is found for your request, * Twilio will add it to your account and bill you for the first month's cost of the phone number. */ @Test public void testPurchaseMobilePhoneNumberSuccess() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4186902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4186902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/Mobile.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14186902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultMobilePurchaseNumber)); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-post-example-1 * Purchases a new phone number for your account. * If Twilio cannot find a phone number to match your request, you will receive an HTTP 400 with Twilio error code 21452. */ @Test @Category(FeatureExpTests.class) public void testPurchaseMobilePhoneNumberNoPhoneNumberFound() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4156902868")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/Mobile.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); if(logger.isDebugEnabled()) logger.debug("clientResponse for buying unavailable number: " + clientResponse); assertEquals(400, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); String jsonResponse = parser.parse(response).getAsString(); assertTrue(jsonResponse.toString().equalsIgnoreCase("21452")); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#instance-delete * Release this phone number from your account. Twilio will no longer answer calls to this number, and you will stop being billed the monthly phone number fee. The phone number will eventually be recycled and potentially given to another customer, so use with care. If you make a mistake, contact us. We may be able to give you the number back. * * If successful, returns an HTTP 204 response with no body. */ @Test public void testDeletePhoneNumberSuccess() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4196902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4196902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("4196902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14196902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultDeletePurchaseNumber)); String phoneNumberSid = jsonResponse.get("sid").getAsString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#instance-post-example-1 * Set the VoiceUrl and SmsUrl on a phone number */ @Test public void testUpdatePhoneNumberSuccess() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4206902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4206902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("4206902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14206902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultUpdatePurchaseNumber)); String phoneNumberSid = jsonResponse.get("sid").getAsString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); formData = new MultivaluedMapImpl(); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice2.xml"); formData.add("SmsUrl", "http://demo.telestax.com/docs/sms2.xml"); formData.add("VoiceMethod", "POST"); formData.add("SMSMethod", "GET"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); logger.info(clientResponse); assertTrue(clientResponse.getStatus() == 200); response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultUpdateSuccessPurchaseNumber)); } @Test @Category(FeatureAltTests.class) public void testMigratePhoneNumberSuccess() { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + migrateURL + "IncomingPhoneNumbers/migrate"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData = new MultivaluedMapImpl(); formData.add("OrganizationSid", "ORafbe225ad37541eba518a74248f0ac4c"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); logger.info(clientResponse); assertEquals(200, clientResponse.getStatus()); } @Test @Category(FeatureExpTests.class) public void testMigratePhoneNumberPermission() { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminOrg2AccountSid, adminAuthToken)); String provisioningURL = deploymentUrl + migrateURL + "IncomingPhoneNumbers/migrate"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData = new MultivaluedMapImpl(); formData.add("OrganizationSid", "ORafbe225ad37541eba518a74248f0ac4c"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); logger.info(clientResponse); assertEquals(403, clientResponse.getStatus()); } /** * super admin's number migration is not allowed */ @Test @Category(FeatureExpTests.class) public void testMigratePhoneNumberSuperAdminMigration() { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminAccountSid, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/migrate"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData = new MultivaluedMapImpl(); formData.add("OrganizationSid", "ORafbe225ad37541eba518a74248f0ac4c"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); logger.info(clientResponse); assertEquals(400, clientResponse.getStatus()); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-get-example-1 */ @Test public void testAccountAssociatedPhoneNumbers() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14216902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultAccountAssociatedPurchaseNumber)); String phoneNumberSid = jsonResponse.get("sid").getAsString(); formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+15216902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My 2nd Company Line"); formData.add("VoiceMethod", "GET"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); String secondPhoneNumberSid = jsonResponse.get("sid").getAsString(); // formData = new MultivaluedMapImpl(); // formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice2.xml"); Map<String, String> filters = new HashMap<>(); filters.put("FriendlyName", "My 2nd Company Line"); JsonObject jsonObject = RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbersUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); JsonArray jsonArray = jsonObject.get("incomingPhoneNumbers").getAsJsonArray(); logger.info(jsonArray + " \n " + jsonArray.size()); assertTrue(jsonArray.size() >0); logger.info("testAccountAssociatedPhoneNumbers:" + (jsonArray.get(jsonArray.size()-1).getAsJsonObject().toString())); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonArray.get(jsonArray.size()-1).getAsJsonObject().toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultAccountAssociatedPurchaseNumberResult)); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + secondPhoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-get-example-2 */ @Test public void testAccountAssociatedPhoneNumbersFilter() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14216902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultAccountAssociatedPurchaseNumber)); String phoneNumberSid = jsonResponse.get("sid").getAsString(); formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+15216902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My 2nd Company Line"); formData.add("VoiceMethod", "GET"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); String secondPhoneNumberSid = jsonResponse.get("sid").getAsString(); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; Map<String, String> filters = new HashMap<>(); filters.put("PhoneNumber", "+15216902867"); JsonObject jsonObject = RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbersUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); JsonArray jsonArray = jsonObject.get("incomingPhoneNumbers").getAsJsonArray(); logger.info(jsonArray + " \n " + jsonArray.size()); assertTrue(jsonArray.size() == 1); logger.info((jsonArray.get(0).getAsJsonObject().toString())); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonArray.get(0).getAsJsonObject().toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultAccountAssociatedPurchaseNumberResult)); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + secondPhoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); } /* * https://www.twilio.com/docs/api/rest/incoming-phone-numbers#list-get-example-3 * Return the set of all phone numbers containing the digits 867. */ @Test public void testAccountAssociatedPhoneNumbersSecondFilter() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("4216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("releaseDID")) .withRequestBody(containing("5216902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.deleteNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14216902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertEquals(200, clientResponse.getStatus()); String response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultAccountAssociatedPurchaseNumber)); String phoneNumberSid = jsonResponse.get("sid").getAsString(); formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+15216902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My 2nd Company Line"); formData.add("VoiceMethod", "GET"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); response = clientResponse.getEntity(String.class); logger.info(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); String secondPhoneNumberSid = jsonResponse.get("sid").getAsString(); Map<String, String> filters = new HashMap<>(); filters.put("PhoneNumber", "6902867"); JsonObject jsonObject = RestcommIncomingPhoneNumberTool.getInstance().getIncomingPhoneNumbersUsingFilter(deploymentUrl.toString(), adminAccountSid, adminAuthToken, filters); JsonArray jsonArray = jsonObject.get("incomingPhoneNumbers").getAsJsonArray(); webResource = jerseyClient.resource(provisioningURL); logger.info(jsonArray + " \n " + jsonArray.size()); assertTrue(jsonArray.size() >= 2); logger.info((jsonArray.get(jsonArray.size() - 1).getAsJsonObject().toString())); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonArray.get(jsonArray.size() - 1).getAsJsonObject().toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultAccountAssociatedPurchaseNumberResult)); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + phoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/" + secondPhoneNumberSid + ".json"; webResource = jerseyClient.resource(provisioningURL); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").delete(ClientResponse.class); assertTrue(clientResponse.getStatus() == 204); } /** * testCreatePureSipPhoneNumbersForOrganizations * https://github.com/RestComm/Restcomm-Connect/issues/2106 */ @Test public void testCreatePureSipPhoneNumbersForOrganizations() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("11223344")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("11223344")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "11223344"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); formData.add("isSIP", "TRUE"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); logger.info("testCreatePureSipPhoneNumber from default org jsonResponse: " + jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultSIPPurchaseNumber)); /* * try to create same number again * under same organization/account, * it should not be allowed * */ stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("11223344")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("11223344")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/Local.json"; webResource = jerseyClient.resource(provisioningURL); formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "11223344"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); formData.add("isSIP", "TRUE"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); logger.info("testCreatePureSipPhoneNumber from default org TWICE clientResponse: " + clientResponse.toString()); assertTrue(clientResponse.getStatus() != 200); /* * try to create same number again * under different organization/account, * it should be allowed * */ stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("11223344")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("11223344")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminOrg2Username, adminOrg2AuthToken)); provisioningURL = deploymentUrl + baseURLOrg2 + "IncomingPhoneNumbers/Local.json"; webResource = jerseyClient.resource(provisioningURL); formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "11223344"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); formData.add("isSIP", "TRUE"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); logger.info("testCreatePureSipPhoneNumber from Org2 jsonResponse: " + jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultSIPPurchaseNumberOrg2)); } /** * testCreateNonPureSipPhoneNumbersForOrganizations * https://github.com/RestComm/Restcomm-Connect/issues/2106 */ @Test @Category(UnstableTests.class) public void testCreateNonPureSipPhoneNumbersForOrganizations() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4166902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4166902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+14166902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); ClientResponse clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); System.out.println(jsonResponse.toString()); assertTrue(IncomingPhoneNumbersEndpointTestUtils.match(jsonResponse.toString(),IncomingPhoneNumbersEndpointTestUtils.jSonResultLocalPurchaseNumber)); /* * try to create same number again * under same organization/account, * it should not be allowed * */ stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("queryDID")) .withRequestBody(containing("4156902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.queryDIDSuccessResponse))); stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("assignDID")) .withRequestBody(containing("4156902867")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(IncomingPhoneNumbersEndpointTestUtils.purchaseNumberSuccessResponse))); // Get Account using admin email address and user email address jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); provisioningURL = deploymentUrl + baseURL + "IncomingPhoneNumbers/Local.json"; webResource = jerseyClient.resource(provisioningURL); formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+4156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); logger.info("testCreatePureSipPhoneNumber from default org TWICE clientResponse: " + clientResponse.toString()); assertEquals(400, clientResponse.getStatus()); /* * try to create same number again * under different organization/account, * it should not be allowed * */ jerseyClient.addFilter(new HTTPBasicAuthFilter(adminOrg2Username, adminOrg2AuthToken)); provisioningURL = deploymentUrl + baseURLOrg2 + "IncomingPhoneNumbers/Local.json"; webResource = jerseyClient.resource(provisioningURL); formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", "+4156902867"); formData.add("VoiceUrl", "http://demo.telestax.com/docs/voice.xml"); formData.add("FriendlyName", "My Company Line"); formData.add("VoiceMethod", "GET"); clientResponse = webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); assertEquals(400, clientResponse.getStatus()); } @Deployment(name = "IncomingPhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_AvailablePhoneNumbers_Test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
77,445
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailablePhoneNumbersEndpointTest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/test/java/org/restcomm/connect/testsuite/provisioning/number/vi/AvailablePhoneNumbersEndpointTest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.vi; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.containing; import static com.github.tomakehurst.wiremock.client.WireMock.post; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static org.junit.Assert.assertTrue; import java.net.URL; import org.apache.log4j.Logger; import org.jboss.arquillian.container.test.api.Deployer; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.arquillian.test.api.ArquillianResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.junit.Rule; import org.junit.Test; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import org.restcomm.connect.commons.Version; import org.restcomm.connect.commons.annotations.FeatureAltTests; /** * @author <a href="mailto:[email protected]">Jean Deruelle</a> */ @RunWith(Arquillian.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AvailablePhoneNumbersEndpointTest { private final static Logger logger = Logger.getLogger(AvailablePhoneNumbersEndpointTest.class.getName()); private static final String version = Version.getVersion(); @ArquillianResource private Deployer deployer; @ArquillianResource URL deploymentUrl; static boolean accountUpdated = false; private String adminUsername = "[email protected]"; private String adminAccountSid = "ACae6e420f425248d6a26948c17a9e2acf"; private String adminAuthToken = "77f8c12cc7b8f8423e5c38b035249166"; private String baseURL = "2012-04-24/Accounts/" + adminAccountSid + "/AvailablePhoneNumbers/"; @Rule public WireMockRule wireMockRule = new WireMockRule(8090); // No-args constructor defaults to port 8080 /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-1 * available local phone numbers in the United States in the 510 area code. */ @Test @Category(FeatureAltTests.class) public void testSearchUSLocalPhoneNumbersWith501AreaCode() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("getDIDs")) .withRequestBody(containing("501")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(AvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("AreaCode","501").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 33); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(AvailablePhoneNumbersEndpointTestUtils.firstJSonResult501AreaCode)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-2 * Find local phone numbers in the United States starting with 510555. */ @Test @Category(FeatureAltTests.class) public void testSearchUSLocalPhoneNumbersWithPattern() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("getDIDs")) .withRequestBody(containing("501")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(AvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("Contains","501555****").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 2); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(AvailablePhoneNumbersEndpointTestUtils.firstJSonResult501ContainsPattern)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-3 * Find local phone numbers that match the pattern 'STORM'. */ @Test @Category(FeatureAltTests.class) public void testSearchUSLocalPhoneNumbersWithLetterPattern() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("getDIDs")) .withRequestBody(containing("675")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(AvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("Contains","STORM").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 1); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(AvailablePhoneNumbersEndpointTestUtils.firstJSonResult501ContainsLetterPattern)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-4 * Find local phone numbers in Arkansas. */ @Test public void testSearchUSLocalPhoneNumbersWithInRegionFilter() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("getDIDs")) .withRequestBody(containing("501")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(AvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("AreaCode","501").queryParam("InRegion","AR").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 1); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(AvailablePhoneNumbersEndpointTestUtils.firstJSonResult501InRegionPattern)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-5 * Find a phone number in the London prefix (+4420) which is Fax-enabled. */ @Test public void testSearchUKFaxEnabledFilter() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("getDIDs")) // .withRequestBody(containing("501")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(AvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "GB/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("Contains","4420").queryParam("FaxEnabled","true").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 1); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(AvailablePhoneNumbersEndpointTestUtils.firstJSonResultUKPattern)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#local-get-basic-example-5 * Find a phone number in the London prefix (+4420) which is Fax-enabled. */ @Test public void testSearchAdvancedFilter() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("getDIDs")) // .withRequestBody(containing("501")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(AvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/Local.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("NearLatLong","37.840699%2C-122.461853").queryParam("Distance","50").queryParam("Contains","501").queryParam("InRegion","CA").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 2); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(AvailablePhoneNumbersEndpointTestUtils.firstJSonResultAdvancedPattern)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#toll-free-get-example-3 * Find toll-free phone numbers in the 800 area code that contain the pattern 'STORM'. */ @Test @Category(FeatureAltTests.class) public void testSearchUSTollFreePhoneNumbersWithLetterPattern() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("getDIDs")) .withRequestBody(containing("675")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(AvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "US/TollFree.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("Contains","STORM").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 1); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(AvailablePhoneNumbersEndpointTestUtils.firstJSonResult501ContainsLetterPattern)); } /* * https://www.twilio.com/docs/api/rest/available-phone-numbers#mobile-get-example-1 * Find a phone number in the London prefix (+4420) which is Fax-enabled. */ @Test @Category(FeatureAltTests.class) public void testSearchMobileUKFaxEnabledFilter() { stubFor(post(urlEqualTo("/test")) .withRequestBody(containing("getDIDs")) // .withRequestBody(containing("501")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "text/xml") .withBody(AvailablePhoneNumbersEndpointTestUtils.body501AreaCode))); // Get Account using admin email address and user email address Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String provisioningURL = deploymentUrl + baseURL + "GB/Mobile.json"; WebResource webResource = jerseyClient.resource(provisioningURL); ClientResponse clientResponse = webResource.queryParam("Contains","4420").queryParam("FaxEnabled","true").accept("application/json") .get(ClientResponse.class); assertTrue(clientResponse.getStatus() == 200); String response = clientResponse.getEntity(String.class); System.out.println(response); assertTrue(!response.trim().equalsIgnoreCase("[]")); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); System.out.println(jsonResponse); assertTrue(jsonResponse.size() == 1); System.out.println((jsonResponse.get(0).getAsJsonObject().toString())); assertTrue(jsonResponse.get(0).getAsJsonObject().toString().equalsIgnoreCase(AvailablePhoneNumbersEndpointTestUtils.firstJSonResultUKPattern)); } @Deployment(name = "AvailablePhoneNumbersEndpointTest", managed = true, testable = false) public static WebArchive createWebArchiveNoGw() { logger.info("Packaging Test App"); logger.info("version"); WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve("org.restcomm:restcomm-connect.application:war:" + version).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); archive.delete("/WEB-INF/sip.xml"); archive.delete("/WEB-INF/web.xml"); archive.delete("/WEB-INF/conf/restcomm.xml"); archive.delete("/WEB-INF/data/hsql/restcomm.script"); archive.addAsWebInfResource("sip.xml"); archive.addAsWebInfResource("web.xml"); archive.addAsWebInfResource("restcomm_AvailablePhoneNumbers_Test.xml", "conf/restcomm.xml"); archive.addAsWebInfResource("restcomm.script_dialTest", "data/hsql/restcomm.script"); logger.info("Packaged Test App"); return archive; } }
19,509
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
WebArchiveUtil.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/WebArchiveUtil.java
package org.restcomm.connect.testsuite; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.jboss.shrinkwrap.resolver.api.maven.Maven; import org.restcomm.connect.commons.Version; public class WebArchiveUtil { public static File tweakFilePorts(String filePath, Map<String, String> portReplaments) { try { InputStream resourceAsStream = WebArchiveUtil.class.getClassLoader().getResourceAsStream(filePath); if (resourceAsStream != null) { StringWriter writer = new StringWriter(); IOUtils.copy(resourceAsStream, writer, java.nio.charset.Charset.defaultCharset()); String confStr = writer.toString(); for (String key : portReplaments.keySet()) { confStr = confStr.replace(key, portReplaments.get(key)); } String targetFilePath = "target" + File.separator; if (System.getProperty("arquillian_sip_port") != null) { targetFilePath = targetFilePath + System.getProperty("arquillian_sip_port"); } targetFilePath = targetFilePath + File.separator + filePath; File f = new File(targetFilePath); FileUtils.writeStringToFile(f, confStr); return f; } } catch (IOException ex) { return null; } return null; } public static WebArchive createWebArchiveNoGw(String restcommConf, String dbScript, Map<String, String> replacements) { return createWebArchiveNoGw(restcommConf, dbScript, new ArrayList(), replacements); } public static WebArchive createWebArchiveNoGw(String restcommConf, String dbScript, List<String> resources, Map<String, String> replacements) { Map<String, String> webInfResources = new HashMap(); webInfResources.put(restcommConf, "conf/restcomm.xml"); webInfResources.put(dbScript, "data/hsql/restcomm.script"); webInfResources.put("akka_application.conf", "classes/application.conf"); webInfResources.put("sip.xml", "/sip.xml"); webInfResources.put("web.xml", "web.xml"); return createWebArchiveNoGw(webInfResources, resources, replacements); } public static WebArchive createWebArchiveNoGw(Map<String, String> webInfResources, List<String> resources, Map<String, String> replacements, String mavenApp ) { WebArchive archive = ShrinkWrap.create(WebArchive.class, "restcomm.war"); final WebArchive restcommArchive = Maven.resolver() .resolve(mavenApp).withoutTransitivity() .asSingle(WebArchive.class); archive = archive.merge(restcommArchive); //by default include Allowing extension to check executionPoints File extFile = WebArchiveUtil.tweakFilePorts("org/restcomm/connect/testsuite/extensions/extensions_allowing.xml", replacements); if (extFile != null) { archive.delete("/WEB-INF/" + "conf/extensions.xml"); archive.addAsWebInfResource(extFile, "conf/extensions.xml"); } for (String webdInfFile : webInfResources.keySet()) { File f = WebArchiveUtil.tweakFilePorts(webdInfFile, replacements); archive.delete("/WEB-INF/" + webInfResources.get(webdInfFile)); archive.addAsWebInfResource(f, webInfResources.get(webdInfFile)); } for (String rAux : resources) { File rFile = WebArchiveUtil.tweakFilePorts(rAux, replacements); //assume wherever the file comes from (dir depth), //we will get it form context root archive.addAsWebResource(rFile, rFile.getName()); } return archive; } public static WebArchive createWebArchiveNoGw(Map<String, String> webInfResources, List<String> resources, Map<String, String> replacements) { return createWebArchiveNoGw( webInfResources, resources, replacements, "org.restcomm:restcomm-connect.application:war:" + Version.getVersion()); } }
4,466
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NetworkPortAssigner.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/NetworkPortAssigner.java
package org.restcomm.connect.testsuite; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.management.ManagementFactory; import java.nio.channels.FileChannel; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.Logger; /** * Allows integration tests to be run in parallel by assigning a free port. * * A port range will be assigned based in JVM PID, and a circular sequence * around this range will be provided. JVM PID are expected to be sequenced, so * incremental PID will be received. It is assumed that low number of forked * JMVs will be used to run parallel tests ( near cores in system), so the * PORT_RANGE dont provide much collisions. * */ public class NetworkPortAssigner { private static final Logger LOGGER = Logger.getLogger(NetworkPortAssigner.class); private static final int PORT_RANGE = 150; //provide ports above system reserved range private static final int PORT_MAX_BASE = 65534; private static final int INITIAL_PORT_VALUE; private static final AtomicInteger PORT_SEQ = new AtomicInteger(0); private static final int PID; static { final String jvmName = ManagementFactory.getRuntimeMXBean().getName(); final int index = jvmName.indexOf('@'); if (index < 1) { // part before '@' empty (index = 0) / '@' not found (index = -1) PID = 0; } else { PID = Integer.parseInt(jvmName.substring(0, index)); } INITIAL_PORT_VALUE = PORT_MAX_BASE - ((PID % PORT_RANGE) * PORT_RANGE); LOGGER.info("PID:" + PID); LOGGER.info("PID:" + PID + ",INITIAL_PORT_VALUE:" + INITIAL_PORT_VALUE); } public static synchronized int retrieveNextPort() { int nextPort = PORT_MAX_BASE; nextPort = retrieveNextPortByFile(); LOGGER.info("PID:" + PID + ",nextPort:" + nextPort); return nextPort; } public static int retrieveNextPortBySeq() { int nextPort = INITIAL_PORT_VALUE - (PORT_SEQ.getAndAdd(1) % PORT_RANGE); return nextPort; } public static int retrieveNextPortByFile() { int nextPort = PORT_MAX_BASE; //assume maven convention, create file under target so its cleaned File portFile = new File("./target/portFile"); try { if (!portFile.exists()) { portFile.createNewFile(); LOGGER.info("PID:" + PID + ",portFile created"); } else { LOGGER.info("PID:" + PID + ",portFile already exists"); } } catch (IOException ex) { LOGGER.info("PID:" + PID + ", there is problem when creating portFile"); } RandomAccessFile aFile = null; try { aFile = new RandomAccessFile(portFile, "rwd"); FileChannel channel = aFile.getChannel(); channel.lock(); try { int readInt = aFile.readInt(); nextPort = readInt - 1; if (nextPort <= 0) { nextPort = PORT_MAX_BASE - 1; } } catch (EOFException eExp) { //file was empty, it was just created nextPort = PORT_MAX_BASE - 1; LOGGER.info("PID:" + PID + ",sequence resetted"); } //rewrite existing value by resetting pointer to the start aFile.seek(0); aFile.writeInt(nextPort); } catch (Exception ex) { LOGGER.error("error getting port", ex); } finally { if (aFile != null) { try { aFile.close(); } catch (Exception e) { LOGGER.error("error getting port", e); } } } return nextPort; } }
3,890
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommRvdProjectsMigratorTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/RestcommRvdProjectsMigratorTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.testsuite; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import javax.ws.rs.core.MediaType; /** * @author [email protected] */ public class RestcommRvdProjectsMigratorTool { private static RestcommRvdProjectsMigratorTool instance; public static enum Endpoint { APPLICATIONS("Applications", ".json"), INCOMING_PHONE_NUMBERS("IncomingPhoneNumbers", ".json"), CLIENTS("Clients", ".json"), NOTIFICATIONS("Notifications", ".json"),; private String name; private String extension; Endpoint(String name, String extension) { this.name = name; this.extension = extension; } public String getName() { return this.name; } public String getExtension() { return this.extension; } } public static RestcommRvdProjectsMigratorTool getInstance() { if (instance == null) { instance = new RestcommRvdProjectsMigratorTool(); } return instance; } public JsonArray getEntitiesList(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, Endpoint endpoint, String propertyName) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getEntitiesUrl(deploymentUrl, adminAccountSid, endpoint); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonArray jsonResponse; if (propertyName == null) { jsonResponse = parser.parse(response).getAsJsonArray(); } else { JsonObject jsonObject = parser.parse(response).getAsJsonObject(); jsonResponse = jsonObject.get(propertyName).getAsJsonArray(); } return jsonResponse; } public JsonArray getEntitiesList(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, Endpoint endpoint) { return getEntitiesList(deploymentUrl, adminUsername, adminAuthToken, adminAccountSid, endpoint, null); } private String getEntitiesUrl(String deploymentUrl, String accountSid, Endpoint endpoint) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } String entitiesUrl = deploymentUrl + "/2012-04-24/Accounts/" + accountSid + "/" + endpoint.getName() + endpoint.getExtension(); return entitiesUrl; } private String getEntityUrl(String deploymentUrl, String accountSid, Endpoint endpoint, String entitySid) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } String entityUrl = deploymentUrl + "/2012-04-24/Accounts/" + accountSid + "/" + endpoint.getName() + "/" + entitySid + endpoint.getExtension(); return entityUrl; } public JsonObject getEntity(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String applicationSid, Endpoint endpoint) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getEntityUrl(deploymentUrl, adminAccountSid, endpoint, applicationSid); WebResource webResource = jerseyClient.resource(url); String response = null; JsonObject jsonResponse = null; try { response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); } catch (Exception e) { System.out.println(e.getMessage()); } return jsonResponse; } }
5,177
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmsEndpointTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/sms/SmsEndpointTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.sms; import java.util.HashMap; import java.util.Iterator; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.util.Map; /** * @author <a href="mailto:[email protected]">gvagenas</a> * */ public class SmsEndpointTool { private static SmsEndpointTool instance; private static String accountsUrl; private SmsEndpointTool() {} public static SmsEndpointTool getInstance() { if (instance == null) instance = new SmsEndpointTool(); return instance; } private String getAccountsUrl(String deploymentUrl, String username, Boolean json) { if (accountsUrl == null) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/SMS/Messages" + ((json) ? ".json" : ""); } return accountsUrl; } public JsonObject createSms (String deploymentUrl, String username, String authToken, String from, String to, String body, HashMap<String, String> additionalHeaders) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("From", from); params.add("To", to); params.add("Body", body); if (additionalHeaders != null && !additionalHeaders.isEmpty()){ Iterator<String> iter = additionalHeaders.keySet().iterator(); while (iter.hasNext()) { String headerName = iter.next(); params.add(headerName, additionalHeaders.get(headerName)); } } // webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject createSms (String deploymentUrl, String username, String authToken, String from, String to, String body, HashMap<String, String> additionalHeaders, String encoding) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("From", from); params.add("To", to); params.add("Encoding", encoding); params.add("Body", body); if (additionalHeaders != null && !additionalHeaders.isEmpty()){ Iterator<String> iter = additionalHeaders.keySet().iterator(); while (iter.hasNext()) { String headerName = iter.next(); params.add(headerName, additionalHeaders.get(headerName)); } } // webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonArray getSmsList(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonArray jsonArray = null; JsonObject jsonObject = parser.parse(response).getAsJsonObject(); jsonArray = jsonObject.get("messages").getAsJsonArray(); return jsonArray; } public JsonObject getSmsMessageList (String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getSmsMessageList (String deploymentUrl, String username, String authToken, Integer page, Integer pageSize, String sortingParameters, Boolean json) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response; MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (sortingParameters != null) { params.add("SortBy", sortingParameters); } if (page != null || pageSize != null) { if (page != null) params.add("Page", String.valueOf(page)); if (pageSize != null) params.add("PageSize", String.valueOf(pageSize)); } if (!params.isEmpty()) { response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getSmsMessageListUsingFilter(String deploymentUrl, String username, String authToken, Map<String, String> filters) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getSmsMessage(String deploymentUrl, String username, String authToken, String sid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, false)+"/"+sid; WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } }
9,049
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MonitoringServiceTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/tools/MonitoringServiceTool.java
package org.restcomm.connect.testsuite.tools; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.ws.rs.core.MediaType; import org.apache.log4j.Logger; /** * Created by gvagenas on 11/25/15. */ public class MonitoringServiceTool { private static MonitoringServiceTool instance; private static Logger logger = Logger.getLogger(MonitoringServiceTool.class); private MonitoringServiceTool() { } public static MonitoringServiceTool getInstance() { if (instance == null) { instance = new MonitoringServiceTool(); } return instance; } public String getAccountsUrl(String deploymentUrl, String username) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } String accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Supervisor.json"; return accountsUrl; } public JsonObject getLiveCalls(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username); WebResource webResource = jerseyClient.resource(url).path("/livecalls"); String response = null; response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); JsonParser parser = new JsonParser(); return parser.parse(response).getAsJsonObject(); } public Map<String, Integer> getMgcpResources(JsonObject metrics) { Integer mgcpEndpoints = metrics.getAsJsonObject("Metrics").get("MgcpEndpoints").getAsInt(); Integer mgcpConnections = metrics.getAsJsonObject("Metrics").get("MgcpConnections").getAsInt(); Map<String, Integer> mgcpResources = new ConcurrentHashMap<String, Integer>(); mgcpResources.put("MgcpEndpoints", mgcpEndpoints); mgcpResources.put("MgcpConnections", mgcpConnections); return mgcpResources; } public JsonObject getMetrics(String deploymentUrl, String username, String authToken) { return getMetrics(deploymentUrl, username, authToken, true, true); } public JsonObject getMetrics(String deploymentUrl, String username, String authToken, boolean callDetails, boolean mgcpStats) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username); WebResource webResource = jerseyClient.resource(url).path("/metrics"); if (callDetails) { webResource = webResource.queryParam("LiveCallDetails", "true"); } if (mgcpStats) { webResource = webResource.queryParam("MgcpStats", "true"); } String response = null; response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); JsonParser parser = new JsonParser(); return parser.parse(response).getAsJsonObject(); } public int getRegisteredUsers(String deploymentUrl, String username, String authToken) { int registeredUsers = 0; JsonObject jsonObject = getMetrics(deploymentUrl, username, authToken); // {"InstanceId":"IDbe78ada9dc864b558774ce4432cac866","Version":"7.5.0-SNAPSHOT","Revision":"r35cf44c0589a0aeabd6ae8d1bfab0a9edcd24c1a","Metrics":{"TotalCallsSinceUptime":0,"NoAnswerCalls":0,"LiveOutgoingCalls":0,"OutgoingCallsSinceUptime":0,"IncomingCallsSinceUptime":0,"RegisteredUsers":1,"CompletedCalls":0,"TextMessageOutbound":0,"NotFoundCalls":0,"CanceledCalls":0,"FailedCalls":0,"TextMessageNotFound":0,"TextMessageInboundToApp":0,"LiveCalls":0,"BusyCalls":0,"LiveIncomingCalls":0,"TextMessageInboundToProxyOut":0,"TextMessageInboundToClient":0},"LiveCallDetails":[]} JsonObject metrics = jsonObject.getAsJsonObject("Metrics"); JsonElement elem = metrics.get("RegisteredUsers"); registeredUsers = elem.getAsInt(); return registeredUsers; } public int getStatistics(String deploymentUrl, String username, String authToken) { int liveCalls = 0; JsonObject jsonObject = getMetrics(deploymentUrl, username, authToken); // {"InstanceId":"IDbe78ada9dc864b558774ce4432cac866","Version":"7.5.0-SNAPSHOT","Revision":"r35cf44c0589a0aeabd6ae8d1bfab0a9edcd24c1a","Metrics":{"TotalCallsSinceUptime":0,"NoAnswerCalls":0,"LiveOutgoingCalls":0,"OutgoingCallsSinceUptime":0,"IncomingCallsSinceUptime":0,"RegisteredUsers":1,"CompletedCalls":0,"TextMessageOutbound":0,"NotFoundCalls":0,"CanceledCalls":0,"FailedCalls":0,"TextMessageNotFound":0,"TextMessageInboundToApp":0,"LiveCalls":0,"BusyCalls":0,"LiveIncomingCalls":0,"TextMessageInboundToProxyOut":0,"TextMessageInboundToClient":0},"LiveCallDetails":[]} JsonObject metrics = jsonObject.getAsJsonObject("Metrics"); JsonElement elem = metrics.get("LiveCalls"); liveCalls = elem.getAsInt(); return liveCalls; } public int getLiveIncomingCallStatistics(String deploymentUrl, String username, String authToken) { int liveIncomingCalls = 0; JsonObject jsonObject = getMetrics(deploymentUrl, username, authToken); // {"InstanceId":"IDbe78ada9dc864b558774ce4432cac866","Version":"7.5.0-SNAPSHOT","Revision":"r35cf44c0589a0aeabd6ae8d1bfab0a9edcd24c1a","Metrics":{"TotalCallsSinceUptime":0,"NoAnswerCalls":0,"LiveOutgoingCalls":0,"OutgoingCallsSinceUptime":0,"IncomingCallsSinceUptime":0,"RegisteredUsers":1,"CompletedCalls":0,"TextMessageOutbound":0,"NotFoundCalls":0,"CanceledCalls":0,"FailedCalls":0,"TextMessageNotFound":0,"TextMessageInboundToApp":0,"LiveCalls":0,"BusyCalls":0,"LiveIncomingCalls":0,"TextMessageInboundToProxyOut":0,"TextMessageInboundToClient":0},"LiveCallDetails":[]} JsonObject metrics = jsonObject.getAsJsonObject("Metrics"); JsonElement elem = metrics.get("LiveIncomingCalls"); liveIncomingCalls = elem.getAsInt(); return liveIncomingCalls; } public int getLiveOutgoingCallStatistics(String deploymentUrl, String username, String authToken) { int liveOutgoingCalls = 0; JsonObject jsonObject = getMetrics(deploymentUrl, username, authToken); // {"InstanceId":"IDbe78ada9dc864b558774ce4432cac866","Version":"7.5.0-SNAPSHOT","Revision":"r35cf44c0589a0aeabd6ae8d1bfab0a9edcd24c1a","Metrics":{"TotalCallsSinceUptime":0,"NoAnswerCalls":0,"LiveOutgoingCalls":0,"OutgoingCallsSinceUptime":0,"IncomingCallsSinceUptime":0,"RegisteredUsers":1,"CompletedCalls":0,"TextMessageOutbound":0,"NotFoundCalls":0,"CanceledCalls":0,"FailedCalls":0,"TextMessageNotFound":0,"TextMessageInboundToApp":0,"LiveCalls":0,"BusyCalls":0,"LiveIncomingCalls":0,"TextMessageInboundToProxyOut":0,"TextMessageInboundToClient":0},"LiveCallDetails":[]} JsonObject metrics = jsonObject.getAsJsonObject("Metrics"); JsonElement elem = metrics.get("LiveOutgoingCalls"); liveOutgoingCalls = elem.getAsInt(); return liveOutgoingCalls; } public int getLiveCallsArraySize(String deploymentUrl, String username, String authToken) { int liveCallsArraySize = 0; JsonObject jsonObject = getLiveCalls(deploymentUrl, username, authToken); // {"InstanceId":"IDbe78ada9dc864b558774ce4432cac866","Version":"7.5.0-SNAPSHOT","Revision":"r35cf44c0589a0aeabd6ae8d1bfab0a9edcd24c1a","Metrics":{"TotalCallsSinceUptime":0,"NoAnswerCalls":0,"LiveOutgoingCalls":0,"OutgoingCallsSinceUptime":0,"IncomingCallsSinceUptime":0,"RegisteredUsers":1,"CompletedCalls":0,"TextMessageOutbound":0,"NotFoundCalls":0,"CanceledCalls":0,"FailedCalls":0,"TextMessageNotFound":0,"TextMessageInboundToApp":0,"LiveCalls":0,"BusyCalls":0,"LiveIncomingCalls":0,"TextMessageInboundToProxyOut":0,"TextMessageInboundToClient":0},"LiveCallDetails":[]} JsonArray liveCallDetails = jsonObject.getAsJsonArray("LiveCallDetails"); liveCallsArraySize = liveCallDetails.size(); // JsonElement elem = metrics.get("LiveCalls"); // // liveCallsArraySize = elem.getAsInt(); return liveCallsArraySize; } public int getMaxConcurrentCalls(String deploymentUrl, String username, String authToken) { int maxConcurrentCalls = 0; JsonObject jsonObject = getMetrics(deploymentUrl, username, authToken); JsonObject metrics = jsonObject.getAsJsonObject("Metrics"); JsonElement elem = metrics.get("MaximumConcurrentCalls"); maxConcurrentCalls = elem.getAsInt(); return maxConcurrentCalls; } public int getMaxConcurrentIncomingCalls(String deploymentUrl, String username, String authToken) { int maxConcurrentIncomingCalls = 0; JsonObject jsonObject = getMetrics(deploymentUrl, username, authToken); JsonObject metrics = jsonObject.getAsJsonObject("Metrics"); JsonElement elem = metrics.get("MaximumConcurrentIncomingCalls"); maxConcurrentIncomingCalls = elem.getAsInt(); return maxConcurrentIncomingCalls; } public int getMaxConcurrentOutgoingCalls(String deploymentUrl, String username, String authToken) { int maxConcurrentOutgoingCalls = 0; JsonObject jsonObject = getMetrics(deploymentUrl, username, authToken); JsonObject metrics = jsonObject.getAsJsonObject("Metrics"); JsonElement elem = metrics.get("MaximumConcurrentIncomingCalls"); maxConcurrentOutgoingCalls = elem.getAsInt(); return maxConcurrentOutgoingCalls; } }
9,936
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommApplicationsTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommApplicationsTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * @author [email protected] */ public class RestcommApplicationsTool { private static RestcommApplicationsTool instance; private static String applicationsUrl; public static RestcommApplicationsTool getInstance() { if (instance == null) { instance = new RestcommApplicationsTool(); } return instance; } private String getApplicationsUrl(String deploymentUrl, String accountSid, Boolean xml) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } applicationsUrl = deploymentUrl + "/2012-04-24/Accounts/" + accountSid + "/Applications"; if (!xml) { applicationsUrl += ".json"; } return applicationsUrl; } private String getApplicationUrl(String deploymentUrl, String accountSid, String applicationSid, Boolean xml) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } applicationsUrl = deploymentUrl + "/2012-04-24/Accounts/" + accountSid + "/Applications/" + applicationSid; if (!xml) { applicationsUrl += ".json"; } return applicationsUrl; } private String getEndpoint(String deploymentUrl) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } return deploymentUrl; } public JsonObject createApplication(String deploymentUrl, String adminAccountSid, String adminUsername, String adminAuthToken, MultivaluedMap<String, String> applicationParams) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getApplicationsUrl(deploymentUrl, adminAccountSid, false); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, applicationParams); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); return jsonResponse; } public JsonObject getApplication(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String applicationSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getApplicationUrl(deploymentUrl, adminAccountSid, applicationSid, false); WebResource webResource = jerseyClient.resource(url); String response = null; JsonObject jsonResponse = null; try { response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); } catch (Exception e) { System.out.println(e.getMessage()); } return jsonResponse; } public JsonArray getApplications(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid) { return getApplications(deploymentUrl, adminUsername, adminAuthToken, adminAccountSid, false); } public JsonArray getApplications(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, boolean includeNumbers) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getApplicationsUrl(deploymentUrl, adminAccountSid, false); WebResource webResource = jerseyClient.resource(url); if (includeNumbers) { webResource = webResource.queryParam("includeNumbers", "true"); } String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); return jsonResponse; } public JsonObject updateApplication(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String applicationSid, MultivaluedMap<String, String> applicationParams, boolean usePut) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getApplicationUrl(deploymentUrl, adminAccountSid, applicationSid, false); WebResource webResource = jerseyClient.resource(url); String response = ""; if (usePut) { response = webResource.accept(MediaType.APPLICATION_JSON).put(String.class, applicationParams); } else { response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, applicationParams); } JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); return jsonResponse; } public void deleteApplication(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String applicationSid) throws IOException { String endpoint = getEndpoint(deploymentUrl).replaceAll("http://", ""); String url = getApplicationUrl("http://" + adminAccountSid + ":" + adminAuthToken + "@" + endpoint, adminAccountSid, applicationSid, false); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminAccountSid, adminAuthToken)); WebResource webResource = jerseyClient.resource(url); webResource.accept(MediaType.APPLICATION_JSON).delete(); } }
7,173
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateClientsTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/CreateClientsTool.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; /** * @author <a href="mailto:[email protected]">gvagenas</a> * @author <a href="mailto:[email protected]">Thinh Ly</a> */ public class CreateClientsTool { private static CreateClientsTool instance; private static String clientUrl; private CreateClientsTool() { } public static CreateClientsTool getInstance() { if (instance == null) { instance = new CreateClientsTool(); } return instance; } private String getEndpoint(String deploymentUrl) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } return deploymentUrl; } private String getAuthorizationToken(String username, String password) { byte[] usernamePassBytes = (username + ":" + password).getBytes(Charset.forName("UTF-8")); String authenticationToken = Base64.encodeBase64String(usernamePassBytes); return authenticationToken; } private String getClientUrl(String deploymentUrl, JsonObject account) { return getClientUrl(deploymentUrl, account, false); } private String getClientUrl(String deploymentUrl, JsonObject account, Boolean xml) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } StringBuffer curlCommand = new StringBuffer("http://"); curlCommand.append(account.get("sid")); curlCommand.append(":"); curlCommand.append(account.get("auth_token")); curlCommand.append(deploymentUrl.replace("http://", "@")); curlCommand.append("/2012-04-24/Accounts/").append(account.get("sid")); if (xml) { curlCommand.append("/Clients"); } else { curlCommand.append("/Clients.json"); } return curlCommand.toString().replace("\"", ""); } public JsonObject getClientOfAccount(String deploymentUrl, JsonObject account, String credentialUsername, String credentialPassword) { String url = getClientUrl(deploymentUrl, account); JsonObject jsonResponse = null; String authToken = getAuthorizationToken(credentialUsername, credentialPassword); try { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); httpGet.addHeader("Authorization", "Basic " + authToken); HttpResponse response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity entity = response.getEntity(); String res = EntityUtils.toString(entity); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(res).getAsJsonArray(); if (jArray.size() > 0) // handle also empty arrays i.e. return null in such a case { jsonResponse = jArray.get(0).getAsJsonObject(); } } httpGet.releaseConnection(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return jsonResponse; } public void updateClientVoiceUrl(String deploymentUrl, JsonObject account, String clientSid, String voiceUrl, String credentialUsername, String credentialPassword) throws IOException { String url = getClientUrl(deploymentUrl, account); String clientUrl = url.replace("Clients.json", "Clients/" + clientSid); String authToken = getAuthorizationToken(credentialUsername, credentialPassword); HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(clientUrl); httpPost.addHeader("Authorization", "Basic " + authToken); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if (voiceUrl != null) { nvps.add(new BasicNameValuePair("VoiceUrl", voiceUrl)); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = httpclient.execute(httpPost); httpPost.releaseConnection(); } public HttpResponse createClientResponse(String deploymentUrl, String username, String password, String voiceUrl) throws IOException { String endpoint = getEndpoint(deploymentUrl).replaceAll("http://", ""); String url = "http://ACae6e420f425248d6a26948c17a9e2acf:77f8c12cc7b8f8423e5c38b035249166@" + endpoint + "/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Clients.json"; HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("Login", username)); nvps.add(new BasicNameValuePair("Password", password)); if (voiceUrl != null) { nvps.add(new BasicNameValuePair("VoiceUrl", voiceUrl)); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); HttpResponse response = httpclient.execute(httpPost); httpPost.releaseConnection(); return response; } public String createClient(String deploymentUrl, String username, String password, String voiceUrl) throws IOException { return createClient(deploymentUrl, "ACae6e420f425248d6a26948c17a9e2acf", "77f8c12cc7b8f8423e5c38b035249166", username, password, voiceUrl); } public String createClient(String deploymentUrl, String accountSid, String authToken, String username, String password, String voiceUrl) throws IOException { String clientSid = null; String endpoint = getEndpoint(deploymentUrl).replaceAll("http://", ""); String url = "http://" + accountSid + ":" + authToken + "@" + endpoint + "/2012-04-24/Accounts/" + accountSid + "/Clients.json"; RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 1000).build(); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("Login", username)); nvps.add(new BasicNameValuePair("Password", password)); if (voiceUrl != null) { nvps.add(new BasicNameValuePair("VoiceUrl", voiceUrl)); } httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String res = EntityUtils.toString(entity, "UTF-8"); response.close(); httpClient.close(); res = res.replaceAll("\\{", "").replaceAll("\\}", ""); String[] components = res.split(","); System.out.println("createClient res: " + res + " components: " + components); clientSid = (components[0].split(":")[1]).replaceAll("\"", "").trim(); return clientSid; } }
8,174
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommConferenceParticipantsTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommConferenceParticipantsTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.thoughtworks.xstream.XStream; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; import org.restcomm.connect.dao.entities.CallDetailRecordList; /** * @author maria */ public class RestcommConferenceParticipantsTool { private static RestcommConferenceParticipantsTool instance; private static String accountsUrl; private static Logger logger = Logger.getLogger(RestcommConferenceParticipantsTool.class); private RestcommConferenceParticipantsTool() { } public static RestcommConferenceParticipantsTool getInstance() { if (instance == null) { instance = new RestcommConferenceParticipantsTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username, String conferenceSid, Boolean json) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Conferences/" + conferenceSid + "/Participants" + ((json) ? ".json" : ""); return accountsUrl; } public JsonObject getParticipants(String deploymentUrl, String username, String authToken, String conferenceSid) { return (JsonObject) getParticipants(deploymentUrl, username, authToken, conferenceSid, null, null, true); } public JsonObject getParticipants(String deploymentUrl, String username, String authToken, String conferenceSid, Integer page, Integer pageSize, Boolean json) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, conferenceSid, json); WebResource webResource = jerseyClient.resource(url); String response = null; if (page != null || pageSize != null) { MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (page != null) { params.add("Page", String.valueOf(page)); } if (pageSize != null) { params.add("PageSize", String.valueOf(pageSize)); } response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); if (json) { JsonObject jsonObject = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonObject()) { jsonObject = jsonElement.getAsJsonObject(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonObject; } else { XStream xstream = new XStream(); xstream.alias("cdrlist", CallDetailRecordList.class); JsonObject jsonObject = parser.parse(xstream.toXML(response)).getAsJsonObject(); return jsonObject; } } public JsonObject getParticipant(String deploymentUrl, String username, String conferenceSid, String authToken, String sid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, conferenceSid, false); WebResource webResource = jerseyClient.resource(url); String response = null; webResource = webResource.path(String.valueOf(sid) + ".json"); logger.info("The URI to sent: " + webResource.getURI()); response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getParticipantsUsingFilter(String deploymentUrl, String username, String conferenceSid, String authToken, Map<String, String> filters) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, conferenceSid, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject modifyCall(String deploymentUrl, String username, String conferenceSid, String authToken, String callSid, Boolean muted) throws Exception { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, conferenceSid, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (muted != null) { params.add("Mute", "" + muted); } JsonObject jsonObject = null; try { String response = webResource.path(callSid).accept(MediaType.APPLICATION_JSON).post(String.class, params); JsonParser parser = new JsonParser(); jsonObject = parser.parse(response).getAsJsonObject(); } catch (Exception e) { logger.info("Exception e: " + e); UniformInterfaceException exception = (UniformInterfaceException) e; jsonObject = new JsonObject(); jsonObject.addProperty("Exception", exception.getResponse().getStatus()); } return jsonObject; } }
7,788
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommProfilesTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommProfilesTool.java
package org.restcomm.connect.testsuite.http; import com.google.common.net.HttpHeaders; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.header.LinkHeader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.util.logging.Logger; import javax.ws.rs.core.MediaType; import org.apache.commons.codec.binary.Base64; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.restcomm.connect.testsuite.http.util.HttpLink; import org.restcomm.connect.testsuite.http.util.HttpUnLink; /** * @author maria farooq */ public class RestcommProfilesTool { private static Logger logger = Logger.getLogger(RestcommProfilesTool.class.getName()); private static RestcommProfilesTool instance; private static String profilesEndpointUrl; private static final String PROFILE_SCHEMA_PATH = "rc-profile-schema.json"; public static final String PROFILE_REL_TYPE = "related"; public static final String PROFILE_CONTENT_TYPE = "application/instance+json"; public static final String PROFILE_SCHEMA_CONTENT_TYPE = "application/schema+json"; private static final String ACCOUNT_ENPOINT_BASE = "/2012-04-24/Accounts/"; private static final String ORGANIZATION_ENPOINT_BASE = "/2012-04-24/Organizations/"; private static final String PROFILE_ENPOINT_BASE = "/2012-04-24/Profiles"; public enum AssociatedResourceType { ACCOUNT, ORGANIZATION }; public static RestcommProfilesTool getInstance() { if (instance == null) { instance = new RestcommProfilesTool(); } return instance; } private String getTargetResourceUrl(String deploymentUrl, String targetResourceSid, AssociatedResourceType type) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } switch (type) { case ACCOUNT: return deploymentUrl + ACCOUNT_ENPOINT_BASE + targetResourceSid; case ORGANIZATION: return deploymentUrl + ORGANIZATION_ENPOINT_BASE + targetResourceSid; default: return null; } } /** * @param deploymentUrl * @return */ private String getProfilesEndpointUrl(String deploymentUrl) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } profilesEndpointUrl = deploymentUrl + PROFILE_ENPOINT_BASE; return profilesEndpointUrl; } /** * @param deploymentUrl * @return */ public String getProfileSchemaUrl(String deploymentUrl) { return getProfilesEndpointUrl(deploymentUrl) + "/schemas/" + PROFILE_SCHEMA_PATH; } public ClientResponse getProfileSchema(String deploymentUrl, String adminUsername, String adminAuthToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); WebResource webResource = jerseyClient.resource(getProfileSchemaUrl(deploymentUrl)); ClientResponse response = webResource.accept(PROFILE_SCHEMA_CONTENT_TYPE).get(ClientResponse.class); return response; } /** * get a particular profile and return json response * * @param deploymentUrl * @param adminUsername * @param adminAuthToken * @param profileSid * @return * @throws UniformInterfaceException */ public JsonObject getProfile(String deploymentUrl, String adminUsername, String adminAuthToken, String profileSid) throws UniformInterfaceException { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); JsonObject jsonResponse = null; try { ClientResponse clientResponse = getProfileResponse(deploymentUrl, adminUsername, adminAuthToken, profileSid); jsonResponse = new JsonParser().parse(clientResponse.getEntity(String.class)).getAsJsonObject(); } catch (Exception e) { logger.info("Exception: " + e); } return jsonResponse; } /** * get a particular profile and return raw response * * @param deploymentUrl * @param username * @param authtoken * @param profileSid * @return */ public ClientResponse getProfileResponse(String deploymentUrl, String username, String authtoken, String profileSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authtoken)); WebResource webResource = jerseyClient.resource(getProfilesEndpointUrl(deploymentUrl)); ClientResponse response = webResource.path(profileSid).accept(PROFILE_CONTENT_TYPE).get(ClientResponse.class); return response; } /** * get profile list and return json response * * @param deploymentUrl * @param adminUsername * @param adminAuthToken * @return * @throws UniformInterfaceException */ public JsonArray getProfileListJsonResponse(String deploymentUrl, String adminUsername, String adminAuthToken) throws UniformInterfaceException { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); WebResource webResource = jerseyClient.resource(getProfilesEndpointUrl(deploymentUrl)); String response; response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonArray jsonArray = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonArray()) { jsonArray = jsonElement.getAsJsonArray(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonArray; } /** * get profile list and return raw response * * @param deploymentUrl * @param username * @param authtoken * @return */ public ClientResponse getProfileListClientResponse(String deploymentUrl, String username, String authtoken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authtoken)); WebResource webResource = jerseyClient.resource(getProfilesEndpointUrl(deploymentUrl)); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class); return response; } /** * create a profile and return json response * * @param deploymentUrl * @param username * @param adminAuthToken * @param profileDocument * @return */ public JsonObject createProfile(String deploymentUrl, String username, String adminAuthToken, String profileDocument) { JsonParser parser = new JsonParser(); JsonObject jsonResponse = null; try { ClientResponse clientResponse = createProfileResponse(deploymentUrl, username, adminAuthToken, profileDocument); jsonResponse = parser.parse(clientResponse.getEntity(String.class)).getAsJsonObject(); } catch (Exception e) { logger.info("Exception: " + e); } return jsonResponse; } /** * create a profile and return raw response * * @param deploymentUrl * @param operatorUsername * @param operatorAuthtoken * @param profileDocument * @return */ public ClientResponse createProfileResponse(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String profileDocument) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(operatorUsername, operatorAuthtoken)); String url = getProfilesEndpointUrl(deploymentUrl); WebResource webResource = jerseyClient.resource(url); ClientResponse response = webResource.type(PROFILE_CONTENT_TYPE).accept(PROFILE_CONTENT_TYPE).post(ClientResponse.class, profileDocument); return response; } /** * update a profile and return json response * * @param deploymentUrl * @param username * @param adminAuthToken * @param profileSid * @param profileDocument * @return */ public JsonObject updateProfile(String deploymentUrl, String username, String adminAuthToken, String profileSid, String profileDocument) { JsonParser parser = new JsonParser(); JsonObject jsonResponse = null; try { ClientResponse clientResponse = updateProfileResponse(deploymentUrl, username, adminAuthToken, profileSid, profileDocument); jsonResponse = parser.parse(clientResponse.getEntity(String.class)).getAsJsonObject(); } catch (Exception e) { logger.info("Exception: " + e); } return jsonResponse; } /** * update a profile and return raw response * * @param deploymentUrl * @param operatorUsername * @param operatorAuthtoken * @param profileSid * @param profileDocument * @return */ public ClientResponse updateProfileResponse(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String profileSid, String profileDocument) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(operatorUsername, operatorAuthtoken)); String url = getProfilesEndpointUrl(deploymentUrl) + "/" + profileSid; WebResource webResource = jerseyClient.resource(url); ClientResponse response = webResource.type(PROFILE_CONTENT_TYPE).accept(PROFILE_CONTENT_TYPE).put(ClientResponse.class, profileDocument); return response; } /** * delete a profile and return raw response * * @param deploymentUrl * @param operatorUsername * @param operatorAuthtoken * @param profileSid * @return */ public ClientResponse deleteProfileResponse(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String profileSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(operatorUsername, operatorAuthtoken)); String url = getProfilesEndpointUrl(deploymentUrl) + "/" + profileSid; WebResource webResource = jerseyClient.resource(url); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).delete(ClientResponse.class); return response; } /** * link a profile to a target resource * * @param deploymentUrl * @param operatorUsername * @param operatorAuthtoken * @param profileSid * @param targetResourceSid * @param associatedResourceType * @return * @throws IOException * @throws URISyntaxException */ public HttpResponse linkProfile(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String profileSid, String targetResourceSid, AssociatedResourceType type) throws IOException, URISyntaxException { String url = getProfilesEndpointUrl(deploymentUrl) + "/" + profileSid; HttpLink request = new HttpLink(url); request = (HttpLink) addLinkUnlinkRequiredHeaders(request, deploymentUrl, operatorUsername, operatorAuthtoken, profileSid, targetResourceSid, type); final DefaultHttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); logger.info("response is here: " + response); return response; } public HttpResponse linkProfileWithOverride(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String profileSid, String targetResourceSid, AssociatedResourceType type) throws IOException, URISyntaxException { String url = getProfilesEndpointUrl(deploymentUrl) + "/" + profileSid; HttpPut request = new HttpPut(url); addLinkUnlinkRequiredHeaders(request, deploymentUrl, operatorUsername, operatorAuthtoken, profileSid, targetResourceSid, type); request.addHeader("X-HTTP-Method-Override", "LINK"); final DefaultHttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); logger.info("response is here: " + response); return response; } /** * unlink a profile from a target resource * * @param deploymentUrl * @param operatorUsername * @param operatorAuthtoken * @param profileSid * @param targetResourceSid * @param associatedResourceType * @return * @throws IOException * @throws URISyntaxException */ public HttpResponse unLinkProfile(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String profileSid, String targetResourceSid, AssociatedResourceType type) throws IOException, URISyntaxException { String url = getProfilesEndpointUrl(deploymentUrl) + "/" + profileSid; HttpUnLink request = new HttpUnLink(url); request = (HttpUnLink) addLinkUnlinkRequiredHeaders(request, deploymentUrl, operatorUsername, operatorAuthtoken, profileSid, targetResourceSid, type); final DefaultHttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); logger.info("response is here: " + response); return response; } public HttpResponse unLinkProfileWithOverride(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String profileSid, String targetResourceSid, AssociatedResourceType type) throws IOException, URISyntaxException { String url = getProfilesEndpointUrl(deploymentUrl) + "/" + profileSid; HttpPut request = new HttpPut(url); addLinkUnlinkRequiredHeaders(request, deploymentUrl, operatorUsername, operatorAuthtoken, profileSid, targetResourceSid, type); request.addHeader("X-HTTP-Method-Override", "UNLINK"); final DefaultHttpClient client = new DefaultHttpClient(); final HttpResponse response = client.execute(request); logger.info("response is here: " + response); return response; } /** * @param request * @param deploymentUrl * @param operatorUsername * @param operatorAuthtoken * @param profileSid * @param targetResourceSid * @param type * @return * @throws URISyntaxException */ private HttpRequestBase addLinkUnlinkRequiredHeaders(HttpRequestBase request, String deploymentUrl, String operatorUsername, String operatorAuthtoken, String profileSid, String targetResourceSid, AssociatedResourceType type) throws URISyntaxException { request.addHeader(getAuthHeader(deploymentUrl, operatorUsername, operatorAuthtoken)); request.addHeader(getjsonAcceptHeader()); request.addHeader(getLinkHeaderOfTargetResource(deploymentUrl, targetResourceSid, type)); return request; } private BasicHeader getLinkHeaderOfTargetResource(String deploymentUrl, String targetResourceSid, AssociatedResourceType type) throws URISyntaxException { String targetResourceLinkstr = LinkHeader.uri(new URI(getTargetResourceUrl(deploymentUrl, targetResourceSid, type))).rel(PROFILE_REL_TYPE).build().toString(); return new BasicHeader("Link", targetResourceLinkstr); } private BasicHeader getAuthHeader(String deploymentUrl, String operatorUsername, String operatorAuthtoken) { String auth = operatorUsername + ":" + operatorAuthtoken; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("ISO-8859-1"))); return new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(encodedAuth)); } private BasicHeader getjsonAcceptHeader() { return new BasicHeader("Accept", "application/json"); } }
16,781
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommOrganizationsTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommOrganizationsTool.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.util.logging.Logger; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * @author maria farooq */ public class RestcommOrganizationsTool { private static Logger logger = Logger.getLogger(RestcommOrganizationsTool.class.getName()); private static RestcommOrganizationsTool instance; private static String organizationsUrl; private RestcommOrganizationsTool() { } public static RestcommOrganizationsTool getInstance() { if (instance == null) { instance = new RestcommOrganizationsTool(); } return instance; } private String getOrganizationsUrl(String deploymentUrl) { return getOrganizationsUrl(deploymentUrl, false); } private String getOrganizationsUrl(String deploymentUrl, Boolean xml) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } if (xml) { organizationsUrl = deploymentUrl + "/2012-04-24/Organizations"; } else { organizationsUrl = deploymentUrl + "/2012-04-24/Organizations.json"; } return organizationsUrl; } public JsonObject getOrganization(String deploymentUrl, String adminUsername, String adminAuthToken, String organizationSid) throws UniformInterfaceException { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); WebResource webResource = jerseyClient.resource(getOrganizationsUrl(deploymentUrl)); String response = webResource.path(organizationSid).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); return jsonResponse; } public JsonArray getOrganizationList(String deploymentUrl, String adminUsername, String adminAuthToken, String status) throws UniformInterfaceException { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); WebResource webResource = jerseyClient.resource(getOrganizationsUrl(deploymentUrl)); String response; if (status != null) { MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Status", String.valueOf(status)); response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); JsonArray jsonArray = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonArray()) { jsonArray = jsonElement.getAsJsonArray(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonArray; } public ClientResponse getOrganizationResponse(String deploymentUrl, String username, String authtoken, String organizationSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authtoken)); WebResource webResource = jerseyClient.resource(getOrganizationsUrl(deploymentUrl)); ClientResponse response = webResource.path(organizationSid).get(ClientResponse.class); return response; } public ClientResponse getOrganizationsResponse(String deploymentUrl, String username, String authtoken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authtoken)); WebResource webResource = jerseyClient.resource(getOrganizationsUrl(deploymentUrl)); ClientResponse response = webResource.get(ClientResponse.class); return response; } public JsonObject createOrganization(String deploymentUrl, String username, String adminAuthToken, String domainName) { JsonParser parser = new JsonParser(); JsonObject jsonResponse = null; try { ClientResponse clientResponse = createOrganizationResponse(deploymentUrl, username, adminAuthToken, domainName); jsonResponse = parser.parse(clientResponse.getEntity(String.class)).getAsJsonObject(); } catch (Exception e) { logger.info("Exception: " + e); } return jsonResponse; } public ClientResponse createOrganizationResponse(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String domainName) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(operatorUsername, operatorAuthtoken)); String url = getOrganizationsUrl(deploymentUrl) + "/" + domainName; WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).put(ClientResponse.class, params); return response; } public JsonObject migrateClientsOfOrganization(String deploymentUrl, String operatorUsername, String operatorAuthToken, String organizationSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(operatorUsername, operatorAuthToken)); WebResource webResource = jerseyClient.resource(getOrganizationsUrl(deploymentUrl)); WebResource migrateWebResource = webResource.path(organizationSid).path("Migrate"); String response = migrateWebResource.put(String.class); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); return jsonResponse; } }
6,652
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NotificationEndpointTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/NotificationEndpointTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * @author <a href="mailto:[email protected]">vunguyen</a> * */ public class NotificationEndpointTool { private static NotificationEndpointTool instance; private static String accountsUrl; private NotificationEndpointTool() { } public static NotificationEndpointTool getInstance() { if (instance == null) { instance = new NotificationEndpointTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username, Boolean json) { if (accountsUrl == null) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Notifications" + ((json) ? ".json" : ""); } return accountsUrl; } public JsonObject getNotificationList(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getNotificationList(String deploymentUrl, String username, String authToken, Integer page, Integer pageSize, String sortingParameters, Boolean json) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response; MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (sortingParameters != null) { params.add("SortBy", sortingParameters); } if (page != null || pageSize != null) { if (page != null) { params.add("Page", String.valueOf(page)); } if (pageSize != null) { params.add("PageSize", String.valueOf(pageSize)); } } if (!params.isEmpty()) { response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getNotificationListUsingFilter(String deploymentUrl, String username, String authToken, Map<String, String> filters) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } }
5,058
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommCallsTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommCallsTool.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.thoughtworks.xstream.XStream; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; import org.restcomm.connect.dao.entities.CallDetailRecordList; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ public class RestcommCallsTool { private static RestcommCallsTool instance; private static String accountsUrl; private static Logger logger = Logger.getLogger(RestcommCallsTool.class); private RestcommCallsTool() { } public static RestcommCallsTool getInstance() { if (instance == null) { instance = new RestcommCallsTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username, Boolean json) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Calls" + ((json) ? ".json" : ""); return accountsUrl; } private String getRecordingsUrl(String deploymentUrl, String username, Boolean json) { if (accountsUrl == null) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Recordings.json"; } return accountsUrl; } private String getCallRecordingsUrl(String deploymentUrl, String username, String callSid, Boolean json) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } String url = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Calls/" + callSid + "/Recordings" + ((json) ? ".json" : ""); return url; } private String getGateWayUrl(String deploymentUrl, String username) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } String url = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Management/Gateways"; return url; } public JsonArray getRecordings(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getRecordingsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = null; response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); // response = response.replaceAll("\\[", "").replaceAll("]", "").trim(); JsonArray jsonArray = null; try { JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); jsonArray = jsonObject.get("recordings").getAsJsonArray(); } catch (Exception e) { logger.info("Exception during getRecordings for url: " + url + " exception: " + e); logger.info("Response object: " + response); } return jsonArray; } public JsonObject getCalls(String deploymentUrl, String username, String authToken) { return (JsonObject) getCalls(deploymentUrl, username, authToken, null, null, null, true); } public JsonObject getCalls(String deploymentUrl, String username, String authToken, Integer page, Integer pageSize, String sortingParameters, Boolean json) throws UniformInterfaceException { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, json); WebResource webResource = jerseyClient.resource(url); String response = null; MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (sortingParameters != null) { params.add("SortBy", sortingParameters); } if (page != null || pageSize != null) { if (page != null) { params.add("Page", String.valueOf(page)); } if (pageSize != null) { params.add("PageSize", String.valueOf(pageSize)); } } if (!params.isEmpty()) { response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); if (json) { JsonObject jsonObject = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonObject()) { jsonObject = jsonElement.getAsJsonObject(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonObject; } else { XStream xstream = new XStream(); xstream.alias("cdrlist", CallDetailRecordList.class); JsonObject jsonObject = parser.parse(xstream.toXML(response)).getAsJsonObject(); return jsonObject; } } /** * getCall from same account * * @param deploymentUrl * @param username * @param authToken * @param sid * @return */ public JsonObject getCall(String deploymentUrl, String username, String authToken, String sid) { return getCall(deploymentUrl, username, authToken, username, sid); } /** * getCall from another account's resource * https://github.com/RestComm/Restcomm-Connect/issues/1939 * * @param deploymentUrl * @param username * @param authToken * @param resourceAccountSid * @param sid * @return */ public JsonObject getCall(String deploymentUrl, String username, String authToken, String resourceAccountSid, String sid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, resourceAccountSid, false); WebResource webResource = jerseyClient.resource(url); String response = null; webResource = webResource.path(String.valueOf(sid) + ".json"); logger.info("The URI to sent: " + webResource.getURI()); response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getCallsUsingFilter(String deploymentUrl, String username, String authToken, Map<String, String> filters) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonElement createCall(String deploymentUrl, String username, String authToken, String from, String to, String rcmlUrl) { return createCall(deploymentUrl, username, authToken, from, to, rcmlUrl, null, null, null, null); } public JsonElement createCall(String deploymentUrl, String username, String authToken, String from, String to, String rcmlUrl, String timeout) { return createCall(deploymentUrl, username, authToken, from, to, rcmlUrl, null, null, null, timeout); } public JsonElement createCall(String deploymentUrl, String username, String authToken, String from, String to, String rcmlUrl, final String statusCallback, final String statusCallbackMethod, final String statusCallbackEvent) { return createCall(deploymentUrl, username, authToken, from, to, rcmlUrl, statusCallback, statusCallbackMethod, statusCallbackEvent, null); } public JsonElement createCall(String deploymentUrl, String username, String authToken, String from, String to, String rcmlUrl, final String statusCallback, final String statusCallbackMethod, final String statusCallbackEvent, final String timeout) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("From", from); params.add("To", to); params.add("Url", rcmlUrl); if (statusCallback != null) { params.add("StatusCallback", statusCallback); } if (statusCallbackMethod != null) { params.add("StatusCallbackMethod", statusCallbackMethod); } if (statusCallbackEvent != null) { params.add("StatusCallbackEvent", statusCallbackEvent); } if (timeout != null) { params.add("Timeout", timeout); } // webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); JsonParser parser = new JsonParser(); if (response.startsWith("[")) { return parser.parse(response).getAsJsonArray(); } else { return parser.parse(response).getAsJsonObject(); } } /** * @param deploymentUrl * @param username * @param authToken * @param callSid * @param mute * @return * @throws Exception */ public JsonObject modifyCall(String deploymentUrl, String username, String authToken, String callSid, Boolean mute) throws Exception { return modifyCall(deploymentUrl, username, authToken, callSid, null, null, false, mute); } /** * @param deploymentUrl * @param username * @param authToken * @param callSid * @param status * @param rcmlUrl * @return * @throws Exception */ public JsonObject modifyCall(String deploymentUrl, String username, String authToken, String callSid, String status, String rcmlUrl) throws Exception { return modifyCall(deploymentUrl, username, authToken, callSid.trim(), status, rcmlUrl, false, null); } public JsonObject modifyCall(String deploymentUrl, String username, String authToken, String callSid, String status, String rcmlUrl, boolean moveConnectedLeg) throws Exception { return modifyCall(deploymentUrl, username, authToken, callSid, status, rcmlUrl, moveConnectedLeg, null); } /** * @param deploymentUrl * @param username * @param authToken * @param callSid * @param status * @param rcmlUrl * @param moveConnectedLeg * @param mute * @return * @throws Exception */ public JsonObject modifyCall(String deploymentUrl, String username, String authToken, String callSid, String status, String rcmlUrl, boolean moveConnectedLeg, Boolean mute) throws Exception { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (status != null && rcmlUrl != null) { throw new Exception( "You can either redirect a call using the \"url\" attribute or terminate it using the \"status\" attribute!"); } if (status != null) { params.add("Status", status); } if (rcmlUrl != null) { params.add("Url", rcmlUrl); } if (moveConnectedLeg) { params.add("MoveConnectedCallLeg", "true"); } if (mute != null) { if (mute) { params.add("Mute", "true"); } else { params.add("Mute", "false"); } } JsonObject jsonObject = null; try { String response = webResource.path(callSid).accept(MediaType.APPLICATION_JSON).post(String.class, params); JsonParser parser = new JsonParser(); jsonObject = parser.parse(response).getAsJsonObject(); } catch (Exception e) { logger.error("Exception : ", e); UniformInterfaceException exception = (UniformInterfaceException) e; jsonObject = new JsonObject(); jsonObject.addProperty("Exception", exception.getResponse().getStatus()); } return jsonObject; } public JsonArray getCallRecordings(String deploymentUrl, String username, String authToken, String callWithRecordingsSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getCallRecordingsUrl(deploymentUrl, username, callWithRecordingsSid, true); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonArray jsonArray = parser.parse(response).getAsJsonArray(); return jsonArray; } public String setGateWay(String deploymentUrl, String username, String authToken, String friend, String uName, String password, String proxy, boolean register, String ttl) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getGateWayUrl(deploymentUrl, username); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("Register", String.valueOf(register)); if (friend != null) { params.add("FriendlyName", friend); } if (uName != null) { params.add("UserName", uName); } if (password != null) { params.add("Password", password); } if (proxy != null) { params.add("Proxy", proxy); } if (ttl != null) { params.add("TTL", ttl); } String response = null; try { response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); } catch (Exception e) { logger.error("Exception : ", e); UniformInterfaceException exception = (UniformInterfaceException) e; } return response; } }
16,276
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
OutboundProxyTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/OutboundProxyTool.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import javax.ws.rs.core.MediaType; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ public class OutboundProxyTool { private static OutboundProxyTool instance; private static String accountsUrl; private OutboundProxyTool() { } public static OutboundProxyTool getInstance() { if (instance == null) { instance = new OutboundProxyTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username, Boolean json) { if (accountsUrl == null) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/OutboundProxy" + ((json) ? ".json" : ""); } return accountsUrl; } public JsonObject getProxies(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = null; response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject switchProxy(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = null; response = webResource.path("switchProxy").accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getActiveProxy(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = null; response = webResource.path("getActiveProxy").accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } }
3,155
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommMultitenancyTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommMultitenancyTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.connect.testsuite.http; import java.io.IOException; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.codec.binary.Base64; import wiremock.org.apache.http.NameValuePair; import wiremock.org.apache.http.client.entity.UrlEncodedFormEntity; import wiremock.org.apache.http.client.methods.CloseableHttpResponse; import wiremock.org.apache.http.client.methods.HttpDelete; import wiremock.org.apache.http.client.methods.HttpGet; import wiremock.org.apache.http.client.methods.HttpPost; import wiremock.org.apache.http.client.methods.HttpPut; import wiremock.org.apache.http.impl.client.CloseableHttpClient; import wiremock.org.apache.http.impl.client.HttpClients; import wiremock.org.apache.http.message.BasicNameValuePair; /** * @author [email protected] */ public class RestcommMultitenancyTool { private static RestcommMultitenancyTool instance; public static RestcommMultitenancyTool getInstance() { if (instance == null) { instance = new RestcommMultitenancyTool(); } return instance; } public int get(String url, String credentialUsername, String credentialPassword) throws IOException { CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse apiResponse = null; HttpGet get = new HttpGet(url); get.addHeader("Authorization", "Basic " + getAuthorizationToken(credentialUsername, credentialPassword)); apiResponse = client.execute(get); return apiResponse.getStatusLine().getStatusCode(); } public int post(String url, String credentialUsername, String credentialPassword, HashMap<String, String> params) throws IOException { CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse apiResponse = null; HttpPost post = new HttpPost(url); List<NameValuePair> values = new ArrayList<NameValuePair>(); Iterator it = params.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); values.add(new BasicNameValuePair(String.valueOf(pair.getKey()), String.valueOf(pair.getValue()))); } post.setEntity(new UrlEncodedFormEntity(values)); post.addHeader("Authorization", "Basic " + getAuthorizationToken(credentialUsername, credentialPassword)); apiResponse = client.execute(post); return apiResponse.getStatusLine().getStatusCode(); } public int delete(String url, String credentialUsername, String credentialPassword) throws IOException { CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse apiResponse = null; HttpDelete delete = new HttpDelete(url); delete.addHeader("Authorization", "Basic " + getAuthorizationToken(credentialUsername, credentialPassword)); apiResponse = client.execute(delete); return apiResponse.getStatusLine().getStatusCode(); } public int update(String url, String credentialUsername, String credentialPassword, Map<String, String> params) throws IOException { CloseableHttpClient client = HttpClients.createDefault(); CloseableHttpResponse apiResponse = null; HttpPut put = new HttpPut(url); List<NameValuePair> values = new ArrayList<NameValuePair>(); Iterator it = params.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); values.add(new BasicNameValuePair(String.valueOf(pair.getKey()), String.valueOf(pair.getValue()))); } put.setEntity(new UrlEncodedFormEntity(values)); put.addHeader("Authorization", "Basic " + getAuthorizationToken(credentialUsername, credentialPassword)); apiResponse = client.execute(put); return apiResponse.getStatusLine().getStatusCode(); } private String getAuthorizationToken(String username, String password) { byte[] usernamePassBytes = (username + ":" + password).getBytes(Charset.forName("UTF-8")); String authenticationToken = Base64.encodeBase64String(usernamePassBytes); return authenticationToken; } }
5,289
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommExtensionsConfigurationTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommExtensionsConfigurationTool.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import java.util.logging.Logger; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ public class RestcommExtensionsConfigurationTool { private static Logger logger = Logger.getLogger(RestcommExtensionsConfigurationTool.class.getName()); private static RestcommExtensionsConfigurationTool instance; private static String accountsUrl; private RestcommExtensionsConfigurationTool() { } public static RestcommExtensionsConfigurationTool getInstance() { if (instance == null) { instance = new RestcommExtensionsConfigurationTool(); } return instance; } private String getUrl(String deploymentUrl, Boolean xml) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } if (xml) { accountsUrl = deploymentUrl + "/2012-04-24/ExtensionsConfiguration"; } else { accountsUrl = deploymentUrl + "/2012-04-24/ExtensionsConfiguration.json"; } return accountsUrl; } public JsonObject postConfiguration(String deploymentUrl, String adminUsername, String adminAuthToken, MultivaluedMap<String, String> configurationParams) { return postConfiguration(deploymentUrl, adminUsername, adminAuthToken, configurationParams, false); } public JsonObject postConfiguration(String deploymentUrl, String adminUsername, String adminAuthToken, MultivaluedMap<String, String> configurationParams, Boolean xml) { JsonParser parser = new JsonParser(); JsonObject jsonResponse = null; Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getUrl(deploymentUrl, xml); WebResource webResource = jerseyClient.resource(url); ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, configurationParams); jsonResponse = parser.parse(clientResponse.getEntity(String.class)).getAsJsonObject(); return jsonResponse; } public JsonObject getConfiguration(String deploymentUrl, String adminUsername, String adminAuthToken, String extensionName) { return getConfiguration(deploymentUrl, adminUsername, adminAuthToken, extensionName, false); } public JsonObject getConfiguration(String deploymentUrl, String adminUsername, String adminAuthToken, String extensionName, Boolean xml) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); WebResource webResource = jerseyClient.resource(getUrl(deploymentUrl, xml)); String response = webResource.path(extensionName).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); return jsonResponse; } public JsonObject updateConfiguration(String deploymentUrl, String adminUsername, String adminAuthToken, String extensionSid, MultivaluedMap<String, String> configurationParams) { return updateConfiguration(deploymentUrl, adminUsername, adminAuthToken, extensionSid, configurationParams, false); } public JsonObject updateConfiguration(String deploymentUrl, String adminUsername, String adminAuthToken, String extensionSid, MultivaluedMap<String, String> configurationParams, Boolean xml) { JsonParser parser = new JsonParser(); JsonObject jsonResponse = null; Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getUrl(deploymentUrl, xml) + "/" + extensionSid; WebResource webResource = jerseyClient.resource(url); ClientResponse clientResponse = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, configurationParams); jsonResponse = parser.parse(clientResponse.getEntity(String.class)).getAsJsonObject(); return jsonResponse; } }
4,550
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CreateGatewaysTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/CreateGatewaysTool.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ public class CreateGatewaysTool { private static CreateGatewaysTool instance; private CreateGatewaysTool() { } public static CreateGatewaysTool getInstance() { if (instance == null) { instance = new CreateGatewaysTool(); } return instance; } private String getEndpoint(String deploymentUrl) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } return deploymentUrl; } public JsonObject createGateway(String deploymentUrl, String friendlyName, String username, String password, String proxy, String register, String ttl) { String endpoint = getEndpoint(deploymentUrl).replaceAll("http://", ""); String restcommUsername = "ACae6e420f425248d6a26948c17a9e2acf"; String restcommPassword = "77f8c12cc7b8f8423e5c38b035249166"; String url = "http://" + restcommUsername + ":" + restcommPassword + "@" + endpoint + "/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Management/Gateways.json"; Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(restcommUsername, restcommPassword)); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("FriendlyName", friendlyName); params.add("UserName", username); params.add("Password", password); params.add("Proxy", proxy); params.add("Register", register); params.add("TTL", ttl); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject updateGateway(String deploymentUrl, String sid, String friendlyName, String username, String password, String proxy, String register, String ttl) { String endpoint = getEndpoint(deploymentUrl).replaceAll("http://", ""); String restcommUsername = "ACae6e420f425248d6a26948c17a9e2acf"; String restcommPassword = "77f8c12cc7b8f8423e5c38b035249166"; String url = "http://" + restcommUsername + ":" + restcommPassword + "@" + endpoint + "/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Management/Gateways/" + sid + ".json"; Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(restcommUsername, restcommPassword)); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (friendlyName != null) { params.add("FriendlyName", friendlyName); } if (username != null) { params.add("UserName", username); } if (password != null) { params.add("Password", password); } if (proxy != null) { params.add("Proxy", proxy); } if (register != null) { params.add("Register", register); } if (ttl != null) { params.add("TTL", ttl); } String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public void deleteGateway(String deploymentUrl, String sid) { String endpoint = getEndpoint(deploymentUrl).replaceAll("http://", ""); String restcommUsername = "ACae6e420f425248d6a26948c17a9e2acf"; String restcommPassword = "77f8c12cc7b8f8423e5c38b035249166"; String url = "http://" + restcommUsername + ":" + restcommPassword + "@" + endpoint + "/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/Management/Gateways/" + sid + ".json"; Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(restcommUsername, restcommPassword)); WebResource webResource = jerseyClient.resource(url); webResource.accept(MediaType.APPLICATION_JSON).delete(); } }
4,778
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommGeolocationsTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommGeolocationsTool.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.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import java.io.IOException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; /** * @author <a href="mailto:[email protected]"> Fernando Mendioroz * </a> * */ public class RestcommGeolocationsTool { private static RestcommGeolocationsTool instance; private static String geolocationsUrl; private static final Logger logger = Logger.getLogger(RestcommGeolocationsTool.class); private static final String apiVersionAccounts = "/2012-04-24/Accounts/"; public static RestcommGeolocationsTool getInstance() { if (instance == null) { instance = new RestcommGeolocationsTool(); } return instance; } private String getGeolocationsUrl(String deploymentUrl, String accountSid, Boolean xml) { deploymentUrl = evaluateDeploymentUrl(deploymentUrl); geolocationsUrl = deploymentUrl + apiVersionAccounts + accountSid + "/Geolocation"; if (!xml) { geolocationsUrl += ".json"; } return geolocationsUrl; } private String getImmediateGeolocationsUrl(String deploymentUrl, String accountSid, Boolean xml) { deploymentUrl = evaluateDeploymentUrl(deploymentUrl); geolocationsUrl = deploymentUrl + apiVersionAccounts + accountSid + "/Geolocation/Immediate"; if (!xml) { geolocationsUrl += ".json"; } return geolocationsUrl; } private String getNotificationGeolocationsUrl(String deploymentUrl, String accountSid, Boolean xml) { deploymentUrl = evaluateDeploymentUrl(deploymentUrl); geolocationsUrl = deploymentUrl + apiVersionAccounts + accountSid + "/Geolocation/Notification"; if (!xml) { geolocationsUrl += ".json"; } return geolocationsUrl; } private String getImmediateGeolocationUrl(String deploymentUrl, String accountSid, String geolocationSid, Boolean xml) { deploymentUrl = evaluateDeploymentUrl(deploymentUrl); geolocationsUrl = deploymentUrl + apiVersionAccounts + accountSid + "/Geolocation/Immediate/" + geolocationSid; if (!xml) { geolocationsUrl += ".json"; } return geolocationsUrl; } private String getNotificationGeolocationUrl(String deploymentUrl, String accountSid, String geolocationSid, Boolean xml) { deploymentUrl = evaluateDeploymentUrl(deploymentUrl); geolocationsUrl = deploymentUrl + apiVersionAccounts + accountSid + "/Geolocation/Notification/" + geolocationSid; if (!xml) { geolocationsUrl += ".json"; } return geolocationsUrl; } private String getEndpoint(String deploymentUrl) { deploymentUrl = evaluateDeploymentUrl(deploymentUrl); return deploymentUrl; } public JsonObject createImmediateGeolocation(String deploymentUrl, String adminAccountSid, String adminUsername, String adminAuthToken, MultivaluedMap<String, String> geolocationParams) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getImmediateGeolocationsUrl(deploymentUrl, adminAccountSid, false); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, geolocationParams); JsonParser parser = new JsonParser(); JsonObject jsonObject = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonObject()) { jsonObject = jsonElement.getAsJsonObject(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonObject; } public JsonObject createNotificationGeolocation(String deploymentUrl, String adminAccountSid, String adminUsername, String adminAuthToken, MultivaluedMap<String, String> geolocationParams) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getNotificationGeolocationsUrl(deploymentUrl, adminAccountSid, false); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, geolocationParams); JsonParser parser = new JsonParser(); JsonObject jsonObject = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonObject()) { jsonObject = jsonElement.getAsJsonObject(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonObject; } public JsonObject getImmediateGeolocation(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String geolocationSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getImmediateGeolocationUrl(deploymentUrl, adminAccountSid, geolocationSid, false); WebResource webResource = jerseyClient.resource(url); String response = null; JsonObject jsonResponse = null; try { response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); } catch (Exception e) { logger.info(e.getMessage()); } return jsonResponse; } public JsonObject getNotificationGeolocation(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String geolocationSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getNotificationGeolocationUrl(deploymentUrl, adminAccountSid, geolocationSid, false); WebResource webResource = jerseyClient.resource(url); String response = null; JsonObject jsonResponse = null; try { response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); jsonResponse = parser.parse(response).getAsJsonObject(); } catch (Exception e) { logger.info(e.getMessage()); } return jsonResponse; } public JsonArray getGeolocations(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getGeolocationsUrl(deploymentUrl, adminAccountSid, false); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonArray jsonResponse = parser.parse(response).getAsJsonArray(); return jsonResponse; } public JsonObject updateImmediateGeolocation(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String geolocationSid, MultivaluedMap<String, String> geolocationParams, boolean usePut) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getImmediateGeolocationUrl(deploymentUrl, adminAccountSid, geolocationSid, false); WebResource webResource = jerseyClient.resource(url); String response = ""; if (usePut) { response = webResource.accept(MediaType.APPLICATION_JSON).put(String.class, geolocationParams); } else { response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, geolocationParams); } JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); return jsonResponse; } public JsonObject updateNotificationGeolocation(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String geolocationSid, MultivaluedMap<String, String> geolocationParams, boolean usePut) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getNotificationGeolocationUrl(deploymentUrl, adminAccountSid, geolocationSid, false); WebResource webResource = jerseyClient.resource(url); String response = ""; if (usePut) { response = webResource.accept(MediaType.APPLICATION_JSON).put(String.class, geolocationParams); } else { response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, geolocationParams); } JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); return jsonResponse; } public void deleteImmediateGeolocation(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String geolocationSid) throws IOException { String endpoint = getEndpoint(deploymentUrl).replaceAll("http://", ""); String url = getImmediateGeolocationUrl("http://" + adminAccountSid + ":" + adminAuthToken + "@" + endpoint, adminAccountSid, geolocationSid, false); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminAccountSid, adminAuthToken)); WebResource webResource = jerseyClient.resource(url); webResource.accept(MediaType.APPLICATION_JSON).delete(); } public void deleteNotificationGeolocation(String deploymentUrl, String adminUsername, String adminAuthToken, String adminAccountSid, String geolocationSid) throws IOException { String endpoint = getEndpoint(deploymentUrl).replaceAll("http://", ""); String url = getNotificationGeolocationUrl("http://" + adminAccountSid + ":" + adminAuthToken + "@" + endpoint, adminAccountSid, geolocationSid, false); Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminAccountSid, adminAuthToken)); WebResource webResource = jerseyClient.resource(url); webResource.accept(MediaType.APPLICATION_JSON).delete(); } private String evaluateDeploymentUrl(String deploymentUrl) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } return deploymentUrl; } }
12,604
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommConferenceTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommConferenceTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.thoughtworks.xstream.XStream; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; import org.restcomm.connect.dao.entities.ConferenceDetailRecordList; /** * @author Maria */ public class RestcommConferenceTool { private static RestcommConferenceTool instance; private static String accountsUrl; private static Logger logger = Logger.getLogger(RestcommConferenceTool.class); private RestcommConferenceTool() { } public static RestcommConferenceTool getInstance() { if (instance == null) { instance = new RestcommConferenceTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username, Boolean json) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Conferences" + ((json) ? ".json" : ""); return accountsUrl; } public JsonObject getConferences(String deploymentUrl, String username, String authToken) { return (JsonObject) getConferences(deploymentUrl, username, authToken, null, null, true); } public JsonObject getConferences(String deploymentUrl, String username, String authToken, Integer page, Integer pageSize, Boolean json) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, json); WebResource webResource = jerseyClient.resource(url); String response = null; if (page != null || pageSize != null) { MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (page != null) { params.add("Page", String.valueOf(page)); } if (pageSize != null) { params.add("PageSize", String.valueOf(pageSize)); } response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); if (json) { JsonObject jsonObject = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonObject()) { jsonObject = jsonElement.getAsJsonObject(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonObject; } else { XStream xstream = new XStream(); xstream.alias("cdrlist", ConferenceDetailRecordList.class); JsonObject jsonObject = parser.parse(xstream.toXML(response)).getAsJsonObject(); return jsonObject; } } public JsonObject getConference(String deploymentUrl, String username, String authToken, String sid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, false); WebResource webResource = jerseyClient.resource(url); String response = null; webResource = webResource.path(String.valueOf(sid) + ".json"); logger.info("The URI to sent: " + webResource.getURI()); response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getConferencesUsingFilter(String deploymentUrl, String username, String authToken, Map<String, String> filters) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public int getConferencesSize(String deploymentUrl, String accountSid, String adminAuthToken) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), accountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); return conferenceArray.size(); } public int getParticipantsSize(String deploymentUrl, String accountSid, String adminAuthToken, final String name) { JsonObject conferences = RestcommConferenceTool.getInstance().getConferences(deploymentUrl.toString(), accountSid, adminAuthToken); JsonArray conferenceArray = conferences.getAsJsonArray("conferences"); String confSid = null; for (int i = 0; i < conferenceArray.size(); i++) { JsonObject confObj = conferenceArray.get(i).getAsJsonObject(); String confName = confObj.get("friendly_name").getAsString(); if (confName.equalsIgnoreCase(name)) { confSid = confObj.get("sid").getAsString(); break; } } JsonObject participants = RestcommConferenceParticipantsTool.getInstance().getParticipants(deploymentUrl.toString(), accountSid, adminAuthToken, confSid); JsonArray participantsArray = participants.getAsJsonArray("calls"); return participantsArray.size(); } }
7,664
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommAccountsTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommAccountsTool.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import java.net.URI; import java.util.logging.Logger; /** * @author <a href="mailto:[email protected]">gvagenas</a> * @author <a href="mailto:[email protected]">Thinh Ly</a> */ public class RestcommAccountsTool { private static Logger logger = Logger.getLogger(RestcommAccountsTool.class.getName()); private static RestcommAccountsTool instance; private static String accountsUrl; private RestcommAccountsTool() { } public static RestcommAccountsTool getInstance() { if (instance == null) { instance = new RestcommAccountsTool(); } return instance; } private String getAccountsUrl(String deploymentUrl) { return getAccountsUrl(deploymentUrl, false); } private String getAccountsUrl(String deploymentUrl, Boolean xml) { // if (accountsUrl == null) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } if (xml) { accountsUrl = deploymentUrl + "/2012-04-24/Accounts"; } else { accountsUrl = deploymentUrl + "/2012-04-24/Accounts.json"; } // } return accountsUrl; } public void removeAccount(String deploymentUrl, String adminUsername, String adminAuthToken, String accountSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getAccountsUrl(deploymentUrl, true) + "/" + accountSid; WebResource webResource = jerseyClient.resource(url); webResource.accept(MediaType.APPLICATION_JSON).delete(); } public JsonObject updateAccount(String deploymentUrl, String adminUsername, String adminAuthToken, String accountSid, String friendlyName, String password, String authToken, String role, String status) { JsonParser parser = new JsonParser(); JsonObject jsonResponse = null; try { ClientResponse clientResponse = updateAccountResponse(deploymentUrl, adminUsername, adminAuthToken, accountSid, friendlyName, password, authToken, role, status); jsonResponse = parser.parse(clientResponse.getEntity(String.class)).getAsJsonObject(); } catch (Exception e) { logger.info("Exception: " + e); } return jsonResponse; } public ClientResponse updateAccountResponse(String deploymentUrl, String adminUsername, String adminAuthToken, String accountSid, String friendlyName, String password, String authToken, String role, String status) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getAccountsUrl(deploymentUrl, false) + "/" + accountSid; WebResource webResource = jerseyClient.resource(url); // FriendlyName, status, password and auth_token are currently updated in AccountsEndpoint. Role remains to be added MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (friendlyName != null) { params.add("FriendlyName", friendlyName); } if (password != null) { params.add("Password", password); } if (authToken != null) { params.add("Auth_Token", authToken); } if (role != null) { params.add("Role", role); } if (status != null) { params.add("Status", status); } ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); return response; } public JsonObject migrateAccount(String deploymentUrl, String adminUsername, String adminAuthToken, String accountSid, String newOrganizationSid) { JsonParser parser = new JsonParser(); JsonObject jsonResponse = null; Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); String url = getAccountsUrl(deploymentUrl, false) + "/migrate/" + accountSid; WebResource webResource = jerseyClient.resource(url); // FriendlyName, status, password and auth_token are currently updated in AccountsEndpoint. Role remains to be added MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (newOrganizationSid != null) { params.add("Organization", newOrganizationSid); } ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); if (response.getStatus() == 200) { jsonResponse = parser.parse(response.getEntity(String.class)).getAsJsonObject(); } return jsonResponse; } public JsonObject createAccount(String deploymentUrl, String adminUsername, String adminAuthToken, String emailAddress, String password) { return createAccount(deploymentUrl, adminUsername, adminAuthToken, emailAddress, password, null); } public JsonObject createAccount(String deploymentUrl, String adminUsername, String adminAuthToken, String emailAddress, String password, String friendlyName) { JsonParser parser = new JsonParser(); JsonObject jsonResponse = null; try { ClientResponse clientResponse = createAccountResponse(deploymentUrl, adminUsername, adminAuthToken, emailAddress, password, friendlyName, null); jsonResponse = parser.parse(clientResponse.getEntity(String.class)).getAsJsonObject(); } catch (Exception e) { logger.info("Exception: " + e); } return jsonResponse; } public ClientResponse createAccountResponse(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String emailAddress, String password) { return createAccountResponse(deploymentUrl, operatorUsername, operatorAuthtoken, emailAddress, password, null, null); } public ClientResponse createAccountResponse(String deploymentUrl, String operatorUsername, String operatorAuthtoken, String emailAddress, String password, String friendlyName, String organizationSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(operatorUsername, operatorAuthtoken)); String url = getAccountsUrl(deploymentUrl); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("EmailAddress", emailAddress); params.add("Password", password); params.add("Role", "Administartor"); if (friendlyName != null) { params.add("FriendlyName", friendlyName); } if (organizationSid != null) { params.add("OrganizationSid", organizationSid); } ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).post(ClientResponse.class, params); return response; } public JsonObject getAccount(String deploymentUrl, String adminUsername, String adminAuthToken, String username) throws UniformInterfaceException { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(adminUsername, adminAuthToken)); WebResource webResource = jerseyClient.resource(URI.create(getAccountsUrl(deploymentUrl))); String response = webResource.path(username).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonResponse = parser.parse(response).getAsJsonObject(); return jsonResponse; } /** * * @param deploymentUrl * @param username * @param authtoken * @param accountSid * @return an account response so that the invoker can make decisions on the * status code etc. */ public ClientResponse getAccountResponse(String deploymentUrl, String username, String authtoken, String accountSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authtoken)); WebResource webResource = jerseyClient.resource(getAccountsUrl(deploymentUrl)); ClientResponse response = webResource.path(accountSid).get(ClientResponse.class); return response; } public ClientResponse getAccountsResponse(String deploymentUrl, String username, String authtoken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authtoken)); WebResource webResource = jerseyClient.resource(getAccountsUrl(deploymentUrl)); ClientResponse response = webResource.get(ClientResponse.class); return response; } public ClientResponse removeAccountResponse(String deploymentUrl, String operatingUsername, String operatingAuthToken, String removedAccountSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(operatingUsername, operatingAuthToken)); WebResource webResource = jerseyClient.resource(getAccountsUrl(deploymentUrl)); ClientResponse response = webResource.path(removedAccountSid).delete(ClientResponse.class); return response; } /** * @param deploymentUrl * @param username * @param authtoken * @param organizationSid * @param domainName * @return */ public ClientResponse getAccountsWithFilterClientResponse(String deploymentUrl, String username, String authtoken, String organizationSid, String domainName) { WebResource webResource = prepareAccountListWebResource(deploymentUrl, username, authtoken); ClientResponse response = webResource.queryParams(prepareAccountListFilter(organizationSid, domainName)) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(ClientResponse.class); return response; } /** * @param deploymentUrl * @param username * @param authtoken * @param organizationSid * @param domainName * @return JsonArray */ public JsonArray getAccountsWithFilterResponse(String deploymentUrl, String username, String authtoken, String organizationSid, String domainName) { WebResource webResource = prepareAccountListWebResource(deploymentUrl, username, authtoken); String response = webResource.queryParams(prepareAccountListFilter(organizationSid, domainName)) .accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); JsonElement jsonElement = new JsonParser().parse(response); return jsonElement.getAsJsonArray(); } /** * @param deploymentUrl * @param username * @param authtoken * @return */ private WebResource prepareAccountListWebResource(String deploymentUrl, String username, String authtoken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authtoken)); WebResource webResource = jerseyClient.resource(getAccountsUrl(deploymentUrl)); return webResource; } /** * @param organizationSid * @param domainName * @return */ private MultivaluedMap<String, String> prepareAccountListFilter(String organizationSid, String domainName) { MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (organizationSid != null && !(organizationSid.trim().isEmpty())) { params.add("OrganizationSid", organizationSid); } if (domainName != null && !(domainName.trim().isEmpty())) { params.add("DomainName", domainName); } return params; } }
12,439
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
TranscriptionEndpointTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/TranscriptionEndpointTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * @author <a href="mailto:[email protected]">vunguyen</a> * */ public class TranscriptionEndpointTool { private static TranscriptionEndpointTool instance; private static String accountsUrl; private TranscriptionEndpointTool() { } public static TranscriptionEndpointTool getInstance() { if (instance == null) { instance = new TranscriptionEndpointTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username, Boolean json) { if (accountsUrl == null) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Transcriptions" + ((json) ? ".json" : ""); } return accountsUrl; } public JsonObject getTranscriptionList(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getTranscriptionList(String deploymentUrl, String username, String authToken, Integer page, Integer pageSize, Boolean json) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response; if (page != null || pageSize != null) { MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (page != null) { params.add("Page", String.valueOf(page)); } if (pageSize != null) { params.add("PageSize", String.valueOf(pageSize)); } response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getTranscriptionListUsingFilter(String deploymentUrl, String username, String authToken, Map<String, String> filters) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } }
4,898
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommUsageRecordsTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommUsageRecordsTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2015, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.commons.collections.map.HashedMap; import org.apache.log4j.Logger; /** * @author <a href="mailto:[email protected]">abdulazizali77</a> */ public class RestcommUsageRecordsTool { private static RestcommUsageRecordsTool instance; private static String accountsUrl; private static Logger logger = Logger.getLogger(RestcommUsageRecordsTool.class); private RestcommUsageRecordsTool() { } public static RestcommUsageRecordsTool getInstance() { if (instance == null) { instance = new RestcommUsageRecordsTool(); } return instance; } public JsonElement getUsageRecordsDaily(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "Daily", categoryStr, "", "", null, null, json); } public JsonElement getUsageRecordsMonthly(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "Monthly", categoryStr, "", "", null, null, json).getAsJsonArray(); } public JsonElement getUsageRecordsYearly(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "Yearly", categoryStr, "", "", null, null, json); } public JsonElement getUsageRecordsAllTime(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "AllTime", categoryStr, "", "", null, null, json); } public JsonElement getUsageRecordsToday(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "Today", categoryStr, "", "", null, null, json); } public JsonElement getUsageRecordsYesterday(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "Yesterday", categoryStr, "", "", null, null, json); } public JsonElement getUsageRecordsThisMonth(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "ThisMonth", categoryStr, "", "", null, null, json); } public JsonElement getUsageRecordsLastMonth(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "LastMonth", categoryStr, "", "", null, null, json); } public JsonElement getUsageRecordsWeekly(String deploymentUrl, String username, String authToken, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, "Weekly", categoryStr, "", "", null, null, json); } public JsonElement getUsageRecords(String deploymentUrl, String username, String authToken, String subresource, String categoryStr, Boolean json) { return getUsageRecords(deploymentUrl, username, authToken, subresource, categoryStr, "", "", null, null, json); } private String getUsageRecordsUrl(String deploymentUrl, String username, String subresource, Boolean json) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } if (!subresource.isEmpty()) { subresource = "/" + subresource; } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Usage/Records" + subresource + ((json) ? ".json" : ""); return accountsUrl; } public JsonElement getUsageRecords(String deploymentUrl, String username, String authToken, String subresource, String categoryStr, String startDate, String endDate, Integer page, Integer pageSize, Boolean json) { Map<String, String> map = new HashedMap(); if (!categoryStr.isEmpty()) { map.put("Category", categoryStr); } if (!startDate.isEmpty()) { map.put("StartDate", startDate); } if (!endDate.isEmpty()) { map.put("EndDate", endDate); } if (page != null) { map.put("Page", String.valueOf(page)); } if (pageSize != null) { map.put("PageSize", String.valueOf(pageSize)); } return getUsageRecordsUsingFilter(deploymentUrl, username, authToken, subresource, map, json); } public JsonElement getUsageRecordsUsingFilter(String deploymentUrl, String username, String authToken, String subresource, Map<String, String> filters, Boolean json) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getUsageRecordsUrl(deploymentUrl, username, subresource, json); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } if (!params.isEmpty()) { webResource = webResource.queryParams(params); } String response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); JsonParser parser = new JsonParser(); JsonElement jsonElement = null; if (json) { try { jsonElement = parser.parse(response); } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } } else { //TODO: return XML and cast as Json } return jsonElement; } }
7,309
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommUssdPushTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RestcommUssdPushTool.java
package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * @author <a href="mailto:[email protected]">gvagenas</a> */ public class RestcommUssdPushTool { private static RestcommUssdPushTool instance; private static String accountsUrl; private RestcommUssdPushTool() { } public static RestcommUssdPushTool getInstance() { if (instance == null) { instance = new RestcommUssdPushTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username) { if (accountsUrl == null) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/UssdPush.json"; } return accountsUrl; } public JsonObject createUssdPush(String deploymentUrl, String username, String authToken, String from, String to, String rcmlUrl) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("From", from); params.add("To", to); params.add("Url", rcmlUrl); // webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).post(String.class, params); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } }
2,095
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RecordingEndpointTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/RecordingEndpointTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.http; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; /** * @author <a href="mailto:[email protected]">vunguyen</a> * */ public class RecordingEndpointTool { private static RecordingEndpointTool instance; private static String accountsUrl; private RecordingEndpointTool() { } public static RecordingEndpointTool getInstance() { if (instance == null) { instance = new RecordingEndpointTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username, Boolean json) { if (accountsUrl == null) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/Recordings" + ((json) ? ".json" : ""); } return accountsUrl; } public JsonObject getRecordingList(String deploymentUrl, String username, String authToken) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getRecordingList(String deploymentUrl, String username, String authToken, Integer page, Integer pageSize, String sortingParameters, Boolean json) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); String response; MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (sortingParameters != null) { params.add("SortBy", sortingParameters); } if (page != null || pageSize != null) { if (page != null) { params.add("Page", String.valueOf(page)); } if (pageSize != null) { params.add("PageSize", String.valueOf(pageSize)); } } if (!params.isEmpty()) { response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public JsonObject getRecordingListUsingFilter(String deploymentUrl, String username, String authToken, Map<String, String> filters) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } webResource = webResource.queryParams(params); String response = webResource.accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = parser.parse(response).getAsJsonObject(); return jsonObject; } public void deleteRecording(String deploymentUrl, String username, String authToken, String recordingSid) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); webResource = webResource.path(recordingSid); webResource.accept(MediaType.APPLICATION_JSON).delete(); } }
5,527
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpLink.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/util/HttpLink.java
package org.restcomm.connect.testsuite.http.util; import java.net.URI; import org.apache.http.client.methods.HttpRequestBase; public class HttpLink extends HttpRequestBase { public static final String METHOD_NAME = "LINK"; public HttpLink() { super(); } public HttpLink(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpLink(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
620
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
CustomDnsResolver.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/util/CustomDnsResolver.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.testsuite.http.util; import org.apache.log4j.Logger; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; import java.util.Map; /** * @author [email protected] */ public class CustomDnsResolver implements sun.net.spi.nameservice.NameService { //Based on https://stackoverflow.com/a/43870031 private static Logger logger = Logger.getLogger(CustomDnsResolver.class); private static final String LOCALHOST = "127.0.0.1"; private static Map<String, String> domainIpMap; @Override public InetAddress[] lookupAllHostAddr (String host) throws UnknownHostException { if (domainIpMap != null) { if (domainIpMap.containsKey(host)) { final byte[] arrayOfByte = sun.net.util.IPAddressUtil.textToNumericFormatV4(domainIpMap.get(host)); final InetAddress address = InetAddress.getByAddress(host, arrayOfByte); return new InetAddress[]{address}; } else { throw new UnknownHostException(); } } else { final byte[] arrayOfByte = sun.net.util.IPAddressUtil.textToNumericFormatV4(LOCALHOST); final InetAddress address = InetAddress.getByAddress(host, arrayOfByte); return new InetAddress[]{address}; } } @Override public String getHostByAddr (byte[] bytes) throws UnknownHostException { throw new UnknownHostException(); } public static void setNameService (Map<String, String> domainIpMapProvided) { try { List<sun.net.spi.nameservice.NameService> nameServices = (List<sun.net.spi.nameservice.NameService>) org.apache.commons.lang3.reflect.FieldUtils.readStaticField(InetAddress.class, "nameServices", true); if (domainIpMap != null) { domainIpMap = domainIpMapProvided; } nameServices.add(new CustomDnsResolver()); } catch (IllegalAccessException e) { logger.error("Error during setNameService: ",e); } } }
2,956
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
HttpUnLink.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/http/util/HttpUnLink.java
package org.restcomm.connect.testsuite.http.util; import java.net.URI; import org.apache.http.client.methods.HttpRequestBase; public class HttpUnLink extends HttpRequestBase { public static final String METHOD_NAME = "UNLINK"; public HttpUnLink() { super(); } public HttpUnLink(final URI uri) { super(); setURI(uri); } /** * @throws IllegalArgumentException if the uri is invalid. */ public HttpUnLink(final String uri) { super(); setURI(URI.create(uri)); } @Override public String getMethod() { return METHOD_NAME; } }
630
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
MockSmppServer.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/smpp/MockSmppServer.java
package org.restcomm.connect.testsuite.smpp; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.Logger; import org.restcomm.connect.sms.smpp.SmppInboundMessageEntity; import com.cloudhopper.commons.charset.Charset; import com.cloudhopper.commons.charset.CharsetUtil; import com.cloudhopper.commons.util.windowing.WindowFuture; import com.cloudhopper.smpp.SmppConstants; import com.cloudhopper.smpp.SmppServerConfiguration; import com.cloudhopper.smpp.SmppServerHandler; import com.cloudhopper.smpp.SmppServerSession; import com.cloudhopper.smpp.SmppSession; import com.cloudhopper.smpp.SmppSessionConfiguration; import com.cloudhopper.smpp.impl.DefaultSmppServer; import com.cloudhopper.smpp.impl.DefaultSmppSessionHandler; import com.cloudhopper.smpp.pdu.BaseBind; import com.cloudhopper.smpp.pdu.BaseBindResp; import com.cloudhopper.smpp.pdu.DeliverSm; import com.cloudhopper.smpp.pdu.DeliverSmResp; import com.cloudhopper.smpp.pdu.PduRequest; import com.cloudhopper.smpp.pdu.PduResponse; import com.cloudhopper.smpp.pdu.SubmitSm; import com.cloudhopper.smpp.pdu.SubmitSmResp; import com.cloudhopper.smpp.type.Address; import com.cloudhopper.smpp.type.SmppChannelException; import com.cloudhopper.smpp.type.SmppInvalidArgumentException; import com.cloudhopper.smpp.type.SmppProcessingException; public class MockSmppServer { private static final Logger logger = Logger.getLogger(MockSmppServer.class); public static enum SmppDeliveryStatus { ACCEPTD, EXPIRED, DELETED, UNDELIV, REJECTD, DELIVRD, UNKNOWN } private final DefaultSmppServer smppServer; private static SmppServerSession smppServerSession; private static boolean linkEstablished = false; private static boolean messageSent = false; private static SmppInboundMessageEntity smppInboundMessageEntity; private static boolean messageReceived; private static String smppMessageId; private static boolean sendFailureOnSubmitSmResponse; private String getDlrMessage(final String smppMessageId, final SmppDeliveryStatus smppStatus){ String dlrFormat = "id:%s sub:001 dlvrd:001 submit date:1805170144 done date:1805170144 stat:%s err:000 text:none"; return String.format(dlrFormat, smppMessageId, smppStatus); } public MockSmppServer() throws SmppChannelException { this(2776); } public MockSmppServer(int port) throws SmppChannelException { ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool(); ScheduledThreadPoolExecutor monitorExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(1, new ThreadFactory() { private AtomicInteger sequence = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("SmppServerSessionWindowMonitorPool-" + sequence.getAndIncrement()); return t; } }); // create a server configuration SmppServerConfiguration configuration = new SmppServerConfiguration(); configuration.setHost("127.0.0.1"); configuration.setPort(port); configuration.setMaxConnectionSize(10); configuration.setNonBlockingSocketsEnabled(true); configuration.setDefaultRequestExpiryTimeout(30000); configuration.setDefaultWindowMonitorInterval(15000); configuration.setDefaultWindowSize(5); configuration.setDefaultWindowWaitTimeout(configuration.getDefaultRequestExpiryTimeout()); configuration.setDefaultSessionCountersEnabled(true); configuration.setJmxEnabled(true); // create a server, start it up smppServer = new DefaultSmppServer(configuration, new DefaultSmppServerHandler(), executor, monitorExecutor); smppServer.start(); logger.info("SMPP server started! Server counters: {} " + smppServer.getCounters()); } public void sendSmppMessageToRestcomm(String smppMessage, String smppTo, String smppFrom, Charset charset) throws IOException, SmppInvalidArgumentException { //http://stackoverflow.com/a/25885741 try { byte[] textBytes; textBytes = CharsetUtil.encode(smppMessage, charset); DeliverSm deliver = new DeliverSm(); deliver.setSourceAddress(new Address((byte) 0x03, (byte) 0x00, smppFrom)); deliver.setDestAddress(new Address((byte) 0x01, (byte) 0x01, smppTo)); deliver.setShortMessage(textBytes); if (CharsetUtil.CHARSET_UCS_2 == charset) { deliver.setDataCoding(SmppConstants.DATA_CODING_UCS2); } else { deliver.setDataCoding(SmppConstants.DATA_CODING_DEFAULT); } logger.info("deliver.getDataCoding: " + deliver.getDataCoding()); WindowFuture<Integer, PduRequest, PduResponse> future = smppServerSession.sendRequestPdu(deliver, 10000, false); if (!future.await()) { logger.error("Failed to receive deliver_sm_resp within specified time"); } else if (future.isSuccess()) { DeliverSmResp deliverSmResp = (DeliverSmResp) future.getResponse(); messageSent = true; logger.info("deliver_sm_resp: commandStatus [" + deliverSmResp.getCommandStatus() + "=" + deliverSmResp.getResultMessage() + "]"); } else { logger.error("Failed to properly receive deliver_sm_resp: " + future.getCause()); } } catch (Exception e) { logger.fatal("Exception during sending SMPP message to Restcomm: " + e); } } /** * @param smppMessageId * @param smppStatus * @throws IOException * @throws SmppInvalidArgumentException */ public void sendSmppDeliveryMessageToRestcomm(String smppMessageId, SmppDeliveryStatus smppStatus) throws IOException, SmppInvalidArgumentException { try { byte[] textBytes = getDlrMessage(smppMessageId, smppStatus).getBytes(); DeliverSm deliver = new DeliverSm(); deliver.setShortMessage(textBytes); deliver.setEsmClass((byte)0x04); deliver.setCommandStatus(001); deliver.setDataCoding(SmppConstants.DATA_CODING_DEFAULT); WindowFuture<Integer, PduRequest, PduResponse> future = smppServerSession.sendRequestPdu(deliver, 10000, false); if (!future.await()) { logger.error("Failed to receive deliver_sm_resp within specified time"); } else if (future.isSuccess()) { DeliverSmResp deliverSmResp = (DeliverSmResp) future.getResponse(); messageSent = true; logger.info("deliver_sm_resp: commandStatus [" + deliverSmResp.getCommandStatus() + "=" + deliverSmResp.getResultMessage() + "]"); } else { logger.error("Failed to properly receive deliver_sm_resp: " + future.getCause()); } } catch (Exception e) { logger.fatal("Exception during sending SMPP message to Restcomm: " + e); logger.error("",e); } } public void stop() { if (smppServerSession != null) { smppServerSession.close(); smppServerSession.destroy(); } } public void cleanup() { this.messageSent = false; this.messageReceived = false; this.smppInboundMessageEntity = null; } public static boolean isLinkEstablished() { return linkEstablished; } public static boolean isMessageSent() { return messageSent; } public static SmppInboundMessageEntity getSmppInboundMessageEntity() { return smppInboundMessageEntity; } public static boolean isMessageReceived() { return messageReceived; } public int getPort() { return smppServer.getConfiguration().getPort(); } public String getSmppMessageId(){ return smppMessageId; } public static boolean isSendFailureOnSubmitSmResponse() { return sendFailureOnSubmitSmResponse; } public static void setSendFailureOnSubmitSmResponse(boolean sendFailureOnSubmitSmResponse) { MockSmppServer.sendFailureOnSubmitSmResponse = sendFailureOnSubmitSmResponse; } private static class DefaultSmppServerHandler implements SmppServerHandler { @Override public void sessionBindRequested(Long sessionId, SmppSessionConfiguration sessionConfiguration, final BaseBind bindRequest) throws SmppProcessingException { // test name change of sessions // this name actually shows up as thread context.... sessionConfiguration.setName("Application.SMPP." + sessionConfiguration.getSystemId()); //throw new SmppProcessingException(SmppConstants.STATUS_BINDFAIL, null); } @Override public void sessionCreated(Long sessionId, SmppServerSession session, BaseBindResp preparedBindResponse) throws SmppProcessingException { logger.info("Session created: {} " + session); // need to do something it now (flag we're ready) session.serverReady(new TestSmppSessionHandler(session)); smppServerSession = session; if (smppServerSession.isClosed()) { logger.info("********Session Closed*******"); } else if (smppServerSession.isOpen()) { logger.info("********Session Open*******"); } else if (smppServerSession.isBinding()) { logger.info("********Session Binding*******"); smppServerSession = session; } else if (smppServerSession.isBound()) { logger.info("********Session Bound*******"); smppServerSession = session; linkEstablished = true; } } @Override public void sessionDestroyed(Long sessionId, SmppServerSession session) { logger.info("Session destroyed: {} " + session); // print out final stats if (session.hasCounters()) { logger.info(" final session rx-submitSM: {} " + session.getCounters().getRxSubmitSM()); } // make sure it's really shutdown session.destroy(); } } private static class TestSmppSessionHandler extends DefaultSmppSessionHandler { private WeakReference<SmppSession> sessionRef; public TestSmppSessionHandler(SmppSession session) { this.sessionRef = new WeakReference<SmppSession>(session); } @Override public PduResponse firePduRequestReceived(PduRequest pduRequest) { SmppSession session = sessionRef.get(); // mimic how long processing could take on a slower smsc //processing received SMPP message from Restcomm String decodedPduMessage = null; byte dcs = 0; String destSmppAddress = null; String sourceSmppAddress = null; boolean isDeliveryReceipt = false; //FIXME: make MockSmppServer configurable Charset charset = CharsetUtil.CHARSET_UTF_8; SubmitSm submitSm = null; if (pduRequest.toString().toLowerCase().contains("enquire_link")) { //logger.info("This is a response to the enquire_link, therefore, do NOTHING "); return pduRequest.createResponse(); } else { //smppOutBoundMessageReceivedByServer = true; logger.info("********Restcomm Message Received By SMPP Server*******"); try { submitSm = (SubmitSm) pduRequest; dcs = submitSm.getDataCoding(); if(dcs==SmppConstants.DATA_CODING_UCS2) { charset = CharsetUtil.CHARSET_UCS_2; } decodedPduMessage = CharsetUtil.decode(submitSm.getShortMessage(), charset); destSmppAddress = submitSm.getDestAddress().getAddress(); sourceSmppAddress = submitSm.getSourceAddress().getAddress(); if (submitSm.getRegisteredDelivery() == (byte) 0x01) { isDeliveryReceipt = true; } logger.info("getDataCoding: " + submitSm.getDataCoding()); //send received SMPP PDU message to restcomm } catch (Exception e) { logger.info("********DeliverSm Exception******* " + e); } smppInboundMessageEntity = new SmppInboundMessageEntity(destSmppAddress, sourceSmppAddress, decodedPduMessage, charset, isDeliveryReceipt); messageReceived = true; } SubmitSmResp response = submitSm.createResponse(); final String smppMessageIdLocal = System.currentTimeMillis()+""; response.setMessageId(smppMessageIdLocal); if(sendFailureOnSubmitSmResponse) { response.setCommandStatus(10);//just setting the status to one of error code: Source address invalid. } smppMessageId = smppMessageIdLocal; return response; } } }
13,598
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BandwidthAvailablePhoneNumbersEndpointTestUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/bandwidth/BandwidthAvailablePhoneNumbersEndpointTestUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.bandwidth; /** * Created by sbarstow on 10/7/14. */ public class BandwidthAvailablePhoneNumbersEndpointTestUtils { public static String areaCode201SearchResult = "<SearchResult><ResultCount>1</ResultCount><TelephoneNumberDetailList><TelephoneNumberDetail><City>JERSEY CITY</City><LATA>224</LATA><RateCenter>JERSEYCITY</RateCenter><State>NJ</State><FullNumber>2012001555</FullNumber></TelephoneNumberDetail></TelephoneNumberDetailList></SearchResult>"; public static String firstJSonResult201AreaCode = "{\"friendlyName\":\"+12012001555\",\"phoneNumber\":\"+12012001555\",\"LATA\":224,\"rateCenter\":\"JERSEYCITY\",\"region\":\"NJ\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"smsCapable\":true,\"mmsCapable\":false,\"faxCapable\":false,\"ussdCapable\":false}"; public static String emptySearchResult = "<SearchResult><ResultCount>0</ResultCount></SearchResult>"; public static String malformedSearchResult = "<SearchResult><SomeElement>Test</SomeElement"; public static String zipCode27601SearchResult = "<SearchResult><ResultCount>1</ResultCount><TelephoneNumberDetailList><TelephoneNumberDetail><City>RALEIGH</City><LATA>123</LATA><RateCenter>RALEIGH</RateCenter><State>NC</State><FullNumber>19195551212</FullNumber></TelephoneNumberDetail></TelephoneNumberDetailList></SearchResult>"; public static String firstJSONResult27601ZipCode = "{\"friendlyName\":\"+19195551212\",\"phoneNumber\":\"+19195551212\",\"lata\":123,\"rateCenter\":\"RALEIGH\",\"region\":\"NC\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"smsCapable\":true,\"mmsCapable\":false,\"faxCapable\":false,\"ussdCapable\":false}"; public static String areaCode205SearchResult = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><SearchResult><ResultCount>5</ResultCount><TelephoneNumberDetailList><TelephoneNumberDetail><City>CALERA</City><LATA>476</LATA><RateCenter>CALERA </RateCenter><State>AL</State><FullNumber>2053194418</FullNumber><Tier>0</Tier><VendorId>49</VendorId><VendorName>Bandwidth CLEC</VendorName></TelephoneNumberDetail><TelephoneNumberDetail><City>CALERA</City><LATA>476</LATA><RateCenter>CALERA </RateCenter><State>AL</State><FullNumber>2053194421</FullNumber><Tier>0</Tier><VendorId>49</VendorId><VendorName>Bandwidth CLEC</VendorName></TelephoneNumberDetail><TelephoneNumberDetail><City>CALERA</City><LATA>476</LATA><RateCenter>CALERA </RateCenter><State>AL</State><FullNumber>2053194437</FullNumber><Tier>0</Tier><VendorId>49</VendorId><VendorName>Bandwidth CLEC</VendorName></TelephoneNumberDetail><TelephoneNumberDetail><City>CALERA</City><LATA>476</LATA><RateCenter>CALERA </RateCenter><State>AL</State><FullNumber>2053194457</FullNumber><Tier>0</Tier><VendorId>49</VendorId><VendorName>Bandwidth CLEC</VendorName></TelephoneNumberDetail><TelephoneNumberDetail><City>CALERA</City><LATA>476</LATA><RateCenter>CALERA </RateCenter><State>AL</State><FullNumber>2053194459</FullNumber><Tier>0</Tier><VendorId>49</VendorId><VendorName>Bandwidth CLEC</VendorName></TelephoneNumberDetail></TelephoneNumberDetailList></SearchResult>"; public static String validTollFreeSearchResult = "<SearchResult><ResultCount>2</ResultCount><TelephoneNumberList><TelephoneNumber>8885551212</TelephoneNumber><TelephoneNumber>8885551213</TelephoneNumber></TelephoneNumberList></SearchResult>"; public static String validTollFreeJsonResult = "{\"friendlyName\":\"+18885551212\",\"phoneNumber\":\"+18885551212\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"smsCapable\":true,\"mmsCapable\":false,\"faxCapable\":false,\"ussdCapable\":false}"; public static String invalidTollFreeSearchResult = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><SearchResult><Error><Code>4004</Code><Description>TollFree wild character search must start with an 8</Description></Error></SearchResult>"; }
4,710
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
BandwidthIncomingPhoneNumbersEndpointTestUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/bandwidth/BandwidthIncomingPhoneNumbersEndpointTestUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.bandwidth; /** * Created by sbarstow on 10/14/14. */ public class BandwidthIncomingPhoneNumbersEndpointTestUtils { public static String validOrderResponseXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><OrderResponse><Order><Name>A New Order</Name><OrderCreateDate>2014-10-14T17:58:15.299Z</OrderCreateDate><BackOrderRequested>false</BackOrderRequested><id>someid</id><ExistingTelephoneNumberOrderType><TelephoneNumberList><TelephoneNumber>4156902867</TelephoneNumber></TelephoneNumberList></ExistingTelephoneNumberOrderType><PartialAllowed>false</PartialAllowed><SiteId>2858</SiteId></Order></OrderResponse>"; public static String jSonResultPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14156902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String validDisconnectOrderResponseXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><DisconnectTelephoneNumberOrderResponse><orderRequest><Name>Disconnect</Name><OrderCreateDate>2014-10-17T15:02:46.077Z</OrderCreateDate><id>disconnectId</id><DisconnectTelephoneNumberOrderType><TelephoneNumberList><TelephoneNumber>4156902867</TelephoneNumber></TelephoneNumberList><DisconnectMode>normal</DisconnectMode></DisconnectTelephoneNumberOrderType></orderRequest></DisconnectTelephoneNumberOrderResponse>"; public static String jSonResultDeletePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14156902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":null,\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static boolean match(String text, String pattern) { text = text.trim(); pattern = pattern.trim(); // Create the cards by splitting using a RegEx. If more speed // is desired, a simpler character based splitting can be done. String[] cards = pattern.split("\\*"); // Iterate over the cards. for (String card : cards) { int idx = text.indexOf(card); // Card not detected in the text. if (idx == -1) { return false; } // Move ahead, towards the right of the text. text = text.substring(idx + card.length()); } return true; } }
4,941
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NexmoIncomingPhoneNumbersEndpointTestUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/nexmo/NexmoIncomingPhoneNumbersEndpointTestUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.nexmo; /** * @author [email protected] * */ public class NexmoIncomingPhoneNumbersEndpointTestUtils { public static String purchaseNumberSuccessResponse = ""; public static String deleteNumberSuccessResponse = ""; public static String jSonResultPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14156902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultDeletePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+34911067000\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultUpdatePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+33911067000\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultUpdateSuccessPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+33911067000\",\"voice_url\":\"http://demo.telestax.com/docs/voice2.xml\",\"voice_method\":\"POST\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":\"http://demo.telestax.com/docs/sms2.xml\",\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultAccountAssociatedPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14216902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultAccountAssociatedPurchaseNumberResult = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My*Company Line\",\"phone_number\":\"+1*6902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice*.xml\",\"voice_method\":\"*\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":*,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static boolean match(String text, String pattern) { text = text.trim(); pattern = pattern.trim(); // Create the cards by splitting using a RegEx. If more speed // is desired, a simpler character based splitting can be done. String[] cards = pattern.split("\\*"); // Iterate over the cards. for (String card : cards) { int idx = text.indexOf(card); // Card not detected in the text. if (idx == -1) { return false; } // Move ahead, towards the right of the text. text = text.substring(idx + card.length()); } return true; } }
8,054
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
NexmoAvailablePhoneNumbersEndpointTestUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/nexmo/NexmoAvailablePhoneNumbersEndpointTestUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.nexmo; /** * @author [email protected] * */ public class NexmoAvailablePhoneNumbersEndpointTestUtils { public static final String body501AreaCode = "{\"count\":6,\"numbers\":[{\"country\":\"US\",\"msisdn\":\"15013036357\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"US\",\"msisdn\":\"15013036361\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"US\",\"msisdn\":\"15013036365\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"US\",\"msisdn\":\"15013036367\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"US\",\"msisdn\":\"15013036371\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"US\",\"msisdn\":\"15013036372\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]}]}"; public static final String bodyCA418AreaCode = "{\"count\":14,\"numbers\":[{\"country\":\"CA\",\"msisdn\":\"13658000418\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14387939418\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"16475594180\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"16475594181\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"16475594182\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"16475594183\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"16475594184\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"16475594185\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"16475594186\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"16475594187\",\"cost\":\"0.67\",\"type\":\"mobile-lvn\",\"features\":[\"VOICE\",\"SMS\"]}]}"; public static final String bodyCA450AreaCode = "{\"count\":41,\"numbers\":[{\"country\":\"CA\",\"msisdn\":\"14506001110\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001113\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001114\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001115\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001117\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001118\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001119\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001121\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001122\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]},{\"country\":\"CA\",\"msisdn\":\"14506001123\",\"cost\":\"0.67\",\"type\":\"landline\",\"features\":[\"VOICE\",\"SMS\"]}]}"; public static String jsonResponseES700 = "{\"count\":1,\"numbers\":[{\"country\":\"ES\",\"msisdn\":\"34911067000\",\"type\":\"landline\",\"features\":[\"SMS\"],\"cost\":\"0.50\"}]}"; public static String jsonResponseUSRange = "{\"count\":177,\"numbers\":[{\"country\":\"US\",\"msisdn\":\"15102694548\",\"type\":\"mobile-lvn\",\"features\":[\"SMS\",\"VOICE\"],\"cost\":\"0.67\"},{\"country\":\"US\",\"msisdn\":\"17088568490\",\"type\":\"mobile-lvn\",\"features\":[\"SMS\",\"VOICE\"],\"cost\":\"0.67\"},{\"country\":\"US\",\"msisdn\":\"17088568491\",\"type\":\"mobile-lvn\",\"features\":[\"SMS\",\"VOICE\"],\"cost\":\"0.67\"},{\"country\":\"US\",\"msisdn\":\"17088568492\",\"type\":\"mobile-lvn\",\"features\":[\"SMS\",\"VOICE\"],\"cost\":\"0.67\"},{\"country\":\"US\",\"msisdn\":\"17088568973\",\"type\":\"mobile-lvn\",\"features\":[\"SMS\",\"VOICE\"],\"cost\":\"0.67\"}]}"; public static String jsonResultES700 = "{\"friendlyName\":\"+34911067000\",\"phoneNumber\":\"34911067000\",\"isoCountry\":\"ES\",\"cost\":\"0.50\",\"voiceCapable\":false,\"smsCapable\":true}"; public static String jsonResultUSRange = "{\"friendlyName\":\"+15102694548\",\"phoneNumber\":\"15102694548\",\"isoCountry\":\"US\",\"cost\":\"0.67\",\"voiceCapable\":true,\"smsCapable\":true}"; public static String firstJSonResult501AreaCode = "{\"friendlyName\":\"+15013036357\",\"phoneNumber\":\"15013036357\",\"isoCountry\":\"US\",\"cost\":\"0.67\",\"voiceCapable\":true,\"smsCapable\":true}"; public static final String firstJSonResultCA418AreaCode = "{\"friendlyName\":\"+13658000418\",\"phoneNumber\":\"13658000418\",\"isoCountry\":\"CA\",\"cost\":\"0.67\",\"voiceCapable\":true,\"smsCapable\":true}"; public static final String firstJSonResultCA450AreaCode = "{\"friendlyName\":\"+14506001110\",\"phoneNumber\":\"14506001110\",\"isoCountry\":\"CA\",\"cost\":\"0.67\",\"voiceCapable\":true,\"smsCapable\":true}"; }
6,349
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoxboneIncomingPhoneNumbersEndpointTestUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/voxbone/VoxboneIncomingPhoneNumbersEndpointTestUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.voxbone; /** * @author [email protected] * */ public class VoxboneIncomingPhoneNumbersEndpointTestUtils { public static String purchaseNumberSuccessResponse = ""; public static String deleteNumberSuccessResponse = ""; public static final String listCountries = "{\"countries\":[{\"countryCodeA3\":\"ARG\",\"countryName\":\"ARGENTINA\",\"phoneCode\":54,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"AUS\",\"countryName\":\"AUSTRALIA\",\"phoneCode\":61,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"AUT\",\"countryName\":\"AUSTRIA\",\"phoneCode\":43,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"BHR\",\"countryName\":\"BAHRAIN\",\"phoneCode\":973,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"BEL\",\"countryName\":\"BELGIUM\",\"phoneCode\":32,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"BRA\",\"countryName\":\"BRAZIL\",\"phoneCode\":55,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"BGR\",\"countryName\":\"BULGARIA\",\"phoneCode\":359,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"CAN\",\"countryName\":\"CANADA\",\"phoneCode\":1,\"hasStates\":true,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"CHL\",\"countryName\":\"CHILE\",\"phoneCode\":56,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"CHN\",\"countryName\":\"CHINA\",\"phoneCode\":86,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"COL\",\"countryName\":\"COLOMBIA\",\"phoneCode\":57,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"HRV\",\"countryName\":\"CROATIA\",\"phoneCode\":385,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"CYP\",\"countryName\":\"CYPRUS\",\"phoneCode\":357,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"CZE\",\"countryName\":\"CZECH REPUBLIC\",\"phoneCode\":420,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"DNK\",\"countryName\":\"DENMARK\",\"phoneCode\":45,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"DOM\",\"countryName\":\"DOMINICAN REPUBLIC\",\"phoneCode\":1,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"SLV\",\"countryName\":\"EL SALVADOR\",\"phoneCode\":503,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"EST\",\"countryName\":\"ESTONIA\",\"phoneCode\":372,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"FIN\",\"countryName\":\"FINLAND\",\"phoneCode\":358,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"FRA\",\"countryName\":\"FRANCE\",\"phoneCode\":33,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"GEO\",\"countryName\":\"GEORGIA\",\"phoneCode\":995,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"DEU\",\"countryName\":\"GERMANY\",\"phoneCode\":49,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"GRC\",\"countryName\":\"GREECE\",\"phoneCode\":30,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"HKG\",\"countryName\":\"HONG KONG\",\"phoneCode\":852,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"HUN\",\"countryName\":\"HUNGARY\",\"phoneCode\":36,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"IRL\",\"countryName\":\"IRELAND\",\"phoneCode\":353,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"ISR\",\"countryName\":\"ISRAEL\",\"phoneCode\":972,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"ITA\",\"countryName\":\"ITALY\",\"phoneCode\":39,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"JPN\",\"countryName\":\"JAPAN\",\"phoneCode\":81,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"LVA\",\"countryName\":\"LATVIA\",\"phoneCode\":371,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"LTU\",\"countryName\":\"LITHUANIA\",\"phoneCode\":370,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"LUX\",\"countryName\":\"LUXEMBOURG\",\"phoneCode\":352,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"MYS\",\"countryName\":\"MALAYSIA\",\"phoneCode\":60,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"MLT\",\"countryName\":\"MALTA\",\"phoneCode\":356,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"MEX\",\"countryName\":\"MEXICO\",\"phoneCode\":52,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"NLD\",\"countryName\":\"NETHERLANDS\",\"phoneCode\":31,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"NZL\",\"countryName\":\"NEW ZEALAND\",\"phoneCode\":64,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"NOR\",\"countryName\":\"NORWAY\",\"phoneCode\":47,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"PAN\",\"countryName\":\"PANAMA\",\"phoneCode\":507,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"PER\",\"countryName\":\"PERU\",\"phoneCode\":51,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"POL\",\"countryName\":\"POLAND\",\"phoneCode\":48,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"PRT\",\"countryName\":\"PORTUGAL\",\"phoneCode\":351,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"PRI\",\"countryName\":\"PUERTO RICO\",\"phoneCode\":1,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"ROU\",\"countryName\":\"ROMANIA\",\"phoneCode\":40,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"SGP\",\"countryName\":\"SINGAPORE\",\"phoneCode\":65,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"SVK\",\"countryName\":\"SLOVAKIA\",\"phoneCode\":421,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"SVN\",\"countryName\":\"SLOVENIA\",\"phoneCode\":386,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"ZAF\",\"countryName\":\"SOUTH AFRICA\",\"phoneCode\":27,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"KOR\",\"countryName\":\"SOUTH KOREA\",\"phoneCode\":82,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"ESP\",\"countryName\":\"SPAIN\",\"phoneCode\":34,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"SWE\",\"countryName\":\"SWEDEN\",\"phoneCode\":46,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"CHE\",\"countryName\":\"SWITZERLAND\",\"phoneCode\":41,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"TUR\",\"countryName\":\"TURKEY\",\"phoneCode\":90,\"hasStates\":false,\"hasRegulationRequirement\":true},{\"countryCodeA3\":\"GBR\",\"countryName\":\"UNITED KINGDOM\",\"phoneCode\":44,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"USA\",\"countryName\":\"UNITED STATES\",\"phoneCode\":1,\"hasStates\":true,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"VEN\",\"countryName\":\"VENEZUELA\",\"phoneCode\":58,\"hasStates\":false,\"hasRegulationRequirement\":false},{\"countryCodeA3\":\"VIR\",\"countryName\":\"VIRGIN ISLANDS (U.S.)\",\"phoneCode\":1,\"hasStates\":false,\"hasRegulationRequirement\":false}],\"resultCount\":57}"; public static final String orderingCartSuccessResponse = "{\"cart\":{\"cartIdentifier\":30007,\"customerReference\":null,\"description\":null,\"dateAdded\":\"2015-04-22 18:55:45\",\"orderProducts\":null}}"; public static final String purchaseOrderingCartSuccessResponse = "{\"cart\":{\"cartIdentifier\":30018,\"customerReference\":null,\"description\":null,\"dateAdded\":\"2015-04-22 20:14:09\",\"orderProducts\":null}}"; public static final String addToCartSuccessResponse = "{\"status\":\"SUCCESS\"}"; public static final String checkoutCartSuccessResponse = "{\"status\":\"SUCCESS\",\"productCheckoutList\":[{\"productType\":\"DID\",\"status\":\"SUCCESS\",\"orderReference\":\"62252DS997341\",\"message\":null}]}"; public static final String inventoryDidSuccessResponse = "{\"dids\":[{\"didId\":6798794,\"e164\":\"+16418470436\",\"type\":\"GEOGRAPHIC\",\"countryCodeA3\":\"USA\",\"cityName\":\"ACKLEY\",\"areaCode\":\"641\",\"voiceUriId\":null,\"faxUriId\":null,\"smsLinkGroupId\":null,\"orderReference\":\"62252DS997341\",\"channels\":0,\"delivery\":\"BE\",\"trunkId\":null,\"capacityGroupId\":null,\"didGroupId\":22073,\"regulationAddressId\":null,\"srvLookup\":false,\"callerId\":{\"cliFormat\":\"E164\",\"cliValue\":\"\"},\"cliPrivacy\":\"DISABLED\",\"otherOptions\":{\"t38Enabled\":\"false\",\"dtmf\":\"RFC2833\",\"dtmfInbandMute\":\"false\",\"codecs\":[\"G711A\",\"G711U\",\"G729\"]},\"ringback\":\"STANDARD\",\"dnisEnabled\":\"false\",\"blockOrdinary\":false,\"blockCellular\":false,\"blockPayphone\":false,\"smsOutbound\":false,\"webRtc\":false}],\"resultCount\":1}"; public static final String updateDidSuccessResponse = "{\"messages\":[{\"configOption\":\"VOICE\",\"numberUpdated\":1}]}"; public static final String cancelDidSuccessResponse = "{\"numberCancelled\":1}"; public static String jSonResultPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"6798794\",\"phone_number\":\"+16418470436\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":null,\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultDeletePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+34911067000\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultUpdatePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+33911067000\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultUpdateSuccessPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+33911067000\",\"voice_url\":\"http://demo.telestax.com/docs/voice2.xml\",\"voice_method\":\"POST\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":\"http://demo.telestax.com/docs/sms2.xml\",\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultAccountAssociatedPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14216902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultAccountAssociatedPurchaseNumberResult = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My*Company Line\",\"phone_number\":\"+1*6902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice*.xml\",\"voice_method\":\"*\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":*,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/restcomm/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static boolean match(String text, String pattern) { text = text.trim(); pattern = pattern.trim(); // Create the cards by splitting using a RegEx. If more speed // is desired, a simpler character based splitting can be done. String[] cards = pattern.split("\\*"); // Iterate over the cards. for (String card : cards) { int idx = text.indexOf(card); // Card not detected in the text. if (idx == -1) { return false; } // Move ahead, towards the right of the text. text = text.substring(idx + card.length()); } return true; } }
16,731
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
VoxboneAvailablePhoneNumbersEndpointTestUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/voxbone/VoxboneAvailablePhoneNumbersEndpointTestUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.voxbone; /** * @author [email protected] * */ public class VoxboneAvailablePhoneNumbersEndpointTestUtils { public static final String VoiceURIJSonResponse = "{\"voiceUri\":{\"voiceUriId\" : \"http://127.0.0.1:5080\",\"backupUriId\" : \"...\",\"voiceUriProtocol\" : \"...\",\"uri\" : \"...\",\"description\" : \"...\"}}"; public static String firstJSonResult501AreaCode = "{\"friendlyName\":\"USA-BEEBE-501\",\"phoneNumber\":\"21558\",\"isoCountry\":\"USA\",\"voiceCapable\":true,\"smsCapable\":true,\"faxCapable\":true}"; public static String allJSonResult501AreaCode = "{\"friendlyName\": \"USA-BEEBE-501\",\"phoneNumber\": \"21558\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-BENTON-501\",\"phoneNumber\": \"20739\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-BRYANT COLLEGEVILLE-501\",\"phoneNumber\": \"12841\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-CONWAY-501\",\"phoneNumber\": \"20655\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-HOT SPRINGS-501\",\"phoneNumber\": \"20486\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-LITTLE ROCK-501\",\"phoneNumber\": \"6819\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-LONOKE-501\",\"phoneNumber\": \"21541\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-MALVERN-501\",\"phoneNumber\": \"21452\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-MORRILTON-501\",\"phoneNumber\": \"21470\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-PARON-501\",\"phoneNumber\": \"22230\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-PINNACLE-501\",\"phoneNumber\": \"21627\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-SCOTT-501\",\"phoneNumber\": \"22040\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-SEARCY-501\",\"phoneNumber\": \"21428\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-SPRING LAKE-501\",\"phoneNumber\": \"20794\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true},{\"friendlyName\": \"USA-WRIGHTSVILLE-501\",\"phoneNumber\": \"21120\",\"isoCountry\": \"USA\",\"voiceCapable\": true,\"smsCapable\": true,\"faxCapable\": true}"; public static String jsonResponseES700 = "{\"didGroups\":[{\"didGroupId\":7360,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"TOLL_FREE\",\"cityName\":null,\"areaCode\":\"900\",\"rateCenter\":null,\"stock\":187,\"setup100\":300,\"monthly100\":200,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":9919,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"NATIONAL\",\"cityName\":null,\"areaCode\":\"518\",\"rateCenter\":null,\"stock\":515,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6847,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"NATIONAL\",\"cityName\":null,\"areaCode\":\"902\",\"rateCenter\":null,\"stock\":400,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":9794,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"SHARED_COST\",\"cityName\":null,\"areaCode\":\"901\",\"rateCenter\":null,\"stock\":424,\"setup100\":300,\"monthly100\":200,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":22427,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"MOBILE\",\"cityName\":null,\"areaCode\":\"668\",\"rateCenter\":null,\"stock\":894,\"setup100\":0,\"monthly100\":300,\"available\":true,\"regulationRequirement\":{\"addressType\":\"NATIONAL\",\"proofRequired\":false},\"features\":[{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":1092,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ALICANTE\",\"areaCode\":\"96\",\"rateCenter\":null,\"stock\":1125,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":12412,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ARANDA DE DUERO\",\"areaCode\":\"947\",\"rateCenter\":null,\"stock\":78,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":10114,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"AVILA\",\"areaCode\":\"920\",\"rateCenter\":null,\"stock\":595,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20265,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"BADAJOZ\",\"areaCode\":\"824\",\"rateCenter\":null,\"stock\":162,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":18,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"BARCELONA\",\"areaCode\":\"93\",\"rateCenter\":null,\"stock\":1547,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6833,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"BILBAO\",\"areaCode\":\"94\",\"rateCenter\":null,\"stock\":394,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":12410,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"BURGOS\",\"areaCode\":\"947\",\"rateCenter\":null,\"stock\":247,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":10113,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"CACERES\",\"areaCode\":\"927\",\"rateCenter\":null,\"stock\":894,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":9856,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"CADIZ\",\"areaCode\":\"856\",\"rateCenter\":null,\"stock\":87,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":12413,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"CASTELLON LA PLANA\",\"areaCode\":\"964\",\"rateCenter\":null,\"stock\":148,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":10116,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"CIUDAD REAL\",\"areaCode\":\"926\",\"rateCenter\":null,\"stock\":909,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20270,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"CORDOBA\",\"areaCode\":\"857\",\"rateCenter\":null,\"stock\":76,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":12414,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"CUENCA\",\"areaCode\":\"969\",\"rateCenter\":null,\"stock\":37,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20267,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"DON BENITO\",\"areaCode\":\"824\",\"rateCenter\":null,\"stock\":221,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20021,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ECIJA\",\"areaCode\":\"95\",\"rateCenter\":null,\"stock\":143,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":19912,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ELCHE\",\"areaCode\":\"96\",\"rateCenter\":null,\"stock\":217,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":10117,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"GUADALAJARA\",\"areaCode\":\"949\",\"rateCenter\":null,\"stock\":875,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6842,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"HUELVA\",\"areaCode\":\"959\",\"rateCenter\":null,\"stock\":299,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20055,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ISLA CRISTINA\",\"areaCode\":\"959\",\"rateCenter\":null,\"stock\":231,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6849,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"L'HOSPITALET DE LLOBREGAT\",\"areaCode\":\"93\",\"rateCenter\":null,\"stock\":30,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20072,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"LEPE\",\"areaCode\":\"959\",\"rateCenter\":null,\"stock\":232,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":12405,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"LLEIDA\",\"areaCode\":\"873\",\"rateCenter\":null,\"stock\":63,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20268,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"LUCENA\",\"areaCode\":\"857\",\"rateCenter\":null,\"stock\":223,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":17,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MADRID\",\"areaCode\":\"91\",\"rateCenter\":null,\"stock\":2135,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6834,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MALAGA\",\"areaCode\":\"95\",\"rateCenter\":null,\"stock\":303,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":19899,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MARBELLA\",\"areaCode\":\"95\",\"rateCenter\":null,\"stock\":110,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":19889,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MATARO\",\"areaCode\":\"93\",\"rateCenter\":null,\"stock\":57,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20266,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MERIDA\",\"areaCode\":\"824\",\"rateCenter\":null,\"stock\":234,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20104,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MIJAS\",\"areaCode\":\"95\",\"rateCenter\":null,\"stock\":218,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":12411,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MIRANDA DE EBRO\",\"areaCode\":\"947\",\"rateCenter\":null,\"stock\":86,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20130,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ORIHUELA\",\"areaCode\":\"96\",\"rateCenter\":null,\"stock\":224,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20269,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"PUENTE GENIL\",\"areaCode\":\"857\",\"rateCenter\":null,\"stock\":240,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6857,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"SABADELL\",\"areaCode\":\"93\",\"rateCenter\":null,\"stock\":70,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6840,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"SANTANDER\",\"areaCode\":\"942\",\"rateCenter\":null,\"stock\":279,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":10115,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"SEGOVIA\",\"areaCode\":\"921\",\"rateCenter\":null,\"stock\":582,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":1085,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"SEVILLA\",\"areaCode\":\"95\",\"rateCenter\":null,\"stock\":252,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6850,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"TERRASSA\",\"areaCode\":\"93\",\"rateCenter\":null,\"stock\":116,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6844,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"TOLEDO\",\"areaCode\":\"925\",\"rateCenter\":null,\"stock\":570,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20223,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"TORREVIEJA\",\"areaCode\":\"96\",\"rateCenter\":null,\"stock\":209,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20229,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"UTRERA\",\"areaCode\":\"95\",\"rateCenter\":null,\"stock\":235,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":1089,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"VALENCIA\",\"areaCode\":\"96\",\"rateCenter\":null,\"stock\":311,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":20234,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"VELEZ-MALAGA\",\"areaCode\":\"95\",\"rateCenter\":null,\"stock\":215,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]},{\"didGroupId\":6848,\"countryCodeA3\":\"ESP\",\"stateId\":null,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"VITORIA-GASTEIZ\",\"areaCode\":\"945\",\"rateCenter\":null,\"stock\":77,\"setup100\":0,\"monthly100\":195,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"}]}],\"resultCount\":48}"; public static String jsonResponseUSRange = "{\"didGroups\":[{\"didGroupId\":13013,\"countryCodeA3\":\"USA\",\"stateId\":41,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ABERDEEN\",\"areaCode\":\"605\",\"rateCenter\":\"ABERDEEN\",\"stock\":49,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":4089,\"countryCodeA3\":\"USA\",\"stateId\":20,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ABERDEEN\",\"areaCode\":\"443\",\"rateCenter\":\"ABERDEEN\",\"stock\":152,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":10950,\"countryCodeA3\":\"USA\",\"stateId\":43,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ABILENE\",\"areaCode\":\"325\",\"rateCenter\":\"ABILENE\",\"stock\":31,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":21440,\"countryCodeA3\":\"USA\",\"stateId\":46,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ABINGDON\",\"areaCode\":\"276\",\"rateCenter\":\"ABINGDON\",\"stock\":5,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":22073,\"countryCodeA3\":\"USA\",\"stateId\":15,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"ACKLEY\",\"areaCode\":\"641\",\"rateCenter\":\"ACKLEY\",\"stock\":12,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]}],\"resultCount\":5481}"; public static String jsonResultES700 = "{\"friendlyName\":\"ESP-900\",\"phoneNumber\":\"7360\",\"isoCountry\":\"ESP\",\"voiceCapable\":true,\"smsCapable\":false,\"faxCapable\":true}"; public static String jsonResultUSRange = "{\"friendlyName\":\"USA-ABERDEEN-605\",\"phoneNumber\":\"13013\",\"isoCountry\":\"USA\",\"voiceCapable\":true,\"smsCapable\":true,\"faxCapable\":true}"; public static String body501AreaCode = "{\"didGroups\":[{\"didGroupId\":21558,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"BEEBE\",\"areaCode\":\"501\",\"rateCenter\":\"BEEBE\",\"stock\":7,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":20739,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"BENTON\",\"areaCode\":\"501\",\"rateCenter\":\"BENTON\",\"stock\":7,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":12841,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"BRYANT COLLEGEVILLE\",\"areaCode\":\"501\",\"rateCenter\":\"BRYANTCGVL\",\"stock\":6,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":20655,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"CONWAY\",\"areaCode\":\"501\",\"rateCenter\":\"CONWAY\",\"stock\":8,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":20486,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"HOT SPRINGS\",\"areaCode\":\"501\",\"rateCenter\":\"HOTSPRINGS\",\"stock\":5,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":6819,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"LITTLE ROCK\",\"areaCode\":\"501\",\"rateCenter\":\"LITTLEROCK\",\"stock\":110,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":21541,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"LONOKE\",\"areaCode\":\"501\",\"rateCenter\":\"LONOKE\",\"stock\":5,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":21452,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MALVERN\",\"areaCode\":\"501\",\"rateCenter\":\"MALVERN\",\"stock\":11,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":21470,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"MORRILTON\",\"areaCode\":\"501\",\"rateCenter\":\"MORRILTON\",\"stock\":5,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":22230,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"PARON\",\"areaCode\":\"501\",\"rateCenter\":\"PARON\",\"stock\":6,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":21627,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"PINNACLE\",\"areaCode\":\"501\",\"rateCenter\":\"PINNACLE\",\"stock\":5,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":22040,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"SCOTT\",\"areaCode\":\"501\",\"rateCenter\":\"SCOTT\",\"stock\":5,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":21428,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"SEARCY\",\"areaCode\":\"501\",\"rateCenter\":\"SEARCY\",\"stock\":5,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":20794,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"SPRING LAKE\",\"areaCode\":\"501\",\"rateCenter\":\"SPRINGLAKE\",\"stock\":5,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]},{\"didGroupId\":21120,\"countryCodeA3\":\"USA\",\"stateId\":4,\"didType\":\"GEOGRAPHIC\",\"cityName\":\"WRIGHTSVILLE\",\"areaCode\":\"501\",\"rateCenter\":\"WRIGHTSVL\",\"stock\":14,\"setup100\":0,\"monthly100\":100,\"available\":true,\"regulationRequirement\":null,\"features\":[{\"featureId\":6,\"name\":\"VoxFax\",\"description\":\"VoxFax\"},{\"featureId\":25,\"name\":\"VoxSMS\",\"description\":\"VoxSMS\"}]}],\"resultCount\":15}"; }
28,852
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
IncomingPhoneNumbersEndpointTestUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/vi/IncomingPhoneNumbersEndpointTestUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.vi; /** * @author [email protected] * */ public class IncomingPhoneNumbersEndpointTestUtils { public static String purchaseNumberSuccessResponse = "<response id=\"cf1d26d08aa642abb5f729b5a14c26a0\"><header><sessionid>a13b72c3ca20dc2174f9fb964bbc0111</sessionid></header>" + "<body><did><TN>4156902867</TN><status>Assigned to endpoint '11858' rewritten as '+14156902867' Tier 0</status><statuscode>100</statuscode><refid></refid><cnam>0</cnam><tier>0</tier></did></body></response>"; public static String queryDIDSuccessResponse = "<response id=\"fab0fc4b6b094e61b06be40171911c65\"><header><sessionid>1857a2fc18c50e5f423292ce493fb34c</sessionid></header>" + "<body><did><tn>4156902867</tn><status>Number currently assigned to you with refid '' rewritten as '+14156902867' to endpoint '11858'</status><availability>assigned</availability><endpoint>11858</endpoint><rewrite>+14156902867</rewrite><statusCode>100</statusCode><refid></refid><cnam>0</cnam><tier>0</tier><t38>1</t38><cnamStorageActive>0</cnamStorageActive><cnamStorageAvailability>1</cnamStorageAvailability><registered911>0</registered911><registered411>0</registered411></did></body></response>"; public static String deleteNumberSuccessResponse = "<response id=\"9680e514f9fb4fbd852651cefe9f4e58\"><header><sessionid>fcb4bae9401df4d88bbb1f37f55042b9</sessionid></header>" + "<body><did><TN>4196902867</TN><status>Released</status><statuscode>100</statuscode></did></body></response>"; public static String jSonResultPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14156902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultLocalPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14166902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultSIPPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"11223344\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultSIPPurchaseNumberOrg2 = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acg\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"11223344\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acg/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultTollFreePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14176902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultMobilePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14186902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultDeletePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14196902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultUpdatePurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14206902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultUpdateSuccessPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14206902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice2.xml\",\"voice_method\":\"POST\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":\"http://demo.telestax.com/docs/sms2.xml\",\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultAccountAssociatedPurchaseNumber = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My Company Line\",\"phone_number\":\"+14216902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice.xml\",\"voice_method\":\"GET\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":null,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static String jSonResultAccountAssociatedPurchaseNumberResult = "{\"sid\":\"PN*\",\"account_sid\":\"ACae6e420f425248d6a26948c17a9e2acf\",\"friendly_name\":\"My*Company Line\",\"phone_number\":\"+1*6902867\",\"voice_url\":\"http://demo.telestax.com/docs/voice*.xml\",\"voice_method\":\"*\",\"voice_fallback_url\":null,\"voice_fallback_method\":\"POST\",\"status_callback\":null,\"status_callback_method\":\"POST\",\"voice_caller_id_lookup\":false,\"voice_application_sid\":null,\"date_created\":\"*\",\"date_updated\":\"*\",\"sms_url\":*,\"sms_method\":\"POST\",\"sms_fallback_url\":null,\"sms_fallback_method\":\"POST\",\"sms_application_sid\":null,\"ussd_url\":null,\"ussd_method\":\"POST\",\"ussd_fallback_url\":null,\"ussd_fallback_method\":\"POST\",\"ussd_application_sid\":null,\"refer_url\":null,\"refer_method\":\"POST\",\"refer_application_sid\":null,\"capabilities\":{\"voice_capable\":false,\"sms_capable\":false,\"mms_capable\":false,\"fax_capable\":false},\"api_version\":\"2012-04-24\",\"uri\":\"/2012-04-24/Accounts/ACae6e420f425248d6a26948c17a9e2acf/IncomingPhoneNumbers/PN*.json\"}"; public static boolean match(String text, String pattern) { text = text.trim(); pattern = pattern.trim(); // Create the cards by splitting using a RegEx. If more speed // is desired, a simpler character based splitting can be done. String[] cards = pattern.split("\\*"); // Iterate over the cards. for (String card : cards) { int idx = text.indexOf(card); // Card not detected in the text. if (idx == -1) { return false; } // Move ahead, towards the right of the text. text = text.substring(idx + card.length()); } return true; } }
15,275
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
AvailablePhoneNumbersEndpointTestUtils.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/vi/AvailablePhoneNumbersEndpointTestUtils.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.vi; /** * @author [email protected] * */ public class AvailablePhoneNumbersEndpointTestUtils { public static String body501AreaCode = "<response id=\"7bf8a6c56f594126a6cdecadb430b672\"><header><sessionid>d46146b4132d611304269388cffabb17</sessionid></header><body><search><name>npa = '510' </name>" + "<status>Results Found</status><statuscode>100</statuscode>" + "<state><name>CA</name><lata>" + "<name>722</name><rate_center><name>BELVEDERE</name><npa><name>415</name><nxx><name>690</name><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4156902867</tn></nxx><nxx><name>691</name><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">5015554883</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4156914885</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4156914887</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4156914995</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4156914996</tn></nxx><nxx><name>797</name><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4157977554</tn></nxx></npa></rate_center><rate_center><name>CORTEMADRA</name><npa><name>415</name><nxx><name>329</name><tn tier=\"777\" t38=\"0\" cnamStorage=\"0\">4420290373</tn><tn tier=\"777\" t38=\"1\" cnamStorage=\"0\">4420290374</tn></nxx><nxx><name>413</name><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154132282</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154132350</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154132353</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154132354</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">6756532355</tn></nxx><nxx><name>496</name><tn tier=\"0\" t38=\"0\" cnamStorage=\"0\">4154964606</tn><tn tier=\"0\" t38=\"0\" cnamStorage=\"0\">5015554607</tn></nxx><nxx><name>758</name><tn tier=\"3\" t38=\"0\" cnamStorage=\"0\">4157583846</tn></nxx></npa></rate_center><rate_center><name>IGNACIO</name><npa><name>415</name><nxx><name>234</name><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4152341046</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4152341054</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4152341058</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4152341068</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">5105551214</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4152341208</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4152341209</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4152344296</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4152344541</tn></nxx><nxx><name>475</name><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154750513</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154750519</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154751618</tn></nxx><nxx><name>483</name><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154831578</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154831604</tn><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4154834163</tn></nxx></npa></rate_center></lata></state>" + "<state><name>AR</name><lata>" + "<name>622</name><rate_center><name>BELVEDEREAR</name><npa><name>411</name><nxx><name>290</name><tn tier=\"0\" t38=\"1\" cnamStorage=\"1\">4156902899</tn></nxx></npa></rate_center></lata></state>" + "</search></body></response>"; public static String firstJSonResult501AreaCode = "{\"friendlyName\":\"+14156902867\",\"phoneNumber\":\"+14156902867\",\"lata\":722,\"rateCenter\":\"BELVEDERE\",\"region\":\"CA\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"faxCapable\":true}"; public static String firstJSonResult501ContainsPattern = "{\"friendlyName\":\"+15015554883\",\"phoneNumber\":\"+15015554883\",\"lata\":722,\"rateCenter\":\"BELVEDERE\",\"region\":\"CA\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"faxCapable\":true}"; public static String firstJSonResult501ContainsLetterPattern = "{\"friendlyName\":\"+16756532355\",\"phoneNumber\":\"+16756532355\",\"lata\":722,\"rateCenter\":\"CORTEMADRA\",\"region\":\"CA\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"faxCapable\":true}"; public static String firstJSonResult501InRegionPattern = "{\"friendlyName\":\"+14156902899\",\"phoneNumber\":\"+14156902899\",\"lata\":622,\"rateCenter\":\"BELVEDEREAR\",\"region\":\"AR\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"faxCapable\":true}"; public static String firstJSonResultUKPattern = "{\"friendlyName\":\"+14420290374\",\"phoneNumber\":\"+14420290374\",\"lata\":722,\"rateCenter\":\"CORTEMADRA\",\"region\":\"CA\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"faxCapable\":true}"; public static String firstJSonResultAdvancedPattern = "{\"friendlyName\":\"+15015554883\",\"phoneNumber\":\"+15015554883\",\"lata\":722,\"rateCenter\":\"BELVEDERE\",\"region\":\"CA\",\"isoCountry\":\"US\",\"voiceCapable\":true,\"faxCapable\":true}"; }
5,559
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
RestcommIncomingPhoneNumberTool.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.testsuite/src/main/java/org/restcomm/connect/testsuite/provisioning/number/vi/RestcommIncomingPhoneNumberTool.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.testsuite.provisioning.number.vi; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.core.util.MultivaluedMapImpl; import com.thoughtworks.xstream.XStream; import java.util.Map; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import org.apache.log4j.Logger; import org.restcomm.connect.dao.entities.IncomingPhoneNumberList; /** * @author [email protected] (Muhammad Bilal) */ public class RestcommIncomingPhoneNumberTool { private static RestcommIncomingPhoneNumberTool instance; private static String accountsUrl; private static Logger logger = Logger.getLogger(RestcommIncomingPhoneNumberTool.class); private RestcommIncomingPhoneNumberTool() { } public static RestcommIncomingPhoneNumberTool getInstance() { if (instance == null) { instance = new RestcommIncomingPhoneNumberTool(); } return instance; } private String getAccountsUrl(String deploymentUrl, String username, Boolean json) { if (deploymentUrl.endsWith("/")) { deploymentUrl = deploymentUrl.substring(0, deploymentUrl.length() - 1); } accountsUrl = deploymentUrl + "/2012-04-24/Accounts/" + username + "/IncomingPhoneNumbers" + ((json) ? ".json" : ""); return accountsUrl; } public JsonObject getIncomingPhoneNumbers(String deploymentUrl, String username, String authToken) { return (JsonObject) getIncomingPhoneNumbers(deploymentUrl, username, authToken, null, null, true); } public JsonObject getIncomingPhoneNumbers(String deploymentUrl, String username, String authToken, Integer page, Integer pageSize, Boolean json) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, json); WebResource webResource = jerseyClient.resource(url); String response = null; if (page != null || pageSize != null) { MultivaluedMap<String, String> params = new MultivaluedMapImpl(); if (page != null) { params.add("Page", String.valueOf(page)); } if (pageSize != null) { params.add("PageSize", String.valueOf(pageSize)); } response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML) .get(String.class); } else { response = webResource.accept(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML).get(String.class); } JsonParser parser = new JsonParser(); if (json) { JsonObject jsonObject = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonObject()) { jsonObject = jsonElement.getAsJsonObject(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonObject; } else { XStream xstream = new XStream(); xstream.alias("incPhoneNumlist", IncomingPhoneNumberList.class); JsonObject jsonObject = parser.parse(xstream.toXML(response)).getAsJsonObject(); return jsonObject; } } /** * @param deploymentUrl * @param username * @param authToken * @param filters * @return */ public JsonObject getIncomingPhoneNumbersUsingFilter(String deploymentUrl, String username, String authToken, Map<String, String> filters) { Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); for (String filterName : filters.keySet()) { String filterData = filters.get(filterName); params.add(filterName, filterData); } String response = webResource.queryParams(params).accept(MediaType.APPLICATION_JSON).get(String.class); JsonParser parser = new JsonParser(); JsonObject jsonObject = null; try { JsonElement jsonElement = parser.parse(response); if (jsonElement.isJsonObject()) { jsonObject = jsonElement.getAsJsonObject(); } else { logger.info("JsonElement: " + jsonElement.toString()); } } catch (Exception e) { logger.info("Exception during JSON response parsing, exception: " + e); logger.info("JSON response: " + response); } return jsonObject; } public ClientResponse getIncomingPhonNumberClientResponse(String deploymentUrl, String username, String authToken){ Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String url = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(url); return webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class); } public ClientResponse purchaseProviderNumber( String deploymentUrl, String username, String authToken, String phoneNumber, String voiceUrl, String voiceMethod, String friendlyName ){ Client jerseyClient = Client.create(); jerseyClient.addFilter(new HTTPBasicAuthFilter(username, authToken)); String provisioningURL = getAccountsUrl(deploymentUrl, username, true); WebResource webResource = jerseyClient.resource(provisioningURL); MultivaluedMap<String, String> formData = new MultivaluedMapImpl(); formData.add("PhoneNumber", phoneNumber); formData.add("VoiceUrl", voiceUrl); formData.add("FriendlyName", friendlyName); formData.add("VoiceMethod", voiceMethod); return webResource.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept("application/json").post(ClientResponse.class, formData); } }
7,566
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
GetSpeechSynthesizerInfo.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.api/src/main/java/org/restcomm/connect/tts/api/GetSpeechSynthesizerInfo.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.tts.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class GetSpeechSynthesizerInfo { public GetSpeechSynthesizerInfo() { super(); } }
1,107
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SpeechSynthesizerException.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.api/src/main/java/org/restcomm/connect/tts/api/SpeechSynthesizerException.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.tts.api; /** * @author [email protected] (Thomas Quintana) */ public final class SpeechSynthesizerException extends RuntimeException { private static final long serialVersionUID = 1L; public SpeechSynthesizerException() { super(); } public SpeechSynthesizerException(final String message) { super(message); } public SpeechSynthesizerException(final Throwable cause) { super(cause); } public SpeechSynthesizerException(final String message, final Throwable cause) { super(message, cause); } }
1,415
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SpeechSynthesizerRequest.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.api/src/main/java/org/restcomm/connect/tts/api/SpeechSynthesizerRequest.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.tts.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class SpeechSynthesizerRequest { private final String gender; private final String language; private final String text; public SpeechSynthesizerRequest(final String gender, final String language, final String text) { super(); this.gender = gender; this.language = language; this.text = text; } public String gender() { return gender; } public String language() { return language; } public String text() { return text; } }
1,535
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SpeechSynthesizerInfo.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.api/src/main/java/org/restcomm/connect/tts/api/SpeechSynthesizerInfo.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.tts.api; import java.util.Set; import org.restcomm.connect.commons.annotations.concurrency.Immutable; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class SpeechSynthesizerInfo { private final Set<String> languages; public SpeechSynthesizerInfo(final Set<String> languages) { super(); this.languages = languages; } public Set<String> languages() { return languages; } }
1,299
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SpeechSynthesizerResponse.java
/FileExtraction/Java_unseen/RestComm_Restcomm-Connect/restcomm/restcomm.tts.api/src/main/java/org/restcomm/connect/tts/api/SpeechSynthesizerResponse.java
/* * TeleStax, Open Source Cloud Communications * Copyright 2011-2014, Telestax Inc and individual contributors * by the @authors tag. * * This program is free software: you can redistribute it and/or modify * under the terms of the GNU Affero General Public License as * published by the Free Software Foundation; either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ package org.restcomm.connect.tts.api; import org.restcomm.connect.commons.annotations.concurrency.Immutable; import org.restcomm.connect.commons.patterns.StandardResponse; /** * @author [email protected] (Thomas Quintana) */ @Immutable public final class SpeechSynthesizerResponse<T> extends StandardResponse<T> { public SpeechSynthesizerResponse(final T object) { super(object); } public SpeechSynthesizerResponse(final Throwable cause) { super(cause); } public SpeechSynthesizerResponse(final Throwable cause, final String message) { super(cause, message); } }
1,436
Java
.java
RestComm/Restcomm-Connect
239
214
788
2012-08-17T17:47:44Z
2023-04-14T20:58:19Z
SmokeTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/SmokeTest.java
package de.hs_mannheim.informatik.ct; /* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import de.hs_mannheim.informatik.ct.controller.CtController; @SpringBootTest public class SmokeTest { @Autowired private CtController controller; @Test public void contextLoads() throws Exception { assertThat(controller).isNotNull(); } }
1,276
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomServiceHelper.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/RoomServiceHelper.java
package de.hs_mannheim.informatik.ct; /* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ import com.sun.istack.NotNull; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.services.RoomService; import org.springframework.core.io.ClassPathResource; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RoomServiceHelper { private final String COMMA_DELIMITER = ";"; /** * Helper Method to load excel file * @param testExcelPath Filename of excel file. Needs to be stored in resources folder * @return InputStream containing data as if it was loaded from an existing excel file */ public InputStream inputStreamFromTestExcel(String testExcelPath) throws IOException { File excelFile = new ClassPathResource(testExcelPath).getFile(); InputStream is = new FileInputStream(excelFile); return is; } /** * Helper Method to create Buffered Reader from Array List. This is used to test a room import * feature without generating and reading from a csv file. * * @aparam roomData Arraylist holding room data. */ public BufferedReader createCsvBuffer(@NotNull List<String[]> roomData) { StringBuilder buffer = new StringBuilder(); String[] last = roomData.get(0); roomData.remove(last); if(!roomData.isEmpty()) { for (String[] room : roomData) { String roomStream = Stream.of(room).collect(Collectors.joining(COMMA_DELIMITER)); buffer.append(roomStream + '\n'); } } buffer.append(Stream.of(last).collect(Collectors.joining(COMMA_DELIMITER))); return new BufferedReader(new StringReader(buffer.toString())); } /** * Helper method that saves Rooms from Array List into the data base * * @param roomData Array list containing room name, building name and room size for each room that should be created. */ public void saveRooms(List<String[]> roomData, RoomService roomService) throws NumberFormatException { for (String[] room : roomData) { roomService.saveRoom(new Room( room[1], // room name room[0], // building name Integer.parseInt(room[2]) // parse room size from string to int )); } } /** * builds Array List with fixed buildingName and roomSize from String Array containing room names * * @param roomNames Array containing room names * @return Array List where every Array contains data to create and save a Room (room name, building name and room size). */ public List<String[]> createRoomData(String[] roomNames) { List<String[]> roomData = new ArrayList<>(); String buildingName = "A"; String size = "3"; for (String name : roomNames) { roomData.add(new String[]{ buildingName, name, size }); } return roomData; } }
3,936
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomVisitHelper.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/RoomVisitHelper.java
package de.hs_mannheim.informatik.ct.persistence; /* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ import de.hs_mannheim.informatik.ct.model.CheckOutSource; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.RoomVisit; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.util.TimeUtil; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.val; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Date; import java.util.List; @AllArgsConstructor public class RoomVisitHelper { private final Room room; public RoomVisit generateVisit(Visitor visitor, @NonNull LocalDateTime start, LocalDateTime end) { Date endDate = null; CheckOutSource checkOutSource = CheckOutSource.NotCheckedOut; if (end != null) { endDate = TimeUtil.convertToDate(end); checkOutSource = CheckOutSource.UserCheckout; } return new RoomVisit( room, null, TimeUtil.convertToDate(start), endDate, visitor, checkOutSource ); } /** * Generates a list of room visits, some of which should be delete because they are after the expiration date for personal data. * * @param expiredVisitor The visitor used for visits that should be deleted * @param notExpiredVisitor The vistor used for visits that are still valid */ public List<RoomVisit> generateExpirationTestData(Visitor expiredVisitor, Visitor notExpiredVisitor) { val roomVisits = new ArrayList<RoomVisit>(); // Absolutely not expired roomVisits.add(generateVisit( notExpiredVisitor, LocalDateTime.now().minusHours(1), LocalDateTime.now())); // Older but also not expired roomVisits.add(generateVisit( notExpiredVisitor, LocalDateTime.now().minusHours(1).minusDays(25), LocalDateTime.now().minusDays(25))); // Definitely expired roomVisits.add(generateVisit( expiredVisitor, LocalDateTime.now().minusHours(1).minusMonths(2), LocalDateTime.now().minusMonths(2))); // Just expired roomVisits.add(generateVisit( expiredVisitor, LocalDateTime.now().minusHours(1).minusWeeks(4).minusDays(1), LocalDateTime.now().minusWeeks(4).minusDays(1))); return roomVisits; } }
3,318
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
EventVisitRepositoryTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/repositories/EventVisitRepositoryTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.repositories; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.everyItem; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.junit.MatcherAssert.assertThat; import java.time.Instant; import java.util.Date; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit.jupiter.SpringExtension; import de.hs_mannheim.informatik.ct.model.Event; import de.hs_mannheim.informatik.ct.model.EventVisit; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.Visitor; import lombok.val; @ExtendWith(SpringExtension.class) @DataJpaTest public class EventVisitRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private EventVisitRepository eventVisitRepository; @Test public void findVisitsWithContact_MultipleContacts() { val event = entityManager.persist( new Event( "TestEvent", entityManager.persist(new Room("test", "test", 20)), Date.from(Instant.parse("2021-03-20T10:00:00Z")), "target")); val target = entityManager.persist(new Visitor("target")); val contact1 = entityManager.persist(new Visitor("contact1")); val contact2 = entityManager.persist(new Visitor("contact2")); val targetVisit = new EventVisit(event, target, Date.from(Instant.parse("2021-03-20T10:00:00Z"))); targetVisit.setEndDate(Date.from(Instant.parse("2021-03-20T11:00:00Z"))); val contactVisit1 = new EventVisit(event, contact1, Date.from(Instant.parse("2021-03-20T10:15:00Z"))); contactVisit1.setEndDate(Date.from(Instant.parse("2021-03-20T11:00:00Z"))); val contactVisit2 = new EventVisit(event, contact2, Date.from(Instant.parse("2021-03-20T10:00:00Z"))); contactVisit2.setEndDate(Date.from(Instant.parse("2021-03-20T10:15:00Z"))); entityManager.persist(targetVisit); entityManager.persist(contactVisit1); entityManager.persist(contactVisit2); entityManager.flush(); val contacts = eventVisitRepository.findVisitsWithContact(target); assertThat(contacts.size(), equalTo(2)); assertThat(contacts, everyItem(hasProperty("targetVisit", equalTo(targetVisit)))); } }
3,441
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomVisitRepositoryTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/repositories/RoomVisitRepositoryTest.java
package de.hs_mannheim.informatik.ct.persistence.repositories; /* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.RoomVisit; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.RoomVisitHelper; import de.hs_mannheim.informatik.ct.util.TimeUtil; import lombok.val; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.hamcrest.Matchers.*; import static org.hamcrest.junit.MatcherAssert.assertThat; @ExtendWith(SpringExtension.class) @DataJpaTest public class RoomVisitRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private RoomVisitRepository roomVisitRepository; private List<RoomVisit> visits; @Test public void deleteExpiredVisits() { val roomVisitHelper = new RoomVisitHelper(entityManager.persist( new Room("Test", "Test", 20))); val expiredVisitor = entityManager.persist(new Visitor("expired")); val notExpiredVisitor = entityManager.persist(new Visitor("not-expired")); val roomVisits = roomVisitHelper.generateExpirationTestData( expiredVisitor, notExpiredVisitor); roomVisitRepository.saveAll(roomVisits); entityManager.flush(); roomVisitRepository.deleteByEndDateBefore(TimeUtil.convertToDate(LocalDateTime.now().minusWeeks(4))); assertThat(roomVisitRepository.findAll(), everyItem(hasProperty("visitor", equalTo(notExpiredVisitor)))); } @Test public void findVisitsWithContact_MultipleContacts() { val roomVisitHelper = new RoomVisitHelper(entityManager.persist(new Room("Test", "Test", 20))); val target = entityManager.persist(new Visitor("target")); val contact1 = entityManager.persist(new Visitor("contact1")); val contact2 = entityManager.persist(new Visitor("contact2")); val targetVisit = entityManager.persist( roomVisitHelper.generateVisit(target, LocalDateTime.parse("2021-03-20T10:00:00"), LocalDateTime.parse("2021-03-20T11:00:00"))); entityManager.persist( roomVisitHelper.generateVisit(contact1, LocalDateTime.parse("2021-03-20T10:15:00"), LocalDateTime.parse("2021-03-20T11:00:00"))); entityManager.persist( roomVisitHelper.generateVisit(contact2, LocalDateTime.parse("2021-03-20T10:00:00"), LocalDateTime.parse("2021-03-20T10:15:00"))); entityManager.flush(); val contacts = roomVisitRepository.findVisitsWithContact(target); assertThat(contacts.size(), equalTo(2)); assertThat(contacts, everyItem(hasProperty("targetVisit", equalTo(targetVisit)))); } @Test public void findNotCheckedOutVisitsTest() { altSetUp(); roomVisitRepository.saveAll(this.visits); entityManager.flush(); List<RoomVisit> notCheckedOutVisits = roomVisitRepository.findNotCheckedOutVisits(); assertThat(notCheckedOutVisits, equalTo(this.visits)); } @Test public void findNotCheckedOutVisits_RoomParam() { altSetUp(); Room room = this.visits.get(0).getRoom(); roomVisitRepository.saveAll(this.visits); entityManager.flush(); List<RoomVisit> notCheckedOutVisits = roomVisitRepository.findNotCheckedOutVisits(room); assertThat(notCheckedOutVisits, equalTo(this.visits)); } @Test public void findNotCheckedOutVisits_VisitorParam() { altSetUp(); Visitor visitor = this.visits.get(0).getVisitor(); roomVisitRepository.saveAll(this.visits); entityManager.flush(); List<RoomVisit> notCheckedOutVisits = roomVisitRepository.findNotCheckedOutVisits(visitor); assertThat(notCheckedOutVisits, equalTo(this.visits)); } @Test public void getRoomVisitorCount_smallRoom() { altSetUp(); Room smallRoom = new Room("room", "a", 5); List<RoomVisit> fewVisits = generateVisitsForRoom(smallRoom, 2); roomVisitRepository.saveAll(fewVisits); entityManager.flush(); assertThat(roomVisitRepository.getRoomVisitorCount(smallRoom), equalTo(2)); } @Test public void getRoomVisitorCount_mediumRoom() { altSetUp(); Room mediumRoom = new Room("medium", "a", 10); List<RoomVisit> someVisits = generateVisitsForRoom(mediumRoom, 5); roomVisitRepository.saveAll(someVisits); entityManager.flush(); assertThat(roomVisitRepository.getRoomVisitorCount(mediumRoom), equalTo(5)); } @Test public void getRoomVisitorCount_fullRoom() { altSetUp(); Room filledRoom = new Room("full", "a", 10); List<RoomVisit> manyVisits = generateVisitsForRoom(filledRoom, 10); roomVisitRepository.saveAll(manyVisits); entityManager.flush(); assertThat(roomVisitRepository.getRoomVisitorCount(filledRoom), equalTo(10)); } @Test public void getAllStudyRooms_oneEmptyRoom() { val room = entityManager.persist(new Room("test", "a", 5)); entityManager.flush(); val studyRooms = roomVisitRepository.getAllStudyRooms(new String[]{"test"}); assertThat(studyRooms.size(), equalTo(1)); val studyRoom = studyRooms.get(0); assertThat(studyRoom.getRoomName(), equalTo(room.getName())); assertThat(studyRoom.getBuildingName(), equalTo(room.getBuildingName())); assertThat(studyRoom.getVisitorCount(), equalTo(0L)); } @Test public void getAllStudyRooms_oneVisitorInRoom() { val room = entityManager.persist(new Room("test", "a", 5)); RoomVisitHelper roomVisitHelper = new RoomVisitHelper(room); val visit = roomVisitHelper.generateVisit( entityManager.persist(new Visitor("[email protected]")), LocalDateTime.parse("2021-03-20T10:00:00"), null); entityManager.persist(visit); entityManager.flush(); val studyRooms = roomVisitRepository.getAllStudyRooms(new String[]{"test"}); assertThat(studyRooms.size(), equalTo(1)); val studyRoom = studyRooms.get(0); assertThat(studyRoom.getRoomName(), equalTo(room.getName())); assertThat(studyRoom.getBuildingName(), equalTo(room.getBuildingName())); assertThat(studyRoom.getVisitorCount(), equalTo(1L)); } @Test public void getAllStudyRooms_onePastVisitorInRoom() { val room = entityManager.persist(new Room("test", "a", 5)); RoomVisitHelper roomVisitHelper = new RoomVisitHelper(room); val visit = roomVisitHelper.generateVisit( entityManager.persist(new Visitor("[email protected]")), LocalDateTime.parse("2021-03-20T10:00:00"), LocalDateTime.parse("2021-03-20T10:30:00")); entityManager.persist(visit); entityManager.flush(); val studyRooms = roomVisitRepository.getAllStudyRooms(new String[]{"test"}); assertThat(studyRooms.size(), equalTo(1)); val studyRoom = studyRooms.get(0); assertThat(studyRoom.getRoomName(), equalTo(room.getName())); assertThat(studyRoom.getBuildingName(), equalTo(room.getBuildingName())); assertThat(studyRoom.getVisitorCount(), equalTo(0L)); } @Test public void getTotalStudyVisitorCount_noRooms() { roomVisitRepository.getTotalStudyRoomsVisitorCount(new String[]{"test"}); } /** * alternativ setup method. If this is set as default @Before Method some methods wont run */ private void altSetUp() { Room room = new Room("Test", "Test", 20); RoomVisitHelper roomVisitHelper = new RoomVisitHelper(entityManager.persist(room)); Visitor visitor = entityManager.persist(new Visitor("email")); this.visits = Stream.of( roomVisitHelper.generateVisit( visitor, LocalDateTime.now(), null ) ).collect(Collectors.toList()); } /** * Generates a List of RoomVisits for given Room. The Visitor names are created as visitor0 - visitorX where X is @param visitorAmount * * @param room Room object the generated visitors will visit. * @param visitorAmount amount of visitors that should visit the room. * @return List of RoomVisits. */ private List<RoomVisit> generateVisitsForRoom(Room room, int visitorAmount) { RoomVisitHelper roomVisitHelper = new RoomVisitHelper(entityManager.persist(room)); RoomVisit[] visitsList = new RoomVisit[visitorAmount]; for (int i = 0; i < visitorAmount; i++) { Visitor visitor = entityManager.persist(new Visitor("visitor" + i)); visitsList[i] = roomVisitHelper.generateVisit( visitor, LocalDateTime.now(), null ); } return Arrays.asList(visitsList); } }
10,356
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomRepositoryTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/repositories/RoomRepositoryTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.repositories; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.test.context.junit.jupiter.SpringExtension; import de.hs_mannheim.informatik.ct.model.Room; import lombok.val; @ExtendWith(SpringExtension.class) @DataJpaTest public class RoomRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private RoomRepository roomRepository; @Test public void findByNameIgnoreCase() { val unique = entityManager.persist(new Room("UNIQUE", "A", 20)); val ambiguous1 = entityManager.persist(new Room("ambiguous", "A", 20)); entityManager.persist(new Room("aMbIgUoUs", "A", 20)); Assertions.assertEquals(roomRepository.findByNameIgnoreCase(unique.getName()).get(), unique); Assertions.assertThrows(IncorrectResultSizeDataAccessException.class, () -> roomRepository.findByNameIgnoreCase(ambiguous1.getName())); } @Test public void verifyRoomPin() { entityManager.persist(new Room("pintest", "A", 20, "0007")); Assertions.assertEquals("0007", roomRepository.findById("pintest").get().getRoomPin()); } @Test public void getStudyRoomTotalCapacity_noRooms() { roomRepository.getTotalStudyRoomsCapacity(new String[]{"test"}); } @Test public void getStudyRoomTotalCapacity_oneMatchingRoom() { entityManager.persist(new Room("test", "t", 30)); entityManager.persist(new Room("test_noStudy", "t", 20)); val capacity = roomRepository.getTotalStudyRoomsCapacity(new String[]{"test"}); assertThat(capacity, equalTo(30)); } }
2,916
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
VisitorRepositoryTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/repositories/VisitorRepositoryTest.java
package de.hs_mannheim.informatik.ct.persistence.repositories; /* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ import de.hs_mannheim.informatik.ct.model.*; import org.hamcrest.Matchers; import org.hamcrest.junit.MatcherAssert; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.*; @ExtendWith(SpringExtension.class) @DataJpaTest public class VisitorRepositoryTest { @Autowired private TestEntityManager entityManager; @Autowired private VisitorRepository visitorRepository; @Autowired private JdbcTemplate jdbcTemplate; private final Visitor visitor1 = new Visitor("[email protected]"); private final Visitor visitor2 = new Visitor("[email protected]"); private final Visitor visitor3 = new Visitor("[email protected]"); //visitor for encryption testing private final String decryptedEmail = "[email protected]"; private final Visitor visitor4 = new Visitor(decryptedEmail); private void befuelleDatenbank() { Room room = new Room("A008","A", 2); Event event1 = new Event("PR1", room, new Date(), "Herr Müller"); Event event2 = new Event("PR2", room, new Date(), "Frau Meier"); entityManager.persist(event1); entityManager.persist(event2); EventVisit besuch1 = new EventVisit(event1, visitor1, new Date()); EventVisit besuch2 = new EventVisit(event1, visitor2, new Date()); EventVisit besuch3 = new EventVisit(event2, visitor3, new Date()); entityManager.persist(visitor1); entityManager.persist(visitor2); entityManager.persist(visitor3); entityManager.persist(visitor4); besuch1.setEndDate(new Date()); besuch2.setEndDate(new Date()); entityManager.persist(besuch1); entityManager.persist(besuch2); entityManager.persist(besuch3); entityManager.flush(); } /** * Uses the repository to fetch a visitor and checks if the email gets correctly decrypted */ @Test public void readDecryptedViaRepo() { befuelleDatenbank(); Optional<Visitor> visitorOptional = visitorRepository.findByEmail(decryptedEmail); Assertions.assertEquals(decryptedEmail, visitorOptional.get().getEmail()); } /** * Gets all rows from the table visitor directly from the database and checks if the email can be read in clear text (it shouldn't) */ @Test public void readEncryptedViaJDBC() { befuelleDatenbank(); String query = "SELECT * FROM visitor"; jdbcTemplate.query(query, rs -> { ArrayList<String> resultsList = new ArrayList<>(); while (rs.next()) { resultsList.add(rs.getString("EMAIL")); } MatcherAssert.assertThat(resultsList.size(), Matchers.greaterThan(0)); Assertions.assertFalse(resultsList.contains(decryptedEmail)); }); } }
4,101
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ScheduledCheckOut.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/integration/ScheduledCheckOut.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.integration; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Arrays; import java.util.List; import de.hs_mannheim.informatik.ct.model.CheckOutSource; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.RoomVisit; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomVisitRepository; import de.hs_mannheim.informatik.ct.persistence.services.DateTimeService; import de.hs_mannheim.informatik.ct.persistence.services.EventVisitService; import de.hs_mannheim.informatik.ct.persistence.services.RoomVisitService; import de.hs_mannheim.informatik.ct.util.ScheduledMaintenanceTasks; import de.hs_mannheim.informatik.ct.util.TimeUtil; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.mockito.InjectMocks; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.*; import static org.hamcrest.junit.MatcherAssert.assertThat; import static org.mockito.Mockito.when; @ExtendWith(SpringExtension.class) @DataJpaTest public class ScheduledCheckOut { @TestConfiguration static class RoomVisitServiceTestContextConfig { @Bean public RoomVisitService service() { return new RoomVisitService(); } @Bean public EventVisitService eventVisitService() { return new EventVisitService(); } @Bean public ScheduledMaintenanceTasks scheduledMaintenanceTasks(){ return new ScheduledMaintenanceTasks(); } } @MockBean public DateTimeService dateTimeService; @InjectMocks private RoomVisitService roomVisitService; @Autowired private ScheduledMaintenanceTasks scheduledMaintenanceTasks; @Autowired private TestEntityManager entityManager; @Autowired private RoomVisitRepository roomVisitRepository; private LocalDateTime now = LocalDateTime.now(); // copied from ScheduledMaintenanceTasks // WARNING needs to be changed if constants in ScheduledMaintenanceTasks change private int maintenanceHour = 3; private int maintenanceMinute = 55; private String forcedEndTime = "00:00:00"; @BeforeEach void mockDateTimeService(){ // this changes the actual time to 3:55 for roomVisitService. This is the time the cron job should run when(dateTimeService.getNow()).thenReturn(LocalDateTime.now().withHour(maintenanceHour).withMinute(maintenanceMinute)); } @Test void signOutAllVisitors_morning() { // start of the day signOutAllVisitorsToSpecificTime(LocalTime.parse("00:00:00")); } @Test void signOutAllVisitors_lastLecture() { // after last lecture signOutAllVisitorsToSpecificTime(LocalTime.parse("19:00:00")); } @Test void signOutAllVisitors_endOfWork() { // end of workday signOutAllVisitorsToSpecificTime(LocalTime.parse("21:00:00")); } @Test void signOutAllVisitors_scheduledTime(){ // this tests the actual forced end time signOutAllVisitorsToSpecificTime(LocalTime.parse(forcedEndTime)); } /** * tests daily check out by generating visits at important times and running doMaintenance() */ @Test void scheduledMaintenanceTasksTest() { Room room = entityManager.persist(new Room("A001", "A", 10)); // visitors that checked in today and should not get checked out by maintenance task List<RoomVisit> visitsToday = Arrays.asList( entityManager.persist(new RoomVisit( entityManager.persist(new Visitor("1")), room, TimeUtil.convertToDate(now.withHour(3).withMinute(54).withSecond(59)) )), entityManager.persist(new RoomVisit( entityManager.persist(new Visitor("2")), room, TimeUtil.convertToDate(now.withHour(0).withMinute(0).withSecond(0)) )), entityManager.persist(new RoomVisit( entityManager.persist(new Visitor("3")), room, TimeUtil.convertToDate(now.withHour(12).withMinute(0).withSecond(0)) )) ); // visitors that checked in yesterday and should get checked out by maintenance task List<RoomVisit> visitsYesterday = Arrays.asList( entityManager.persist(new RoomVisit( entityManager.persist(new Visitor("4")), room, TimeUtil.convertToDate(now.withHour(23).withMinute(59).withSecond(59).minusDays(1)) )), entityManager.persist(new RoomVisit( entityManager.persist(new Visitor("5")), room, TimeUtil.convertToDate(now.withHour(0).withMinute(0).withSecond(1).minusDays(1)) )) ); roomVisitRepository.saveAll(visitsToday); roomVisitRepository.saveAll(visitsYesterday); // run check out task scheduledMaintenanceTasks.doMaintenance(); // tests repository assertThat(roomVisitRepository.findNotCheckedOutVisits(room), everyItem(in(visitsToday))); assertThat(roomVisitRepository.findNotCheckedOutVisits(room), not(everyItem(in(visitsYesterday)))); // test RoomVisit objects visitsToday.stream().allMatch( visit -> visit.getCheckOutSource().equals(CheckOutSource.NotCheckedOut) && visit.getEndDate() == null ); visitsYesterday.stream().allMatch( visit -> visit.getCheckOutSource().equals(CheckOutSource.AutomaticCheckout) && visit.getEndDate() != null ); } /** * runs singOutAllVisitors() to a specified forcedEndTime and test if the visitor got checked out properly. * @param forcedEndtime every visit that happened before this time is going to be checked out */ private void signOutAllVisitorsToSpecificTime(LocalTime forcedEndtime){ Room room = entityManager.persist(new Room("Test", "Test", 20)); Visitor expiredVisitor = entityManager.persist(new Visitor("expired")); RoomVisit roomVisit = new RoomVisit( expiredVisitor, room, TimeUtil.convertToDate(now.withHour(12).minusDays(1)) ); roomVisitRepository.save(roomVisit); // forcing check out at given time scheduledMaintenanceTasks.signOutAllVisitors(forcedEndtime); assertThat(roomVisitRepository.getRoomVisitorCount(room), is(0)); assertThat(roomVisit.getCheckOutSource(), is(CheckOutSource.AutomaticCheckout)); assertThat(roomVisit.getEndDate(), not(nullValue())); } }
8,281
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
VisitExpiryTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/integration/VisitExpiryTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.integration; import static org.hamcrest.Matchers.anyOf; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.everyItem; import static org.hamcrest.Matchers.hasProperty; import static org.hamcrest.junit.MatcherAssert.assertThat; import java.time.LocalDateTime; import java.time.Period; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit.jupiter.SpringExtension; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.RoomVisitHelper; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomVisitRepository; import de.hs_mannheim.informatik.ct.persistence.repositories.VisitorRepository; import de.hs_mannheim.informatik.ct.persistence.services.DateTimeService; import de.hs_mannheim.informatik.ct.persistence.services.RoomVisitService; import lombok.val; @ExtendWith(SpringExtension.class) @DataJpaTest public class VisitExpiryTest { @TestConfiguration static class RoomVisitServiceTestContextConfig { @Bean public RoomVisitService service() { return new RoomVisitService(); } @Bean public DateTimeService dateTimeService() { return new DateTimeService(); } } @Autowired private RoomVisitService roomVisitService; @Autowired private TestEntityManager entityManager; @Autowired private RoomVisitRepository roomVisitRepository; @Autowired private VisitorRepository visitorRepository; /** * This test creates room visits, some of which are expired, and verifies that room visits older than the deletion * date are removed. If a user has no more room visits remaining on record, they have to be removed as well. */ @Test public void expirePersonalData() { val roomVisitHelper = new RoomVisitHelper(entityManager.persist( new Room("Test", "Test", 20))); val expiredVisitor = entityManager.persist(new Visitor("expired")); val notExpiredVisitor = entityManager.persist(new Visitor("not-expired")); val partiallyExpiredVisitor = entityManager.persist(new Visitor("some-expired")); val roomVisits = roomVisitHelper.generateExpirationTestData(expiredVisitor, notExpiredVisitor); // Add visits for a visitor that has an expired visit, but also a visit that is kept on record // A visit that just ended roomVisits.add(roomVisitHelper.generateVisit( partiallyExpiredVisitor, LocalDateTime.now().minusHours(1), LocalDateTime.now())); // A visit that ended two months ago, to be removed roomVisits.add(roomVisitHelper.generateVisit( partiallyExpiredVisitor, LocalDateTime.now().minusHours(1).minusMonths(2), LocalDateTime.now().minusMonths(2))); roomVisitRepository.saveAll(roomVisits); // Expire records older than 4 Weeks roomVisitService.deleteExpiredRecords(Period.ofWeeks(4)); // Verify that visit are expired assertThat(roomVisitRepository.findAll(), everyItem(hasProperty("visitor", anyOf(equalTo(notExpiredVisitor), equalTo(partiallyExpiredVisitor))))); // Verify that only the expired visitor was removed assertThat(visitorRepository.findAll().size(), equalTo(2)); assertThat(visitorRepository.findAll(), everyItem(anyOf(equalTo(notExpiredVisitor), equalTo(partiallyExpiredVisitor)))); } }
4,817
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ContactTracingServiceTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/services/ContactTracingServiceTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.apache.xmlbeans.impl.tool.XSTCTester.TestCase; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit.jupiter.SpringExtension; import de.hs_mannheim.informatik.ct.model.Visitor; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SpringExtension.class) public class ContactTracingServiceTest extends TestCase { @TestConfiguration static class ContactTracingServiceTestTestContextConfig { @Bean public ContactTracingService service() { return new ContactTracingService(); } } @Autowired private ContactTracingService contactTracingService; @MockBean private RoomVisitService roomVisitService; @MockBean private EventVisitService eventVisitService; @Test public void ContactTracing_CallsAllOtherServices() { contactTracingService.getVisitorContacts(new Visitor()); verify(roomVisitService, times(1)) .getVisitorContacts(any()); verify(eventVisitService, times(1)) .getVisitorContacts(any()); } }
2,381
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
DateTimeServiceTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/services/DateTimeServiceTest.java
package de.hs_mannheim.informatik.ct.persistence.services; /* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ import lombok.val; import org.apache.xmlbeans.impl.tool.XSTCTester.TestCase; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.Duration; import java.util.Date; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.lessThan; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SpringExtension.class) public class DateTimeServiceTest extends TestCase { private final DateTimeService dateTimeService = new DateTimeService(); @Test public void getDateNowIsNewDate() { val serviceDate = dateTimeService.getDateNow(); val newDate = new Date(); val diff = Duration.between(serviceDate.toInstant(), newDate.toInstant()).abs(); assertThat(diff.toMillis(), lessThan(100L)); } }
1,761
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
VisitorServiceTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/services/VisitorServiceTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.verify; import java.util.Optional; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit.jupiter.SpringExtension; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.InvalidEmailException; import de.hs_mannheim.informatik.ct.persistence.InvalidExternalUserdataException; import de.hs_mannheim.informatik.ct.persistence.repositories.VisitorRepository; import lombok.val; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SpringExtension.class) public class VisitorServiceTest { @TestConfiguration static class VisitorServiceTestConfig { @Bean public VisitorService visitorService() { return new VisitorService(); } } @Autowired private VisitorService visitorService; @MockBean private VisitorRepository visitorRepository; @Test void createVisitorsCheckEmail() { // Create new visitors Mockito.when(visitorRepository.findByEmail(any(String.class))) .thenReturn(Optional.empty()); Mockito.when(visitorRepository.save(any(Visitor.class))) .thenAnswer(visitor -> visitor.getArgument(0, Visitor.class)); // Empty email Assertions.assertThrows(InvalidEmailException.class, () -> visitorService.findOrCreateVisitor("",null, null, null)); // Incomplete email Assertions.assertThrows(InvalidEmailException.class, () -> visitorService.findOrCreateVisitor("13337@",null, null, null)); Assertions.assertThrows(InvalidEmailException.class, () -> visitorService.findOrCreateVisitor("12",null, null, null)); Assertions.assertThrows(InvalidEmailException.class, () -> visitorService.findOrCreateVisitor("[email protected]",null, null, null)); // External Guest required mail, name and (number or address) Assertions.assertThrows(InvalidEmailException.class, () -> visitorService.findOrCreateVisitor("","CoolName", "Number is a String", "null")); Assertions.assertThrows(InvalidExternalUserdataException.class, () -> visitorService.findOrCreateVisitor("[email protected]",null, "123456 call me", null)); Assertions.assertThrows(InvalidExternalUserdataException.class, () -> visitorService.findOrCreateVisitor("[email protected]","Dragons", null, null)); try { //Valid external emails visitorService.findOrCreateVisitor("[email protected]","Tester1", "123", null); visitorService.findOrCreateVisitor("[email protected]","Tester2", "345", null); visitorService.findOrCreateVisitor("[email protected]","Tester3", "234", null); visitorService.findOrCreateVisitor("[email protected]","Tester3", "234", "That's were I live"); visitorService.findOrCreateVisitor("[email protected]","Tester3", null, "beautiful place"); // Valid internal emails visitorService.findOrCreateVisitor("[email protected]",null, null, null); visitorService.findOrCreateVisitor("[email protected]",null, null, null); } catch (InvalidEmailException | InvalidExternalUserdataException e) { fail("Valid email caused exception"); } } /** * There was a bug that caused the findOrCreateVisitor method to save the visitor even if it was found. This causes * a constraint violation, Therefore ensure that save is ONLY called if the visitor wasn't found. */ @Test void finOrCreateNoDuplicateSave() throws InvalidEmailException, InvalidExternalUserdataException { val email = "[email protected]"; val visitor = new Visitor(); // The visitor doesn't exist yet doReturn(Optional.empty()).when(visitorRepository).findByEmail(email); visitorService.findOrCreateVisitor(email,null, null, null); // The visitor exists now doReturn(Optional.of(visitor)).when(visitorRepository).findByEmail(email); Assertions.assertTrue(visitorService.findVisitorByEmail(email).isPresent()); // This should return the visitor without creating a new one visitorService.findOrCreateVisitor(email,null, null, null); // Finally ensure that save was called exactly once verify( visitorRepository, Mockito.times(1)) .save(any(Visitor.class)); } }
5,805
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomVisitServiceTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/services/RoomVisitServiceTest.java
package de.hs_mannheim.informatik.ct.persistence.services; /* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ import de.hs_mannheim.informatik.ct.model.CheckOutSource; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.RoomVisit; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.RoomVisitHelper; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomRepository; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomVisitRepository; import de.hs_mannheim.informatik.ct.persistence.repositories.VisitorRepository; import lombok.NonNull; import lombok.val; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.time.*; import java.util.*; import static de.hs_mannheim.informatik.ct.util.TimeUtil.convertToLocalDateTime; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.lessThan; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SpringExtension.class) class RoomVisitServiceTest { @TestConfiguration static class RoomVisitServiceTestContextConfig { @Bean public RoomVisitService service() { return new RoomVisitService(); } } @Autowired private RoomVisitService roomVisitService; @MockBean private RoomVisitRepository roomVisitRepository; @MockBean private RoomRepository roomRepository; @MockBean private VisitorRepository visitorRepository; @MockBean private DateTimeService dateTimeService; @MockBean private RoomVisit roomVisit; @Captor private ArgumentCaptor<List<RoomVisit>> roomVisitCaptor; private AutoCloseable mocks; private LocalDate today = LocalDate.of(2021, Month.APRIL, 2); private LocalDateTime now = LocalDateTime.of(today, LocalTime.of(18, 1)); @BeforeEach public void openMocks() { mocks = MockitoAnnotations.openMocks(this); } @AfterEach public void releaseMocks() throws Exception { mocks.close(); } @Test void autoCheckOutVisitor_HadCheckedOutProperly() { val forcedEndTime = LocalTime.of(18, 0); Mockito.when(roomVisitRepository.findNotCheckedOutVisits()) .thenReturn(Collections.emptyList()); roomVisitService.checkOutAllVisitors(forcedEndTime); Mockito .verify( roomVisitRepository, Mockito.times(1)) .saveAll(roomVisitCaptor.capture()); val capturedArgument = roomVisitCaptor.getValue(); assertThat(capturedArgument.size(), equalTo(0)); } @Test void autoCheckOutVisitor_NoCheckoutYesterday() { val forcedEndTime = LocalTime.of(18, 0); val today = LocalDate.of(2021, Month.APRIL, 2); val yesterday = today.minusDays(1); val checkInTime = LocalDateTime.of(yesterday, LocalTime.of(14, 0)); val now = LocalDateTime.of(today, forcedEndTime.plusHours(1)); val expectedCheckout = LocalDateTime.of(yesterday, forcedEndTime); Mockito.when(dateTimeService.getNow()) .thenReturn(now); testAutoCheckout(checkInTime, forcedEndTime, expectedCheckout); } @Test void autoCheckOutVisitor_NoCheckoutToday() { val forcedEndTime = LocalTime.of(18, 0); val today = LocalDate.of(2021, Month.APRIL, 2); val checkInTime = LocalDateTime.of(today, LocalTime.of(14, 0)); val now = LocalDateTime.of(today, forcedEndTime.plusHours(1)); val expectedCheckout = LocalDateTime.of(today, forcedEndTime); Mockito.when(dateTimeService.getNow()) .thenReturn(now); testAutoCheckout(checkInTime, forcedEndTime, expectedCheckout); } /** * Someone checked in yesterday AFTER the auto-checkout. They should be checked out at midnight. */ @Test void autoCheckOutVisitor_NoCheckoutYesterdayAfterAutoCheckout() { val forcedEndTime = LocalTime.of(18, 0); val today = LocalDate.of(2021, Month.APRIL, 2); val yesterday = today.minusDays(1); val checkInTime = LocalDateTime.of(yesterday, LocalTime.of(18, 1)); val now = LocalDateTime.of(today, forcedEndTime.plusHours(1)); val expectedCheckout = LocalDateTime.of(yesterday, LocalTime.of(23, 59, 59)); Mockito.when(dateTimeService.getNow()) .thenReturn(now); testAutoCheckout(checkInTime, forcedEndTime, expectedCheckout); } /** * Someone checked in today AFTER the auto-checkout. They should not be checked out today. */ @Test void autoCheckOutVisitor_NoCheckoutTodayAfterAutoCheckout() { val forcedEndTime = LocalTime.of(18, 0); val today = LocalDate.of(2021, Month.APRIL, 2); val checkInTime = LocalDateTime.of(today, LocalTime.of(18, 1)); val now = LocalDateTime.of(today, forcedEndTime.plusHours(1)); Mockito.when(dateTimeService.getNow()) .thenReturn(now); testAutoCheckout(checkInTime, forcedEndTime, null); } @Test void deleteExpiredRecords() { roomVisitService.deleteExpiredRecords(Period.ofWeeks(4)); val dateCaptor = ArgumentCaptor.forClass(Date.class); Mockito.verify( visitorRepository, Mockito.times(1) ).removeVisitorsWithNoVisits(); Mockito.verify( roomVisitRepository, Mockito.times(1) ).deleteByEndDateBefore(dateCaptor.capture()); val actualDate = convertToLocalDateTime(dateCaptor.getValue()); val expectedDate = LocalDateTime.now().minusWeeks(4); assertThat(Duration.between(actualDate, expectedDate).toMinutes(), is(lessThan(1L))); } @Test void resetEmptyRoom(){ Room emptyRoom = new Room("A", "B", 2); Mockito.when(roomVisitRepository.findNotCheckedOutVisits(emptyRoom)) .thenReturn(new LinkedList<RoomVisit>()); roomVisitService.resetRoom(emptyRoom); Mockito.verify(roomVisitRepository).findNotCheckedOutVisits(emptyRoom); Mockito.verify(roomVisitRepository, Mockito.times(1)) .saveAll(roomVisitCaptor.capture()); } @Test void resetFilledRoom(){ Visitor visitor = new Visitor("visitor"); RoomVisit visit = new RoomVisitHelper(new Room("A", "B", 2)).generateVisit( visitor, this.now, null ); // setup Room filledRoom = visit.getRoom(); Mockito.when(roomVisitRepository.findNotCheckedOutVisits(filledRoom)) .thenReturn(Collections.singletonList(visit)); Mockito.when(dateTimeService.getDateNow()) .thenReturn(java.util.Date.from(this.today.atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant())); // method call roomVisitService.resetRoom(filledRoom); // behavior validation Mockito.verify(roomVisitRepository).findNotCheckedOutVisits(filledRoom); Mockito.verify(roomVisitRepository, Mockito.times(1)) .saveAll(roomVisitCaptor.capture()); assertThat(roomVisitService.getVisitorCount(filledRoom), equalTo(0)); } @Test void resetFullRoom(){ Room fullRoom = new Room("A", "B", 10); List<RoomVisit> roomVisits = new ArrayList<RoomVisit>(); // fill roomVisits with Visitors who visit the room for(int i = 0; i < 10; i++){ Visitor visitor = new Visitor("visitor" + i); RoomVisit visit = new RoomVisitHelper(fullRoom).generateVisit( visitor, this.now, null ); roomVisits.add(visit); } // setup Mockito.when(roomVisitRepository.findNotCheckedOutVisits(fullRoom)) .thenReturn(roomVisits); Mockito.when(dateTimeService.getDateNow()) .thenReturn(java.util.Date.from(this.today.atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant())); // method call roomVisitService.resetRoom(fullRoom); // behavior validation Mockito.verify(roomVisitRepository).findNotCheckedOutVisits(fullRoom); Mockito.verify(roomVisitRepository, Mockito.times(1)) .saveAll(roomVisitCaptor.capture()); assertThat(roomVisitService.getVisitorCount(fullRoom), equalTo(0)); } /** * resets a Room with visitors who already checked out and others who did not */ @Test void resetRoomExpiredRecords() { Visitor expiredVisitor = new Visitor("exp"); Visitor notExpiredVisitor = new Visitor("nexp"); Room testRoom = new Room("A", "B", 4); // adds expired and not expired visitors List<RoomVisit> visits = new RoomVisitHelper(testRoom).generateExpirationTestData(expiredVisitor, notExpiredVisitor); // setup Mockito.when(roomVisitRepository.findNotCheckedOutVisits(testRoom)) .thenReturn(visits); Mockito.when(dateTimeService.getDateNow()) .thenReturn(java.util.Date.from(this.today.atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant())); // method call roomVisitService.resetRoom(testRoom); // behavior validation Mockito.verify(roomVisitRepository).findNotCheckedOutVisits(testRoom); assertThat(roomVisitService.getVisitorCount(testRoom), equalTo(0)); for(RoomVisit visit : visits){ assertThat(visit.getCheckOutSource(), not(CheckOutSource.NotCheckedOut)); } } @Test void resetRoom_chekOutSource(){ Room testRoom = new Room("A", "B", 1); Visitor visitor = new Visitor("visitor"); RoomVisit visit = new RoomVisitHelper(new Room("A", "B", 1)).generateVisit( visitor, this.now, null ); // setup Mockito.when(roomVisitRepository.findNotCheckedOutVisits(testRoom)) .thenReturn(Collections.singletonList(visit)); Mockito.when(dateTimeService.getDateNow()) .thenReturn(java.util.Date.from(this.today.atStartOfDay() .atZone(ZoneId.systemDefault()) .toInstant())); roomVisitService.resetRoom(testRoom); assertThat(visit.getCheckOutSource(), equalTo(CheckOutSource.RoomReset)); } private void testAutoCheckout(@NonNull LocalDateTime checkInTime, @NonNull LocalTime forcedEndTime, LocalDateTime expectedCheckoutTime) { val visitor = new Visitor("1"); val visit = new RoomVisitHelper(new Room("A", "A007a", 2)).generateVisit( visitor, checkInTime, null ); Mockito.when(roomVisitRepository.findNotCheckedOutVisits()) .thenReturn(Collections.singletonList(visit)); roomVisitService.checkOutAllVisitors(forcedEndTime); Mockito .verify( roomVisitRepository, Mockito.times(1)) .saveAll(roomVisitCaptor.capture()); val capturedArgument = roomVisitCaptor.getValue(); if (expectedCheckoutTime == null) { // No one to be checked out assertThat(capturedArgument.size(), equalTo(0)); } else { assertThat(capturedArgument.size(), equalTo(1)); val checkedOutVisit = capturedArgument.get(0); assertThat(convertToLocalDateTime(checkedOutVisit.getEndDate()), equalTo(expectedCheckoutTime)); assertThat(checkedOutVisit.getCheckOutSource(), equalTo(CheckOutSource.AutomaticCheckout)); } } }
13,110
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomServiceTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/persistence/services/RoomServiceTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; import java.util.Collections; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomRepository; @ExtendWith(SpringExtension.class) @ExtendWith(MockitoExtension.class) public class RoomServiceTest { @MockBean private RoomRepository roomRepositoryMock; @InjectMocks private RoomService roomService; @Test public void shouldThrowException_When_RaumPinIsNotANumberOrNull() { Room roomWithNullPin = new Room(); roomWithNullPin.setRoomPin(null); Room notValidRoom = new Room(); notValidRoom.setRoomPin("notValidPin"); when(roomRepositoryMock.findAll()).thenReturn(Collections.emptyList()); // Not necessary for the test for the test to pass, but when the test fails it // may mislead the real issue if not present. when(roomRepositoryMock.saveAll(Collections.singletonList(notValidRoom))) .thenReturn(Collections.singletonList(notValidRoom)); assertAll( () -> assertThrows(IllegalArgumentException.class, () -> roomService.saveRoom(notValidRoom)), () -> assertThrows(IllegalArgumentException.class, () -> roomService.saveRoom(roomWithNullPin)) ); } }
2,558
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomControllerOverrideTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/end_to_end/RoomControllerOverrideTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.end_to_end; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.InvalidEmailException; import de.hs_mannheim.informatik.ct.persistence.InvalidExternalUserdataException; import de.hs_mannheim.informatik.ct.persistence.services.RoomService; import de.hs_mannheim.informatik.ct.persistence.services.RoomVisitService; import de.hs_mannheim.informatik.ct.persistence.services.VisitorService; @SpringBootTest @AutoConfigureMockMvc @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) @AutoConfigureTestDatabase(replace = Replace.ANY) @TestPropertySource(properties="allow_full_room_checkIn=true") // this can only be set on class level, hence an extra test class is necessary @TestPropertySource(properties="warning_for_full_room=false") public class RoomControllerOverrideTest { @TestConfiguration static class RoomControllerTestConfig { @Bean public RoomService service() { return new RoomService(); } } @Autowired private RoomService roomService; @Autowired private RoomVisitService roomVisitService; @Autowired private VisitorService visitorService; @Autowired private MockMvc mockMvc; private final String TEST_ROOM_NAME = "123"; private String TEST_ROOM_PIN; private final String TEST_USER_EMAIL = "[email protected]"; @BeforeEach public void setUp() { Room room = new Room(TEST_ROOM_NAME, "A", 10); TEST_ROOM_PIN = room.getRoomPin(); roomService.saveRoom(room); } @Test public void checkInFullRoomWithOverride() throws Exception { // find and fill testroom Room testRoom = roomService.findByName(TEST_ROOM_NAME).get(); fillRoom(testRoom, 10); this.mockMvc.perform( get("/r/" + TEST_ROOM_NAME + "?override=true").with(csrf())) .andExpect(status().isOk()) .andExpect(forwardedUrl(null)); this.mockMvc.perform( post("/r/checkInOverride") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("visitorEmail", TEST_USER_EMAIL) .param("roomId", TEST_ROOM_NAME) .param("roomPin", TEST_ROOM_PIN) .with(csrf())) .andExpect(forwardedUrl(null)) .andExpect(status().isOk()); } /** * Helper method that creates users to fill room. * An address is created by combining iterator value with '@stud.hs-mannheim.de'. * To prevent the Test-User getting checked in, [email protected] is prevented as a fallback Address. * * @param room the room that should get filled. * @param amount the amount the room will be filled. */ public void fillRoom(Room room, int amount) throws InvalidEmailException, InvalidExternalUserdataException { for (int i = 0; i < amount; i++) { String randomUserEmail = String.format("%[email protected]", i); if (randomUserEmail != TEST_USER_EMAIL) { roomVisitService.visitRoom(visitorService.findOrCreateVisitor("" + i + "@stud.hs-mannheim.de", null, null, null), room); } else { roomVisitService.visitRoom(visitorService.findOrCreateVisitor("[email protected]", null, null, null), room); } } } }
5,582
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomControllerTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/end_to_end/RoomControllerTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.end_to_end; import static org.hamcrest.Matchers.containsString; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.net.URLDecoder; import java.net.URLEncoder; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.http.MediaType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.TestPropertySource; import org.springframework.test.web.servlet.MockMvc; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.InvalidEmailException; import de.hs_mannheim.informatik.ct.persistence.InvalidExternalUserdataException; import de.hs_mannheim.informatik.ct.persistence.services.RoomService; import de.hs_mannheim.informatik.ct.persistence.services.RoomVisitService; import de.hs_mannheim.informatik.ct.persistence.services.VisitorService; @SpringBootTest @AutoConfigureMockMvc @DirtiesContext(classMode = ClassMode.BEFORE_EACH_TEST_METHOD) @AutoConfigureTestDatabase(replace = Replace.ANY) @TestPropertySource(properties="allow_full_room_checkIn=false") @TestPropertySource(properties="warning_for_full_room=true") public class RoomControllerTest { @TestConfiguration static class RoomControllerTestConfig { @Bean public RoomService service() { return new RoomService(); } } @Autowired private RoomService roomService; @Autowired private RoomVisitService roomVisitService; @Autowired private VisitorService visitorService; @Autowired private MockMvc mockMvc; private final String TEST_ROOM_NAME = "123"; private String TEST_ROOM_PIN; private final String TEST_ROOM_PIN_INVALID = ""; private final String TEST_USER_EMAIL = "[email protected]"; @BeforeEach public void setUp() { Room room = new Room(TEST_ROOM_NAME, "A", 10); TEST_ROOM_PIN = room.getRoomPin(); roomService.saveRoom(room); } @Test public void areStaticPagesCallable() throws Exception { // strings that called Page should contain String rTestRoom = "HSMA CTT - Check-in Raum " + TEST_ROOM_NAME; String rTestRoomCheckOut = "Check-out"; // /{roomId} this.mockMvc.perform( get("/r/" + TEST_ROOM_NAME).with(csrf())) .andExpect(status().isOk()) .andExpect(content().string( containsString(rTestRoom))); // /{roomId}/checkOut this.mockMvc.perform( get("/r/" + TEST_ROOM_NAME + "/checkOut").with(csrf())) .andExpect(status().isOk()) .andExpect(content().string( containsString(rTestRoomCheckOut) )); } @Test public void accessingImportWithoutAdminLogin() throws Exception { // /import (should not be accessible without admin login) // todo find a way to check for redirect without 'http://localhost' this.mockMvc.perform( get("/r/import").with(csrf())) .andExpect(status().is(302)) .andExpect(redirectedUrl("http://localhost/login")); } @Test public void checkInEmptyRoom() throws Exception { this.mockMvc.perform( post("/r/checkIn") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("visitorEmail", TEST_USER_EMAIL) .param("roomId", TEST_ROOM_NAME) .param("roomPin", TEST_ROOM_PIN) .with(csrf())) .andExpect(status().isOk()); } @Test public void openEventManagerPortal() throws Exception { this.mockMvc.perform( get("/r/"+TEST_ROOM_NAME+"/event-manager-portal") .param("visitorEmail", TEST_USER_EMAIL) ) .andExpect(status().isOk()); } @Test public void resetRoomWithDefaultRedirectURI() throws Exception { this.mockMvc.perform( post("/r/"+TEST_ROOM_NAME+"/executeRoomReset") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .with(csrf()) ) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/r/" + TEST_ROOM_NAME + "?&privileged=true")); } @Test public void resetRoomWithCustomRedirectURI() throws Exception { String redirectURI = URLEncoder.encode("/r/"+TEST_ROOM_NAME+"/event-manager-portal", "UTF-8"); this.mockMvc.perform( post("/r/"+TEST_ROOM_NAME+"/executeRoomReset") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("redirectURI", redirectURI) .with(csrf()) ) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(URLDecoder.decode(redirectURI, "UTF-8"))); } @Test public void checkInFilledRoom() throws Exception { Room testRoom = roomService.findByName(TEST_ROOM_NAME).get(); fillRoom(testRoom, 5); this.mockMvc.perform( post("/r/checkIn") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("visitorEmail", TEST_USER_EMAIL) .param("roomId", TEST_ROOM_NAME) .param("roomPin", TEST_ROOM_PIN) .with(csrf())) .andExpect(status().isOk()); } @Test public void checkInFullRoom() throws Exception { Room testRoom = roomService.findByName(TEST_ROOM_NAME).get(); fillRoom(testRoom, 10); // request form to check into full room should redirect to roomFull/{roomId} this.mockMvc.perform( get("/r/" + TEST_ROOM_NAME).with(csrf())) .andExpect(status().isOk()) .andExpect(forwardedUrl("roomFull/" + TEST_ROOM_NAME)); } @Test public void checkInInvalidCredentials() throws Exception { this.mockMvc.perform( post("/r/checkIn") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("visitorEmail", "") .param("roomId", TEST_ROOM_NAME) .param("roomPin", TEST_ROOM_PIN) .with(csrf())) .andExpect(status().is(400)) .andExpect(content().string(containsString("Ungültige Email."))); } @Test public void checkInInvalidRoomPin() throws Exception { this.mockMvc.perform( post("/r/checkIn") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("visitorEmail", TEST_USER_EMAIL) .param("roomId", TEST_ROOM_NAME) .param("roomPin", TEST_ROOM_PIN_INVALID) .with(csrf())) .andExpect(status().is(400)) .andExpect(content().string(containsString("Ungültige Raum-Pin."))); } @Test public void checkOut() throws Exception { // post request on /r/checkout should check out user and redirect to /r/checkedOut this.mockMvc.perform( // check in post("/r/checkIn") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("visitorEmail", TEST_USER_EMAIL) .param("roomId", TEST_ROOM_NAME) .param("roomPin", TEST_ROOM_PIN) .with(csrf())) .andExpect(status().isOk()) .andDo( // check out result -> mockMvc.perform( post("/r/checkOut") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("visitorEmail", TEST_USER_EMAIL) .with(csrf())) .andExpect(status().isFound()) .andExpect(redirectedUrl("/r/checkedOut"))); } @Test public void checkOutInvalidCredentials() throws Exception { this.mockMvc.perform( // check in post("/r/checkIn") .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("visitorEmail", TEST_USER_EMAIL) .param("roomId", TEST_ROOM_NAME) .param("roomPin", TEST_ROOM_PIN) .with(csrf())) .andExpect(status().isOk()) .andDo( // check out result -> mockMvc.perform( post("/r/checkOut") .contentType(MediaType.APPLICATION_FORM_URLENCODED) // invalid email .param("visitorEmail", "1" + TEST_USER_EMAIL) .with(csrf())) .andExpect(status().is(404))); } @Test public void asyncRoomReset() throws Exception { this.mockMvc.perform( post("/r/" + TEST_ROOM_NAME + "/reset").with(csrf()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("roomPin", TEST_ROOM_PIN) ) .andExpect(status().is(200)); } @Test public void asyncRoomResetWithInvalidPin() throws Exception { this.mockMvc.perform( post("/r/" + TEST_ROOM_NAME + "/reset").with(csrf()) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("roomPin", TEST_ROOM_PIN_INVALID) ) .andExpect(status().is(400)); } @Test public void roomNotFoundException() throws Exception { this.mockMvc.perform( get("/r/" + "thisRoomShouldNotExsits").with(csrf())) .andExpect(status().is(404)) // checking for response status code 404 .andExpect(content().string(containsString("Raum nicht gefunden")));// checking if error message is displayed for user } /** * Helper method that creates users to fill room. * An address is created by combining iterator value with '@stud.hs-mannheim.de'. * To prevent the Test-User getting checked in, [email protected] is prevented as a fallback Address. * * @param room the room that should get filled. * @param amount the amount the room will be filled. */ public void fillRoom(Room room, int amount) throws InvalidEmailException, InvalidExternalUserdataException { for (int i = 0; i < amount; i++) { String randomUserEmail = String.format("%[email protected]", i); if (randomUserEmail != TEST_USER_EMAIL) { roomVisitService.visitRoom(visitorService.findOrCreateVisitor("" + i + "@stud.hs-mannheim.de", null, null, null), room); } else { roomVisitService.visitRoom(visitorService.findOrCreateVisitor("[email protected]", null, null, null), room); } } } }
13,387
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ImportRoomsFromFile.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/end_to_end/ImportRoomsFromFile.java
package de.hs_mannheim.informatik.ct.end_to_end; /* * Corona Tracking Tool der Hochschule Mannheim * Copyright (C) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ import de.hs_mannheim.informatik.ct.RoomServiceHelper; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.services.RoomService; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.TestConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.test.annotation.DirtiesContext; import java.io.*; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import static org.hamcrest.Matchers.*; import static org.hamcrest.junit.MatcherAssert.assertThat; @SpringBootTest @AutoConfigureMockMvc @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY) public class ImportRoomsFromFile { @TestConfiguration static class RoomControllerTestConfig { @Bean public RoomService service() { return new RoomService(); } } @Autowired private RoomService roomService; private RoomServiceHelper helper = new RoomServiceHelper(); // these tests verify that room pins won't change after usage of import functions provided by RoomService.java // CSV tests // one room in csv, same room in DB @Test public void importCsv_overrideSingleRoom_EmptyDB() throws IOException { String roomName = "newTestRoom"; List<String[]> testRoomData = helper.createRoomData(new String[]{roomName}); helper.saveRooms(testRoomData, roomService); String initialTestRoomPin = roomService.findByName(roomName).get().getRoomPin(); BufferedReader csvReader = helper.createCsvBuffer(testRoomData); roomService.importFromCsv(csvReader); String newTestRoomPin = roomService.findByName(roomName).get().getRoomPin(); assertThat(newTestRoomPin, equalTo(initialTestRoomPin)); } // one room in csv, multiple rooms in DB @Test public void importCsv_overrideSingleRoom_FilledDB() throws IOException { String[] roomNames = {"newTestRoom", "some", "other", "rooms", "roomRoom", "emptyRoom"}; List<String[]> testRoomData = helper.createRoomData(roomNames); helper.saveRooms(testRoomData, roomService); String initialTestRoomPin[] = extractRoomPins(roomNames); BufferedReader csvReader = helper.createCsvBuffer(helper.createRoomData(new String[]{roomNames[0]})); roomService.importFromCsv(csvReader); String[] newTestRoomPin = extractRoomPins(roomNames); assertThat(newTestRoomPin, equalTo(initialTestRoomPin)); } // multiple rooms in csv, same rooms in DB but no others @Test public void importCsv_overrideMultipleRooms_EmptyDB() throws IOException { String[] roomNames = new String[]{"newTestRoom", "otherTestRoom", "test", "room"}; List<String[]> testRoomData = helper.createRoomData(roomNames); helper.saveRooms(testRoomData, roomService); String[] initialTestRoomPins = extractRoomPins(roomNames); BufferedReader csvData = helper.createCsvBuffer(testRoomData); roomService.importFromCsv(csvData); String[] newTestRoomPins = extractRoomPins(roomNames); assertThat(initialTestRoomPins, equalTo(newTestRoomPins)); } // multiple rooms in csv, same rooms and additional rooms in DB @Test public void importCsv_overrideMultipleRooms_FilledDB() throws IOException { String[] roomNames = new String[]{"newTestRoom", "otherTestRoom", "test", "room"}; String[] additionalRoomNames = new String[]{"other", "rooms", "roomRoom", "emptyRoom"}; List<String[]> testRoomData = helper.createRoomData(roomNames); List<String[]> additionalData = helper.createRoomData(additionalRoomNames); helper.saveRooms(testRoomData, roomService); helper.saveRooms(additionalData, roomService); String[] initialTestRoomPins = extractRoomPins(roomNames); String[] additionalInitialRoomPins = extractRoomPins(additionalRoomNames); BufferedReader csvData = helper.createCsvBuffer(testRoomData); roomService.importFromCsv(csvData); String[] newTestRoomPins = extractRoomPins(roomNames); String[] additionalNewRoomPins = extractRoomPins(additionalRoomNames); // checks overwritten rooms assertThat(initialTestRoomPins, equalTo(newTestRoomPins)); // checks not overwritten rooms assertThat(additionalInitialRoomPins, equalTo(additionalNewRoomPins)); } // existing and new rooms in csv @Test public void importCsv_overrideRoomsAndAddNew_EmptyDB() throws IOException { String[] roomNamesDB = new String[]{"newTestRoom", "otherTestRoom"}; String[] roomNamesImport = new String[]{roomNamesDB[0], roomNamesDB[1], "roomRoom", "emptyRoom"}; List<String[]> dataDB = helper.createRoomData(roomNamesDB); List<String[]> dataImport = helper.createRoomData(roomNamesImport); helper.saveRooms(dataDB, roomService); String[] initialTestRoomPins = extractRoomPins(roomNamesDB); BufferedReader csvData = helper.createCsvBuffer(dataImport); roomService.importFromCsv(csvData); String[] newTestRoomPins = extractRoomPins(roomNamesDB); assertThat(initialTestRoomPins, equalTo(newTestRoomPins)); } // existing and new rooms in csv, additional rooms that won't get overwritten in DB @Test public void importCsv_overrideRoomsAndAddNew_FilledDB() throws IOException { String[] existingRoomNames = new String[]{"newTestRoom", "otherTestRoom", "test", "room"}; List<String[]> testRoomData = helper.createRoomData(existingRoomNames); helper.saveRooms(testRoomData, roomService); String[] initialTestRoomPins = extractRoomPins(existingRoomNames); String[] newRoomNames = new String[]{"TestR00m", "otherTestRoom", "test2", "room"}; List<String[]> testRoomData2 = helper.createRoomData(newRoomNames); BufferedReader csvData = helper.createCsvBuffer(testRoomData2); roomService.importFromCsv(csvData); String[] newTestRoomPins = extractRoomPins(newRoomNames); for (int i = 0; i < initialTestRoomPins.length; i++) { if (existingRoomNames[i].equals(newRoomNames[i])) { assertThat(initialTestRoomPins[i], equalTo(newTestRoomPins[i])); } } } @Test public void importExcel_overriteMultipleRooms() throws Exception { String testExcelPath = "excelForTest.xlsm"; // needs to be changed if the values in the testfile change. String[] roomNames = new String[]{"A-101", "A-102"}; List<String[]> testRoomData = helper.createRoomData(roomNames); helper.saveRooms(testRoomData, roomService); String[] initialTestRoomPins = extractRoomPins(roomNames); roomService.saveRoom( new Room("A-101", "A", 2) ); roomService.saveRoom( new Room("A-102", "A", 8) ); InputStream is = helper.inputStreamFromTestExcel(testExcelPath); roomService.importFromExcel(is); String[] newTestRoomPins = extractRoomPins(roomNames); for (int i = 0; i < initialTestRoomPins.length; i++) { assertThat(initialTestRoomPins[i], equalTo(newTestRoomPins[i])); } } /** * Helper Method to extract room pins * * @param roomNames string array holding the room names * @return array holding the room pins */ private String[] extractRoomPins(String[] roomNames) throws NoSuchElementException { String[] roomPins = new String[roomNames.length]; for (int i = 0; i < roomNames.length; i++) { Optional<Room> room = roomService.findByName(roomNames[i]); if (room.isPresent()) { roomPins[i] = room.get().getRoomPin(); } else { String errorMessage = "Keine Raum-Pin vorhanden. Raum " + roomNames[i] + " konnte nicht gefunden werden."; throw new NoSuchElementException(errorMessage); } } return roomPins; } }
9,360
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomVisitTest.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/test/java/de/hs_mannheim/informatik/ct/model/RoomVisitTest.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.model; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Date; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.junit.jupiter.SpringExtension; import de.hs_mannheim.informatik.ct.util.ScheduledMaintenanceTasks; import de.hs_mannheim.informatik.ct.util.TimeUtil; @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SpringExtension.class) public class RoomVisitTest { private AutoCloseable mocks; @BeforeEach public void openMocks() { mocks = MockitoAnnotations.openMocks(this); } @AfterEach public void releaseMocks() throws Exception { mocks.close(); } @MockBean private ScheduledMaintenanceTasks scheduledMaintenanceTasks; @MockBean private Room room; @MockBean private Visitor visitor; private LocalDateTime now = LocalDateTime.now(); @Test void checkout() { RoomVisit roomVisit = new RoomVisit( room, null, TimeUtil.convertToDate(now.minusDays(1)), TimeUtil.convertToDate(now), visitor, CheckOutSource.NotCheckedOut); roomVisit.checkOut(TimeUtil.convertToDate(now), CheckOutSource.RoomReset); assertThat(roomVisit.getEndDate(), notNullValue()); assertThat(roomVisit.getCheckOutSource(), not(CheckOutSource.NotCheckedOut)); } @Test void checkout_checkOutSources() { Date validDate = TimeUtil.convertToDate(now); // no matter which check out source is used. The user will get checked out for (CheckOutSource checkOutSource : CheckOutSource.values()) { RoomVisit roomVisit = checkOutCall(validDate, checkOutSource); assertThat(roomVisit.getEndDate(), notNullValue()); assertThat(roomVisit.getCheckOutSource(), not(CheckOutSource.NotCheckedOut)); } } @Test void automaticCheckOutFailureData_checkOut() { Date validDate = TimeUtil.convertToDate(now); Long[] idArray = new Long[]{188L, 192L, 194L, 133L, 123L}; Visitor[] visitors = createVisitors_automaticCheckOutFailureData(); Room[] rooms = createRooms_automaticCheckoutFailureData(); for (int i = 0; i < visitors.length; i++) { RoomVisit roomVisit = new RoomVisit( rooms[i], idArray[i], TimeUtil.convertToDate(now.minusDays(1)), validDate, visitors[i], CheckOutSource.AutomaticCheckout ); roomVisit.checkOut(TimeUtil.convertToDate(now), CheckOutSource.RoomReset); assertThat(roomVisit.getEndDate(), notNullValue()); assertThat(roomVisit.getCheckOutSource(), not(CheckOutSource.NotCheckedOut)); } } @Test void automaticCheckOutFailureData_signOutAllVisitors() { Date validDate = TimeUtil.convertToDate(now.minusMinutes(1)); Long[] idArray = new Long[]{188L, 192L, 194L, 133L, 123L}; Room[] rooms = createRooms_automaticCheckoutFailureData(); Visitor[] visitors = createVisitors_automaticCheckOutFailureData(); for (int i = 0; i < visitors.length; i++) { RoomVisit roomVisit = new RoomVisit( rooms[i], idArray[i], TimeUtil.convertToDate(now.minusDays(1)), validDate, visitors[i], CheckOutSource.AutomaticCheckout ); scheduledMaintenanceTasks.signOutAllVisitors(LocalTime.now()); assertThat(roomVisit.getEndDate(), notNullValue()); assertThat(roomVisit.getCheckOutSource(), not(CheckOutSource.NotCheckedOut)); } } /* Database entry that caused visitors to not get checked out automatically * id | end_date | start_date | room_name | visitor_id | check_out_source * ---- - +-------------------------+-------------------------+-----------+------------+------------------ * 188 | |2021 - 07 - 01 12:29:54.322 | r1 | 187 | 0 * 192 | |2021 - 07 - 01 12:42:29.346 | r2 | 191 | 0 * 194 | |2021 - 07 - 01 12:43:08.854 | r3 | 193 | 0 * 133 | |2021 - 06 - 20 12:07:31.253 | r4 | 27 | * 123 | |2021 - 06 - 17 15:05:49.142 | r5 | 122 | */ /** * Creates objects after a db dump where users did not get checked automatically * * @return visitors that did not get checked out */ private Visitor[] createVisitors_automaticCheckOutFailureData() { Visitor visitor1 = new Visitor(187L, "v1"); Visitor visitor2 = new Visitor(191L, "v2"); Visitor visitor3 = new Visitor(193L, "v3"); Visitor visitor4 = new Visitor(27L, "v4"); Visitor visitor5 = new Visitor(122L, "v5"); return new Visitor[]{visitor1, visitor2, visitor3, visitor4, visitor5}; } /** * Creates objects after a db dump where users did not get checked automatically * * @return censored rooms */ private Room[] createRooms_automaticCheckoutFailureData() { Room room1 = new Room("r1", "L", 10); Room room2 = new Room("r2", "L", 10); Room room4 = new Room("r3", "K", 10); Room room5 = new Room("r4", "L", 10); return new Room[]{room1, room2, room2, room4, room5}; } /** * Imitates check out for given checkOutSource by creating RoomVisit and checking out visitor. * * @param checkOutDate Date Object specifying user check out * @param checkOutSource Entry from CheckOutSource specifying why user got checked out * @return room visit with user checked out */ private RoomVisit checkOutCall(Date checkOutDate, CheckOutSource checkOutSource) { RoomVisit roomVisit = new RoomVisit( room, null, TimeUtil.convertToDate(now.minusDays(1)), checkOutDate, visitor, checkOutSource ); roomVisit.checkOut(TimeUtil.convertToDate(now), CheckOutSource.RoomReset); return roomVisit; } }
7,614
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
CtApp.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/CtApp.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication @EnableScheduling public class CtApp { public static void main(String[] args) { SpringApplication.run(CtApp.class, args); } }
1,162
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
DbInit.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/DbInit.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Service; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.services.RoomService; import lombok.val; @Service public class DbInit implements CommandLineRunner { @Value("${server_env:production}") private String serverEnvironment; @Autowired private RoomService roomService; @Override public void run(String... args) { if (serverEnvironment.equalsIgnoreCase("dev")) { val testRoom = new Room("test", "test", 12); // Don't randomly generate the pin for the test room in dev mode testRoom.setRoomPin("1234"); val roomList = Arrays.asList( new Room("A007a", "A", 3), testRoom, new Room("A210", "A", 19) ); roomService.saveAllRooms(roomList); } } }
1,926
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomFullException.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/RoomFullException.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence; public class RoomFullException extends Exception { }
871
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
EventNotFoundException.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/EventNotFoundException.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence; public class EventNotFoundException extends Exception { }
876
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
InvalidExternalUserdataException.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/InvalidExternalUserdataException.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence; public class InvalidExternalUserdataException extends Exception { }
887
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
InvalidEmailException.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/InvalidEmailException.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence; public class InvalidEmailException extends Exception { }
876
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
EventVisitRepository.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/repositories/EventVisitRepository.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.repositories; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.model.EventVisit; import de.hs_mannheim.informatik.ct.model.Visitor; public interface EventVisitRepository extends JpaRepository<EventVisit, Long> { @Modifying @Transactional void deleteByEndDateBefore(Date endDate); @Query("SELECT COUNT(*) " + "FROM EventVisit visit " + "WHERE visit.event.id = ?1 AND endDate IS NULL") int getEventVisitorCount(long eventId); @Query("SELECT eventVisit " + "FROM EventVisit eventVisit " + "WHERE eventVisit.visitor.email = :visitorEmail and eventVisit.endDate is null") List<EventVisit> getNotSignedOut(@Param(value = "visitorEmail") String visitorEmail); @Query("SELECT NEW de.hs_mannheim.informatik.ct.model.Contact(visitTarget, visitOther) " + "FROM EventVisit visitTarget," + "EventVisit visitOther " + "WHERE visitTarget.visitor = :visitor AND " + "visitTarget.visitor != visitOther.visitor AND " + "visitTarget.event = visitOther.event AND " + "visitTarget.startDate <= visitOther.endDate AND " + "visitOther.startDate <= visitTarget.endDate " + "ORDER BY visitTarget.startDate") List<Contact<EventVisit>> findVisitsWithContact(@Param(value = "visitor") Visitor visitor); }
2,559
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomRepository.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/repositories/RoomRepository.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.repositories; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import de.hs_mannheim.informatik.ct.model.Room; public interface RoomRepository extends JpaRepository<Room, String> { // TODO: is this optimal and smart to do it like this? @Modifying @Transactional @Query(value = "BACKUP TO ?1", nativeQuery = true) int backupH2DB(String path); @Query("SELECT DISTINCT room.buildingName " + "FROM Room room " + "ORDER BY room.buildingName") List<String> getAllBuildings(); Optional<Room> findByNameIgnoreCase(String roomName); List<Room> findByBuildingName(String building); @Query("SELECT COALESCE(SUM(room.maxCapacity), 0) " + "FROM Room room " + "WHERE room.name in :studyRooms") int getTotalStudyRoomsCapacity(@Param("studyRooms") String[] studyRooms); }
1,969
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
EventRepository.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/repositories/EventRepository.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.repositories; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import de.hs_mannheim.informatik.ct.model.Event; import de.hs_mannheim.informatik.ct.model.Room; public interface EventRepository extends JpaRepository<Event, Long> { List<Event> findAllByOrderByDatumAsc(); List<Event> findByDatumGreaterThan(Date startDate); List<Event> findByRoom(Room room); }
1,252
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomVisitRepository.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/repositories/RoomVisitRepository.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.repositories; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.RoomVisit; import de.hs_mannheim.informatik.ct.model.StudyRoom; import de.hs_mannheim.informatik.ct.model.Visitor; import lombok.NonNull; public interface RoomVisitRepository extends JpaRepository<RoomVisit, Long> { @Query("SELECT visit " + "FROM RoomVisit visit " + "WHERE visit.visitor = :visitor and visit.endDate is null") List<RoomVisit> findNotCheckedOutVisits(@Param(value = "visitor") Visitor visitor); @Query("SELECT COUNT (visit) " + "FROM RoomVisit visit " + "WHERE visit.room = :room and visit.endDate is null ") int getRoomVisitorCount(@Param(value = "room") Room room); /** * Finds all visitors that haven't checked out yet. * * @return All visitors that haven't checked out yet. */ @Query("SELECT visit " + "FROM RoomVisit visit " + "WHERE visit.endDate is null") List<RoomVisit> findNotCheckedOutVisits(); @Query("SELECT visit " + "FROM RoomVisit visit " + "WHERE visit.room = :room AND visit.endDate is null") List<RoomVisit> findNotCheckedOutVisits(@NonNull Room room); void deleteByEndDateBefore(Date endDate); @Query("SELECT NEW de.hs_mannheim.informatik.ct.model.Contact(visitTarget, visitOther) " + "FROM RoomVisit visitTarget," + "RoomVisit visitOther " + "WHERE visitTarget.visitor = :visitor AND " + "visitTarget.visitor != visitOther.visitor AND " + "visitTarget.room = visitOther.room AND " + "visitTarget.startDate <= visitOther.endDate AND " + "visitOther.startDate <= visitTarget.endDate " + "ORDER BY visitTarget.startDate") List<Contact<RoomVisit>> findVisitsWithContact(@Param(value = "visitor") Visitor visitor); /** * Gets the total number of people currently checked in in a study room * * @param studyRooms room names of all study rooms * @return total number of people currently checked in in a study room */ @Query("SELECT COUNT (*) " + "FROM RoomVisit rv " + "WHERE rv.room.name IN :studyRooms " + "AND rv.endDate is null") int getTotalStudyRoomsVisitorCount(@Param("studyRooms") String[] studyRooms); /** * Gets all study rooms * * @param studyRooms room names of all study rooms * @return List of study rooms with room infos (roomName, buildingName, maxCapacity) and current visitor count */ @Query("SELECT NEW de.hs_mannheim.informatik.ct.model.StudyRoom" + "(r.name, r.buildingName, MAX(r.maxCapacity), COUNT (rv.room.name) AS visitorCount) " + "FROM Room r " + "LEFT JOIN RoomVisit rv ON (r.name = rv.room.name) AND rv.endDate IS null " + "WHERE r.name IN :studyRooms " + "GROUP BY r.name, r.buildingName") List<StudyRoom> getAllStudyRooms(@Param("studyRooms") String[] studyRooms); }
4,160
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
VisitorRepository.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/repositories/VisitorRepository.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.repositories; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import de.hs_mannheim.informatik.ct.model.Visitor; public interface VisitorRepository extends JpaRepository<Visitor, Long> { Optional<Visitor> findByEmail(String email); List<Visitor> findAll(); /** * Deletes all visitors that are not listed in neither a room nor an event visit. */ @Modifying @Query("DELETE FROM Visitor visitor " + "WHERE visitor NOT IN (" + " SELECT roomVisit.visitor " + " FROM RoomVisit roomVisit) " + "AND visitor NOT IN (" + "SELECT visit.visitor " + "FROM EventVisit visit)") void removeVisitorsWithNoVisits(); }
1,709
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
DateTimeService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/DateTimeService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import org.springframework.stereotype.Service; @Service public class DateTimeService { public LocalDateTime getNow() { return LocalDateTime.now(); } public Date getDateNow() { return Date.from(getNow().atZone(ZoneId.systemDefault()).toInstant()); } }
1,193
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ContactTracingService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/ContactTracingService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import java.util.ArrayList; import java.util.List; import de.hs_mannheim.informatik.ct.model.Visit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.model.Visitor; import lombok.NonNull; import lombok.val; @Service public class ContactTracingService { @Autowired private List<VisitService<?>> visitServices; @NonNull public List<Contact<? extends Visit>> getVisitorContacts(@NonNull Visitor visitor) { val contacts = new ArrayList<Contact<?>>(); for (val service : visitServices) { contacts.addAll(service.getVisitorContacts(visitor)); } return contacts; } }
1,603
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/RoomService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Optional; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.stereotype.Service; import de.hs_mannheim.informatik.ct.controller.RoomController; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomRepository; import lombok.NonNull; @Service public class RoomService { private final String COMMA_DELIMITER = ";"; @Autowired private RoomRepository roomsRepo; public Optional<Room> findByName(String roomName) { try { return roomsRepo.findByNameIgnoreCase(roomName); } catch (IncorrectResultSizeDataAccessException e) { return roomsRepo.findById(roomName); } } /** * Gets a room by id or throws a RoomNotFoundException. * * @param roomId The rooms id. * @return The room. */ public Room getRoomOrThrow(String roomId) { Optional<Room> room = this.findByName(roomId); if (room.isPresent()) { return room.get(); } else { throw new RoomController.RoomNotFoundException(); } } public Room saveRoom(@NonNull Room room) { return saveAllRooms(Collections.singletonList(room)).get(0); } public List<Room> saveAllRooms(@NonNull List<Room> roomList) { return roomsRepo.saveAll(checkRoomPin(roomList)); } private List<Room> checkRoomPin(List<Room> roomList) { List<Room> oldRoomList = roomsRepo.findAll(); for (Room r : roomList) { checkRoomPinFormatForRoom(r); for (Room rOld : oldRoomList) { if (r.getName().equals(rOld.getName())) { r.setRoomPin(rOld.getRoomPin()); break; } } } return roomList; } private void checkRoomPinFormatForRoom(Room room) { try{ Long.parseLong(room.getRoomPin()); } catch (NumberFormatException err) { throw new IllegalArgumentException("Wrong roomPin format 'not a number' so can't proceed."); } catch (NullPointerException err) { throw new IllegalArgumentException("Can't save a Room with a null roomPin."); } } // TODO: Maybe check if csv is correctly formatted (or accept that the user // uploads only correct files?) public void importFromCsv(BufferedReader csv) { csv.lines().map((line) -> { String[] values = line.split(COMMA_DELIMITER); String building = values[0]; String roomName = values[1]; int roomCapacity = Integer.parseInt(values[2]); return new Room(roomName, building, roomCapacity); }).forEach(this::saveRoom); } public void importFromExcel(InputStream is) throws IOException { XSSFWorkbook workbook = XSSFWorkbookFactory.createWorkbook(is); Sheet sheet = workbook.getSheetAt(0); List<Room> rooms = new LinkedList<>(); Iterator<Row> iter = sheet.rowIterator(); if (iter.hasNext()) iter.next(); // skip first line while (iter.hasNext()) { Row row = iter.next(); String building, roomName; int roomCapacity; try { building = row.getCell(32).getStringCellValue(); roomName = row.getCell(34).getStringCellValue(); roomCapacity = (int) row.getCell(35).getNumericCellValue(); // Sometimes POI returns a partially empty row, might be a bug in POI or just weird excel things. if (building.equals("") || roomName.equals("")) { continue; } } catch (NullPointerException e) { // Sometimes POI returns a partially empty row, might be a bug in POI or just weird excel things. continue; } rooms.add(new Room(roomName, building, roomCapacity)); } this.saveAllRooms(rooms); workbook.close(); } }
5,372
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
BuildingService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/BuildingService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomRepository; @Service public class BuildingService { @Autowired private RoomRepository roomRepository; public List<String> getAllBuildings() { return roomRepository.getAllBuildings(); } public List<Room> getAllRoomsInBuilding(String building) { return roomRepository.findByBuildingName(building); } public List<Room> getAllRooms(){ List<Room> allRooms = new ArrayList<>(); List<String> allBuildings = getAllBuildings(); for (String building: allBuildings){ List<Room> roomsinBuilding = getAllRoomsInBuilding(building); for (Room room: roomsinBuilding){ allRooms.add(room); } } return allRooms; } }
1,840
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
VisitorService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/VisitorService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import java.util.Optional; import org.apache.commons.validator.routines.EmailValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.thymeleaf.util.StringUtils; import de.hs_mannheim.informatik.ct.model.ExternalVisitor; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.InvalidEmailException; import de.hs_mannheim.informatik.ct.persistence.InvalidExternalUserdataException; import de.hs_mannheim.informatik.ct.persistence.repositories.VisitorRepository; import lombok.val; @Service public class VisitorService { @Autowired private VisitorRepository visitorRepo; public Optional<Visitor> findVisitorByEmail(String email) { email = email.toLowerCase(); return visitorRepo.findByEmail(email); } @Transactional public Visitor findOrCreateVisitor(String email, String name, String number, String address) throws InvalidEmailException, InvalidExternalUserdataException { email = email.toLowerCase(); val visitor = findVisitorByEmail(email); if (visitor.isPresent()) { return visitor.get(); } else if (EmailValidator.getInstance().isValid(email)) { if (email.endsWith("hs-mannheim.de")) { return visitorRepo.save(new Visitor(email)); } else { if (!StringUtils.isEmptyOrWhitespace(name) && (!StringUtils.isEmptyOrWhitespace(number) || !StringUtils.isEmptyOrWhitespace(address))) { return visitorRepo.save(new ExternalVisitor(email, name, number, address)); } else { throw new InvalidExternalUserdataException(); } } } else { throw new InvalidEmailException(); } } }
2,753
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
EventVisitService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/EventVisitService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import static de.hs_mannheim.informatik.ct.util.TimeUtil.convertToDate; import java.time.LocalDateTime; import java.time.Period; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import com.sun.istack.NotNull; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.model.Event; import de.hs_mannheim.informatik.ct.model.EventVisit; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.repositories.EventVisitRepository; import lombok.NonNull; import lombok.val; @Service public class EventVisitService implements VisitService<EventVisit> { @Autowired private EventVisitRepository eventVisitRepository; @Transactional private void signOut(Visitor visitor, Event event, @NotNull Date end) { val visits = eventVisitRepository.getNotSignedOut(visitor.getEmail()); for (val visit : visits) { visit.setEndDate(end); } eventVisitRepository.saveAll(visits); } /** * Holt alle Besuche eines Besuchers, bei denen er sich noch nicht abgemeldet hat. Normalerweise sollte das nur höchstens einer sein. * * @param visitor Besucher für den nach nicht abgemeldeten Besuchen gesucht wird. * @return Alle nicht abgemeldeten Besuche. */ public List<EventVisit> getNotSignedOutVisits(Visitor visitor) { return eventVisitRepository.getNotSignedOut(visitor.getEmail()); } /** * Meldet den Besucher aus allen angemeldeten Veranstaltungen ab. * * @param visitor Besucher für den nach nicht abgemeldeten Besuchen gesucht wird. * @return Alle nicht abgemeldeten Besuche. */ @Transactional public List<EventVisit> signOutVisitor(Visitor visitor, Date end) { List<EventVisit> eventVisits = getNotSignedOutVisits(visitor); for (EventVisit visit : eventVisits) { signOut(visitor, visit.getEvent(), end); } return eventVisits; } @Transactional(isolation = Isolation.READ_COMMITTED) public void deleteExpiredRecords(Period recordLifeTime) { val oldestAllowedRecord = LocalDateTime.now().minus(recordLifeTime); eventVisitRepository.deleteByEndDateBefore(convertToDate(oldestAllowedRecord)); } @Override public List<Contact<EventVisit>> getVisitorContacts(@NonNull Visitor visitor) { return eventVisitRepository.findVisitsWithContact(visitor); } }
3,525
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
VisitService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/VisitService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import java.util.List; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.model.Visit; import de.hs_mannheim.informatik.ct.model.Visitor; import lombok.NonNull; public interface VisitService<T extends Visit> { List<Contact<T>> getVisitorContacts(@NonNull Visitor visitor); }
1,144
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
EventService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/EventService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import java.util.Collection; import java.util.Date; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import de.hs_mannheim.informatik.ct.model.Event; import de.hs_mannheim.informatik.ct.model.EventVisit; import de.hs_mannheim.informatik.ct.persistence.repositories.EventRepository; import de.hs_mannheim.informatik.ct.persistence.repositories.EventVisitRepository; @Service public class EventService { @Autowired private EventRepository eventRepository; @Autowired private EventVisitRepository eventVisitRepository; @Autowired private DateTimeService dateTimeService; public Event saveEvent(Event entity) { return eventRepository.save(entity); } public Optional<Event> getEventById(long id) { return eventRepository.findById(id); } public EventVisit saveVisit(EventVisit eventVisit) { return eventVisitRepository.save(eventVisit); } public Collection<Event> getAll() { return eventRepository.findAllByOrderByDatumAsc(); } public Collection<Event> getEventsToday() { long time = dateTimeService.getDateNow().getTime(); return eventRepository.findByDatumGreaterThan(new Date(time - time % (24 * 60 * 60 * 1000))); } public int getVisitorCount(long id) { return eventVisitRepository.getEventVisitorCount(id); } }
2,262
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomVisitService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/RoomVisitService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import static de.hs_mannheim.informatik.ct.util.TimeUtil.convertToDate; import static de.hs_mannheim.informatik.ct.util.TimeUtil.convertToLocalDate; import static de.hs_mannheim.informatik.ct.util.TimeUtil.convertToLocalTime; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.Period; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.data.jpa.repository.Modifying; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Transactional; import de.hs_mannheim.informatik.ct.model.CheckOutSource; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.RoomVisit; import de.hs_mannheim.informatik.ct.model.StudyRoom; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomRepository; import de.hs_mannheim.informatik.ct.persistence.repositories.RoomVisitRepository; import de.hs_mannheim.informatik.ct.persistence.repositories.VisitorRepository; import lombok.NonNull; import lombok.val; import lombok.extern.slf4j.Slf4j; @Service @Slf4j public class RoomVisitService implements VisitService<RoomVisit> { @Autowired private RoomVisitRepository roomVisitRepository; @Autowired private RoomRepository roomRepository; @Autowired private VisitorRepository visitorRepository; @Autowired private DateTimeService dateTimeService; @Value("${allow_full_room_checkIn:false}") private boolean allowFullRoomCheckIn; @Value("${ctt.studyRooms}") private String studyRooms; public RoomVisit visitRoom(Visitor visitor, Room room) { return roomVisitRepository.save(new RoomVisit(visitor, room, dateTimeService.getDateNow())); } /** * Check in the visitor into a full room, overriding the limit. Requires the 'allow_full_room_checkIn' env variable * to be set to true. * * @param visitor The visitor to check into a already full room. * @param fullRoom The full room to check into * @return The visit generated by checking into the room. */ public RoomVisit visitFullRoom(Visitor visitor, Room fullRoom) { if (!allowFullRoomCheckIn) { throw new UnsupportedOperationException("Check-in for full rooms is disabled."); } return visitRoom(visitor, fullRoom); } /** * Checks the visitor out from all currently checked-in visits and returns the visits. * Their should usually be only one checked in visit at a time. * * @param visitor The visitor who is checked out of their visits. * @return The rooms the visitor was checked into. */ @NonNull public List<RoomVisit> checkOutVisitor(@NonNull Visitor visitor) { List<RoomVisit> notSignedOutVisits = getCheckedInRoomVisits(visitor); notSignedOutVisits.forEach((visit) -> { visit.checkOut(dateTimeService.getDateNow(), CheckOutSource.UserCheckout); roomVisitRepository.save(visit); }); return notSignedOutVisits; } @NonNull public List<RoomVisit> getCheckedInRoomVisits(@NonNull Visitor visitor) { val notCheckedOutVisits = roomVisitRepository.findNotCheckedOutVisits(visitor); if (notCheckedOutVisits.size() > 1) { log.warn(String.format("Visitor %s was checked into more than one room at once", visitor.getEmail())); } return notCheckedOutVisits; } public void checkOutAllVisitors(@NonNull LocalTime forcedVisitEndTime) { // Setting the end time in Java makes it easier to set it correctly. // Concretely, visits will always end on the same day even if processing was delayed. val notCheckedOut = roomVisitRepository.findNotCheckedOutVisits(); val updatedVisits = notCheckedOut .stream() .map((roomVisit -> { val startTime = convertToLocalTime(roomVisit.getStartDate()); val startDate = convertToLocalDate(roomVisit.getStartDate()); LocalDateTime endDate; if (startTime.isBefore(forcedVisitEndTime)) { endDate = startDate.atTime(forcedVisitEndTime); } else if (startDate.isBefore(dateTimeService.getNow().toLocalDate())) { // Visit started yesterday after forced sign-out time, sign-out at midnight yesterday instead endDate = startDate.atTime(LocalTime.parse("23:59:59")); } else { return null; } roomVisit.checkOut(convertToDate(endDate), CheckOutSource.AutomaticCheckout); return roomVisit; })) .filter(Objects::nonNull) .collect(Collectors.toList()); roomVisitRepository.saveAll(updatedVisits); } public int getVisitorCount(@NonNull Room room) { return roomVisitRepository.getRoomVisitorCount(room); } public boolean isRoomFull(@NonNull Room room) { return getVisitorCount(room) >= room.getMaxCapacity(); } /** * Immediately checks out everyone in the room. * * @param room The room that will be cleared. */ @Transactional(isolation = Isolation.SERIALIZABLE) @Modifying public void resetRoom(@NonNull Room room) { val notCheckedOutVisits = roomVisitRepository.findNotCheckedOutVisits(room); for (val visit : notCheckedOutVisits) { visit.checkOut(dateTimeService.getDateNow(), CheckOutSource.RoomReset); } roomVisitRepository.saveAll(notCheckedOutVisits); assert getVisitorCount(room) == 0; log.info("Room reset for room {}, {} visitors removed.", room.getName(), notCheckedOutVisits.size()); } @Transactional(isolation = Isolation.READ_COMMITTED) public void deleteExpiredRecords(Period recordLifeTime) { val oldestAllowedRecord = LocalDateTime.now().minus(recordLifeTime); roomVisitRepository.deleteByEndDateBefore(convertToDate(oldestAllowedRecord)); visitorRepository.removeVisitorsWithNoVisits(); log.info("Expired records removed."); } public List<Contact<RoomVisit>> getVisitorContacts(@NonNull Visitor visitor) { val contacts = roomVisitRepository.findVisitsWithContact(visitor); log.info("Contact tracing delivered {} contacts.", contacts.size()); return contacts; } public int getRemainingStudyPlaces() { if (studyRooms.isEmpty()) return -1; // if no study rooms are configured in application.properties, skip DB queries String[] roomNames = studyRooms.split(";"); int totalCapacity = roomRepository.getTotalStudyRoomsCapacity(roomNames); int currentVisitorCount = roomVisitRepository.getTotalStudyRoomsVisitorCount(roomNames); return totalCapacity - currentVisitorCount; } public List<StudyRoom> getAllStudyRooms() { String[] roomNames = studyRooms.split(";"); return roomVisitRepository.getAllStudyRooms(roomNames); } }
8,318
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
DynamicContentService.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/persistence/services/DynamicContentService.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.persistence.services; import java.io.ByteArrayOutputStream; import java.io.IOException; // Import the IOException class to handle errors import java.io.OutputStream; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Collection; import java.util.function.Function; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.xmlbeans.XmlException; import org.springframework.stereotype.Service; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import com.google.zxing.EncodeHintType; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.util.ContactListGenerator; import de.hs_mannheim.informatik.ct.util.DocxTemplate; import lombok.val; import net.glxn.qrgen.core.image.ImageType; import net.glxn.qrgen.javase.QRCode; @Service public class DynamicContentService { private final Path defaultDocxTemplatePath = FileSystems.getDefault().getPath("templates/printout/room-printout.docx"); private final Path privilegedDocxTemplatePath = FileSystems.getDefault().getPath("templates/printout/room-printout-privileged.docx"); public byte[] getQRCodePNGImage(UriComponents uri, int width, int height) { ByteArrayOutputStream out = new ByteArrayOutputStream(); QRCode.from(uri.toUriString()) .withSize(width, height) .withHint(EncodeHintType.MARGIN, "5") .to(ImageType.PNG) .writeTo(out); return out.toByteArray(); } public void addRoomPrintOutDocx(Room room, boolean privileged, ZipOutputStream outputStream, Function<Room, UriComponents> uriConverter) throws IOException, XmlException { XWPFDocument document = getRoomPrintOutDocx(room, uriConverter, privileged); writeRoomPrintOutDocx(room, outputStream, document); } public synchronized void writeRoomPrintOutDocx(Room room, ZipOutputStream outputStream, XWPFDocument document) throws IOException { outputStream.putNextEntry(new ZipEntry(room.getBuildingName() + "/" + room.getName() + ".docx")); document.write(outputStream); } public void writeContactList(Collection<Contact<?>> contacts, Visitor target, ContactListGenerator generator, OutputStream outputStream) throws IOException { try (val workbook = generator.generateWorkbook(contacts, target.getEmail())) { workbook.write(outputStream); } } public XWPFDocument getRoomPrintOutDocx(Room room, Function<Room, UriComponents> uriConverter, boolean privileged) throws IOException, XmlException { DocxTemplate templateGenerator; DocxTemplate.TextTemplate<Room> textReplacer = (roomContent, templatePlaceholder) -> { switch (templatePlaceholder) { case "g": return roomContent.getBuildingName(); case "r": return roomContent.getName(); case "l": return uriConverter.apply(roomContent).toUriString(); case "p": return Integer.toString(roomContent.getMaxCapacity()); case "c": return roomContent.getRoomPin(); default: throw new UnsupportedOperationException("Template contains invalid placeholder: " + templatePlaceholder); } }; Function<Room, byte[]> qrGenerator = roomQr -> { // TODO: This is a hack to integrate the PIN code into the QR Code but not in the hyperlink. // depending on privileged the ur should look different which is currently not the case // A007a qr code funktioniert nicht, A210 qr code dagegen schon .....????? if (privileged) { val qrUri = UriComponentsBuilder.fromUri(uriConverter.apply(room).toUri()) .queryParam("pin", room.getRoomPin()) .queryParam("privileged", true) .build(); System.out.println("URL: "+qrUri); return getQRCodePNGImage(qrUri, 500, 500); } else { val qrUri = UriComponentsBuilder.fromUri(uriConverter.apply(room).toUri()) .queryParam("pin", room.getRoomPin()) .build(); return getQRCodePNGImage(qrUri, 500, 500); } }; if (privileged) { templateGenerator = new DocxTemplate<>(privilegedDocxTemplatePath.toFile(), textReplacer, qrGenerator); } else { templateGenerator = new DocxTemplate<>(defaultDocxTemplatePath.toFile(), textReplacer, qrGenerator); } return templateGenerator.generate(room); } }
5,739
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
CtController.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/controller/CtController.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.controller; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import de.hs_mannheim.informatik.ct.model.Event; import de.hs_mannheim.informatik.ct.model.EventVisit; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.EventNotFoundException; import de.hs_mannheim.informatik.ct.persistence.InvalidEmailException; import de.hs_mannheim.informatik.ct.persistence.InvalidExternalUserdataException; import de.hs_mannheim.informatik.ct.persistence.RoomFullException; import de.hs_mannheim.informatik.ct.persistence.services.DateTimeService; import de.hs_mannheim.informatik.ct.persistence.services.EventService; import de.hs_mannheim.informatik.ct.persistence.services.EventVisitService; import de.hs_mannheim.informatik.ct.persistence.services.RoomService; import de.hs_mannheim.informatik.ct.persistence.services.RoomVisitService; import de.hs_mannheim.informatik.ct.persistence.services.VisitorService; @Controller public class CtController { @Autowired private EventService eventService; @Autowired private EventVisitService eventVisitService; @Autowired private RoomService roomService; @Autowired private RoomVisitService roomVisitService; @Autowired private VisitorService visitorService; @Autowired private Utilities util; @Autowired private DateTimeService dateTimeService; @Value("${server.port}") private String port; @Value("${hostname}") private String host; @RequestMapping("/") public String home(Model model) { model.addAttribute("freeLearnerPlaces", roomVisitService.getRemainingStudyPlaces()); return "index"; } @RequestMapping("/neu") // wenn neue veranstaltung erstellt wurde public String newEvent(@RequestParam String name, @RequestParam Optional<Integer> max, @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Date datum, @RequestParam String zeit, // TODO: schauen, ob das auch eleganter geht Model model, Authentication auth, @RequestHeader(value = "Referer", required = false) String referer) { // Optional beim int, um prüfen zu können, ob ein Wert übergeben wurde if (name.isEmpty() || !max.isPresent()) { // Achtung, es gibt Java-8-Versionen, die Optional.isEmpty noch nicht enthalten! model.addAttribute("message", "Bitte alle mit Sternchen markierten Felder ausfüllen."); return "neue"; } if (referer != null && (referer.endsWith("/neuVer") || referer.contains("neu?name="))) { datum = util.uhrzeitAufDatumSetzen(datum, zeit); Room defaultRoom = roomService.saveRoom(new Room("test", "test", max.get())); Event v = eventService.saveEvent(new Event(name, defaultRoom, datum, auth.getName())); return "redirect:/zeige?vid=" + v.getId(); // Qr code zeigen } return "neue"; } @RequestMapping("/besuch") public String neuerBesuch(@RequestParam Long vid, Model model) throws EventNotFoundException { Optional<Event> event = eventService.getEventById(vid); if (event.isPresent()) { model.addAttribute("vid", event.get().getId()); model.addAttribute("name", event.get().getName()); return "eintragen"; } throw new EventNotFoundException(); } @RequestMapping("/besuchMitCode") public String besuchMitCode(@RequestParam Long vid, @CookieValue(value = "email", required = false) String email, Model model, HttpServletResponse response) throws UnsupportedEncodingException, InvalidEmailException, EventNotFoundException, RoomFullException, InvalidExternalUserdataException { if (email == null) { model.addAttribute("vid", vid); return "eintragen"; } return besucheEintragen(vid, email, true, model, "/besuchMitCode", response); } @PostMapping("/senden") public String besucheEintragen(@RequestParam Long vid, @RequestParam String email, @RequestParam(required = false, defaultValue = "false") boolean saveMail, Model model, @RequestHeader(value = "Referer", required = false) String referer, HttpServletResponse response) throws UnsupportedEncodingException, InvalidEmailException, EventNotFoundException, RoomFullException, InvalidExternalUserdataException { model.addAttribute("vid", vid); if (referer != null && (referer.contains("/besuch") || referer.contains("/senden") || referer.contains("/besuchMitCode"))) { if (email.isEmpty()) { throw new InvalidEmailException(); } else { Optional<Event> event = eventService.getEventById(vid); if (!event.isPresent()) { throw new EventNotFoundException(); } else { int visitorCount = eventService.getVisitorCount(vid); Event v = event.get(); if (visitorCount >= v.getRoomCapacity()) { throw new RoomFullException(); } else { Visitor b = null; b = visitorService.findOrCreateVisitor(email, null, null, null); Optional<String> autoAbmeldung = Optional.empty(); List<EventVisit> nichtAbgemeldeteBesuche = eventVisitService.signOutVisitor(b, dateTimeService.getDateNow()); if (nichtAbgemeldeteBesuche.size() > 0) { autoAbmeldung = Optional.ofNullable(nichtAbgemeldeteBesuche.get(0).getEvent().getName()); // TODO: Warning in server console falls mehr als eine Event abgemeldet wurde, // da das eigentlich nicht möglich ist } EventVisit vb = new EventVisit(v, b, dateTimeService.getDateNow()); vb = eventService.saveVisit(vb); if (saveMail) { Cookie c = new Cookie("email", email); c.setMaxAge(60 * 60 * 24 * 365 * 5); c.setPath("/"); response.addCookie(c); } UriComponents uriComponents = UriComponentsBuilder.newInstance() .path("/angemeldet") .queryParam("email", b.getEmail()) .queryParam("veranstaltungId", v.getId()) .queryParamIfPresent("autoAbmeldung", autoAbmeldung) .build() .encode(StandardCharsets.UTF_8); return "redirect:" + uriComponents.toUriString(); } // endif Platz im Raum } // endif Event existiert } // endif nicht leere Mail-Adresse } // endif referer korrekt? return "eintragen"; } @RequestMapping("/veranstaltungen") public String eventList(Model model) { Collection<Event> events = eventService.getAll(); model.addAttribute("events", events); return "eventList"; } @RequestMapping("/zeige") public String showEvent(@RequestParam Long vid, Model model) throws EventNotFoundException { Optional<Event> event = eventService.getEventById(vid); if (event.isPresent()) { model.addAttribute("event", event.get()); model.addAttribute("teilnehmerzahl", eventService.getVisitorCount(vid)); return "event"; } throw new EventNotFoundException(); } @RequestMapping("/angemeldet") public String angemeldet( @RequestParam String email, @RequestParam(value = "veranstaltungId") long eventId, @RequestParam(required = false) Optional<String> autoAbmeldung, Model model, HttpServletResponse response) throws EventNotFoundException { Optional<Event> v = eventService.getEventById(eventId); if (!v.isPresent()) { throw new EventNotFoundException(); } model.addAttribute("visitorEmail", email); model.addAttribute("autoAbmeldung", autoAbmeldung.orElse("")); model.addAttribute("message", "Vielen Dank, Sie wurden erfolgreich im Raum eingecheckt."); Cookie c = new Cookie("checked-into", "" + v.get().getId()); // Achtung, Cookies erlauben keine Sonderzeichen (inkl. Whitespaces)! c.setMaxAge(60 * 60 * 8); c.setPath("/"); response.addCookie(c); return "angemeldet"; } @RequestMapping("/abmelden") public String abmelden(@RequestParam(name = "besucherEmail", required = false) String besucherEmail, Model model, HttpServletRequest request, HttpServletResponse response, @CookieValue("email") String mailInCookie) { // TODO: ich denke, wir müssen das Speichern der Mail im Cookie zur Pflicht machen, wenn wir den Logout über die Leiste oben machen wollen? // Oder wir versuchen es mit einer Session-Variablen? if (besucherEmail == null || besucherEmail.length() == 0) { if (mailInCookie != null && mailInCookie.length() > 0) besucherEmail = mailInCookie; else return "index"; } visitorService.findVisitorByEmail(besucherEmail) .ifPresent(value -> eventVisitService.signOutVisitor(value, dateTimeService.getDateNow())); Cookie c = new Cookie("checked-into", ""); c.setMaxAge(0); c.setPath("/"); response.addCookie(c); return "abgemeldet"; } // zum Testen ggf. wieder aktivieren // @RequestMapping("/loeschen") // public String kontakteLoeschen(Model model) { // vservice.loescheAlteBesuche(); // model.addAttribute("message", "Alte Kontakte gelöscht!"); // // return "index"; // } @RequestMapping("/neuVer") public String neu() { return "neue"; } @RequestMapping("/login") public String login() { return "login"; } @RequestMapping("/datenschutz") public String datenschutz() { return "datenschutz"; } @RequestMapping("/howToQr") public String howToQr() { return "howToQr"; } @RequestMapping("/howToInkognito") public String howToInkognito() { return "howToInkognito"; } @RequestMapping("/learningRooms") public String showLearningRooms(Model model) { model.addAttribute("learningRoomsCapacity", roomVisitService.getAllStudyRooms()); return "learningRooms"; } @RequestMapping("/faq") public String showFaq(Model model) { Map<String, ArrayList<String>> faqs = getFAQText(); ArrayList<String> answers = faqs.get("answers"); ArrayList<String> questions = faqs.get("questions"); model.addAttribute("questions", questions); model.addAttribute("answers", answers); return "faq"; } /** * Helper method to get all the text needed for the FAQ page, stored in a xml file * * @return Map with 2 Array lists, one for all the answers and one for all the questions */ public Map<String, ArrayList<String>> getFAQText() { String FILENAME = "static/faq.xml"; Map<String, ArrayList<String>> faqs = new HashMap<>(); ArrayList<String> answers = new ArrayList<>(); ArrayList<String> questions = new ArrayList<>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { // optional, but recommended process XML securely, avoid attacks like XML External Entities (XXE) dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); // parse XML file DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(this.getClass().getClassLoader().getResourceAsStream(FILENAME)); doc.getDocumentElement().normalize(); // get all faqs NodeList faqNodes = doc.getElementsByTagName("faq-element"); for (int i = 0; i < faqNodes.getLength(); i++) { Node node = faqNodes.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; String question = element.getElementsByTagName("question").item(0).getTextContent(); String answer = element.getElementsByTagName("answer").item(0).getTextContent(); answers.add(answer); questions.add(question); } } faqs.put("answers", answers); faqs.put("questions", questions); } catch (ParserConfigurationException | SAXException | IOException e) { e.printStackTrace(); } return faqs; } }
15,490
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
Utilities.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/controller/Utilities.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.controller; import java.net.URI; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.util.UriComponents; import org.springframework.web.util.UriComponentsBuilder; @Component public class Utilities { @Value("${server.port}") private String port; @Value("${hostname}") private String host; /** * Optional override for the URL the service is reachable at. This URL is used to construct absolute links. * Useful for reverse proxy setups/CDNs. */ @Value("${url_override:#{null}}") private String urlOverride; public Date uhrzeitAufDatumSetzen(Date datum, String zeit) { if (zeit != null && zeit.length() == 5) { Calendar cal = new GregorianCalendar(); cal.setTime(datum); cal.set(Calendar.HOUR, Integer.parseInt(zeit.substring(0, 2))); cal.set(Calendar.MINUTE, Integer.parseInt(zeit.substring(3, 5))); datum = cal.getTime(); } return datum; } /** * Converts a relative local path to an absolute URI * * @param localPath Local path of the resource * @param request The request is used to differentiate between http/https. Should be moved to setting! * @return An absolute URI to the given resource */ public UriComponents getUriToLocalPath(String scheme, String localPath) { return createUriBuilder(scheme, localPath).build(); } public UriComponents getUriToLocalPath(String scheme, String localPath, String query) { return createUriBuilder(scheme, localPath) .query(query) .build(); } private UriComponentsBuilder createUriBuilder(String scheme, String path){ if (urlOverride == null) { return UriComponentsBuilder.newInstance() .scheme(scheme) // TODO: Optimally http/https should be configured somewhere .host(host) .port(port) .path(path); } else { return UriComponentsBuilder.newInstance() .uri(URI.create(urlOverride)) .path(path); } } }
3,137
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ContactTracingController.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/controller/ContactTracingController.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.controller; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.model.Visit; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.services.ContactTracingService; import de.hs_mannheim.informatik.ct.persistence.services.DateTimeService; import de.hs_mannheim.informatik.ct.persistence.services.DynamicContentService; import de.hs_mannheim.informatik.ct.persistence.services.VisitorService; import de.hs_mannheim.informatik.ct.util.ContactListGenerator; import lombok.AllArgsConstructor; import lombok.Data; import lombok.val; @Controller @RequestMapping("tracing") public class ContactTracingController { @Autowired private VisitorService visitorService; @Autowired private ContactTracingService contactTracingService; @Autowired private DateTimeService dateTimeService; @Autowired private DynamicContentService dynamicContentService; private final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd.MM.yyyy"); private final SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm"); private final List<TracingColumn> tracingColumnsStudents = Arrays.asList( new TracingColumn("E-Mail-Adresse", contact -> contact.getContact().getEmail()), new TracingColumn("Matr.Nr.", contact -> contact.getContact().getEmail().split("@")[0]), new TracingColumn("Raum/Veranstaltung", Contact::getContactLocation), new TracingColumn("Datum", contact -> dateFormatter.format(contact.getTargetVisit().getStartDate())), new TracingColumn("Anmeldung Ziel", contact -> timeFormatter.format(contact.getTargetVisit().getStartDate())), new TracingColumn("Anmeldung Kontakt", contact -> timeFormatter.format(contact.getContactVisit().getStartDate())), new TracingColumn("Abmeldung Ziel", contact -> timeFormatter.format(contact.getTargetVisit().getEndDate())), new TracingColumn("Abmeldung Kontakt", contact -> timeFormatter.format(contact.getContactVisit().getEndDate())), new TracingColumn("Adresse", contact -> ""), new TracingColumn("Telefon", contact -> "") ); private final List<TracingColumn> tracingColumnsStaff = Arrays.asList( new TracingColumn("E-Mail-Adresse", contact -> contact.getContact().getEmail()), new TracingColumn("Name", contact -> contact.getContact().getEmail().split("@")[0]), new TracingColumn("Raum/Veranstaltung", Contact::getContactLocation), new TracingColumn("Datum", contact -> dateFormatter.format(contact.getTargetVisit().getStartDate())), new TracingColumn("Anmeldung Ziel", contact -> timeFormatter.format(contact.getTargetVisit().getStartDate())), new TracingColumn("Anmeldung Kontakt", contact -> timeFormatter.format(contact.getContactVisit().getStartDate())), new TracingColumn("Abmeldung Ziel", contact -> timeFormatter.format(contact.getTargetVisit().getEndDate())), new TracingColumn("Abmeldung Kontakt", contact -> timeFormatter.format(contact.getContactVisit().getEndDate())), new TracingColumn("Adresse", contact -> ""), new TracingColumn("Telefon", contact -> "") ); private final List<TracingColumn> tracingColumnsGuests = Arrays.asList( new TracingColumn("E-Mail-Adresse", contact -> contact.getContact().getEmail()), new TracingColumn("Name", contact -> contact.getContact().getName()), new TracingColumn("Raum/Veranstaltung", Contact::getContactLocation), new TracingColumn("Datum", contact -> dateFormatter.format(contact.getTargetVisit().getStartDate())), new TracingColumn("Anmeldung Ziel", contact -> timeFormatter.format(contact.getTargetVisit().getStartDate())), new TracingColumn("Anmeldung Kontakt", contact -> timeFormatter.format(contact.getContactVisit().getStartDate())), new TracingColumn("Abmeldung Ziel", contact -> timeFormatter.format(contact.getTargetVisit().getEndDate())), new TracingColumn("Abmeldung Kontakt", contact -> timeFormatter.format(contact.getContactVisit().getEndDate())), new TracingColumn("Adresse", contact -> contact.getContact().getAddress()), new TracingColumn("Telefon", contact -> contact.getContact().getNumber()) ); @GetMapping("/search") public String searchPage() { return "tracing/search"; } @PostMapping("/results") public String doSearch(@RequestParam String email, Model model) { val target = visitorService.findVisitorByEmail(email); if (!target.isPresent()) { model.addAttribute("error", "Eingegebene E-Mail-Adresse konnte im System nicht gefunden werden!"); return "tracing/search"; } val contacts = contactTracingService.getVisitorContacts(target.get()); List<Contact<?>> contactsStudents = filterContactList(contacts, "students"); List<Contact<?>> contactsStaff = filterContactList(contacts, "staff"); List<Contact<?>> contactsGuests = filterContactList(contacts, "guests"); List<String[]> contactTableStudents = contactsStudents .stream() .map(contact -> { val rowValues = new String[tracingColumnsStudents.size()]; for (int columnIndex = 0; columnIndex < tracingColumnsStudents.size(); columnIndex++) { val column = tracingColumnsStudents.get(columnIndex); rowValues[columnIndex] = column.cellValue.apply(contact); } return rowValues; }).collect(Collectors.toList()); List<String[]> contactTableStaff = contactsStaff .stream() .map(contact -> { val rowValues = new String[tracingColumnsStaff.size()]; for (int columnIndex = 0; columnIndex < tracingColumnsStaff.size(); columnIndex++) { val column = tracingColumnsStaff.get(columnIndex); rowValues[columnIndex] = column.cellValue.apply(contact); } return rowValues; }).collect(Collectors.toList()); List<String[]> contactTableGuests = contactsGuests .stream() .map(contact -> { val rowValues = new String[tracingColumnsGuests.size()]; for (int columnIndex = 0; columnIndex < tracingColumnsGuests.size(); columnIndex++) { val column = tracingColumnsGuests.get(columnIndex); rowValues[columnIndex] = column.cellValue.apply(contact); } return rowValues; }).collect(Collectors.toList()); model.addAttribute("numberOfContacts", contacts.size()); model.addAttribute("tableHeadersStudents", tracingColumnsStudents.stream().map(TracingColumn::getHeader).toArray()); model.addAttribute("tableHeadersStaff", tracingColumnsStaff.stream().map(TracingColumn::getHeader).toArray()); model.addAttribute("tableHeadersGuests", tracingColumnsGuests.stream().map(TracingColumn::getHeader).toArray()); model.addAttribute("tableValuesStudents", contactTableStudents); model.addAttribute("tableValuesStaff", contactTableStaff); model.addAttribute("tableValuesGuests", contactTableGuests); model.addAttribute("target", target.get().getEmail()); return "tracing/contactList.html"; } @GetMapping("/download") public ResponseEntity<StreamingResponseBody> downloadExcel(@RequestParam String email, @RequestParam String type) { Visitor target = visitorService.findVisitorByEmail(email) .orElseThrow(RoomController.RoomNotFoundException::new); List<Contact<?>> contacts = filterContactList(contactTracingService.getVisitorContacts(target), type); List<ContactTracingController.TracingColumn> tracingColumns = tracingColumnsStudents; if (type.equals("staff")) { tracingColumns = tracingColumnsStaff; } else if (type.equals("guests")) { tracingColumns = tracingColumnsGuests; } val generator = new ContactListGenerator( dateTimeService, tracingColumns.stream().map(TracingColumn::getHeader).collect(Collectors.toList()), tracingColumns.stream().map(TracingColumn::getCellValue).collect(Collectors.toList()) ); StreamingResponseBody responseBody = outputStream -> { try { dynamicContentService.writeContactList(contacts, target, generator, outputStream); } catch (Exception e) { throw new RuntimeException(e); } }; return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=kontaktliste.xlsx") .contentType(MediaType.valueOf("application/vnd.ms-excel")) .body(responseBody); } @Data @AllArgsConstructor public static class TracingColumn { private String header; private Function<Contact<?>, String> cellValue; } /** * Helper method to filter the contacts into 3 subcategories: students, employees of the university and guests * * @param contacts List of all possible contacts of the target email * @param type String of the filter type (students/ staff/ guests) * @return filtered List of Contacts */ private List<Contact<? extends Visit>> filterContactList(Collection<Contact<? extends Visit>> contacts, String type) { List<Contact<?>> filteredList = new ArrayList<>(); for (Contact<? extends Visit> contact : contacts) { if (type.equals("students") && contact.getContact().getEmail().contains("@stud.hs-mannheim.de")) { filteredList.add(contact); } else if (type.equals("staff") && (contact.getContact().getEmail().contains("@hs-mannheim.de") || contact.getContact().getEmail().contains("@lba.hs-mannheim.de"))) { filteredList.add(contact); } else if (type.equals("guests") && !(contact.getContact().getEmail().contains("hs-mannheim.de"))) { filteredList.add(contact); } } return filteredList; } }
12,156
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ErrorController.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/controller/ErrorController.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.controller; import java.io.PrintWriter; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import de.hs_mannheim.informatik.ct.controller.exception.InvalidRoomPinException; import de.hs_mannheim.informatik.ct.persistence.EventNotFoundException; import de.hs_mannheim.informatik.ct.persistence.InvalidEmailException; import de.hs_mannheim.informatik.ct.persistence.InvalidExternalUserdataException; import de.hs_mannheim.informatik.ct.persistence.RoomFullException; import lombok.extern.slf4j.Slf4j; @ControllerAdvice @Slf4j public class ErrorController { @ExceptionHandler({RoomController.RoomNotFoundException.class}) @ResponseStatus(value = HttpStatus.NOT_FOUND) // @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Room not found") public String handleRoomNotFoundException(Model model) { model.addAttribute("errorMessage", "Raum nicht gefunden."); return "error/errorTemplate"; } @ExceptionHandler({RoomController.InvalidFileUploadException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) // @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Invalid file upload") public String handleInvalidFileUploadException(Model model) { model.addAttribute("errorMessage", "Ungültiger Datei-Upload."); return "error/errorTemplate"; } @ExceptionHandler({RoomController.VisitorNotFoundException.class}) @ResponseStatus(value = HttpStatus.NOT_FOUND) // @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "visitor not found") public String handleVisitorNotFoundException(Model model) { model.addAttribute("errorMessage", "Besucher nicht gefunden."); return "error/errorTemplate"; } @ExceptionHandler({InvalidEmailException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) // @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "invalid email") public String handleInvalidEmail(Model model) { model.addAttribute("errorMessage", "Ungültige Email."); return "error/errorTemplate"; } @ExceptionHandler({EventNotFoundException.class}) @ResponseStatus(value = HttpStatus.NOT_FOUND) // @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "event not found") public String handleEventNotFound(Model model) { model.addAttribute("errorMessage", "Ereignis nicht gefunden."); return "error/errorTemplate"; } @ExceptionHandler({UnsupportedEncodingException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) // @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "unsupported encoding") public String handleUnsupportedEncodingException(Model model) { model.addAttribute("errorMessage", "Codierung wird nicht unterstützt."); return "error/errorTemplate"; } @ExceptionHandler({RoomFullException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) // @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "room full") public String handleRoomFullException(Model model) { model.addAttribute("errorMessage", "Raum ist voll."); return "error/errorTemplate"; } @ExceptionHandler({InvalidExternalUserdataException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) // @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "invalid external userdata") public String handleInvalidExternalUserdataException(Model model) { model.addAttribute("errorMessage", "Ungültige Benutzerdaten."); return "error/errorTemplate"; } @ExceptionHandler({InvalidRoomPinException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) // @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "invalid room pin") public String handleInvalidRoomPinException(Model model) { model.addAttribute("errorMessage", "Ungültige Raum-Pin."); return "error/errorTemplate"; } @RequestMapping("/error") @ResponseStatus(value = HttpStatus.BAD_REQUEST) // @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "error") public String handleError(HttpServletRequest request) { Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE); log.error("Request Status: {}", status); if (status != null) { Integer statusCode = Integer.valueOf(status.toString()); if (statusCode == HttpStatus.NOT_FOUND.value()) { return "error/404"; } } return "error"; } @ExceptionHandler({Exception.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) // @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "unknown error") public String anyException(Exception e) { StringWriter sw = new StringWriter(); e.printStackTrace(new PrintWriter(sw)); log.error(sw.toString()); return "error"; } }
6,148
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
QRController.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/controller/QRController.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.server.ResponseStatusException; import org.springframework.web.util.UriComponents; import de.hs_mannheim.informatik.ct.persistence.services.DynamicContentService; import de.hs_mannheim.informatik.ct.persistence.services.EventService; import de.hs_mannheim.informatik.ct.persistence.services.RoomService; import lombok.val; @RestController @RequestMapping("/QRCodes") public class QRController { private final String veranstaltungPath = "/besuchMitCode?vid=%s"; private final int maxSizeInPx = 2000; @Autowired private EventService eventService; @Autowired private RoomService roomService; @Autowired private DynamicContentService contentService; @Autowired private Utilities utilities; @Value("${server.port}") private String port; @Value("${hostname}") private String host; @GetMapping(value = "/room/{roomId}", produces = MediaType.IMAGE_PNG_VALUE) public byte[] getRoomQRCode( @PathVariable(name = "roomId") String roomId, @RequestParam(required = false, defaultValue = "400") int width, @RequestParam(required = false, defaultValue = "400") int height, HttpServletRequest request ) { val room = roomService.findByName(roomId); if (!room.isPresent()) { throw new ResponseStatusException(HttpStatus.NOT_FOUND); } val qrUri = utilities.getUriToLocalPath( request.getScheme(), RoomController.getRoomCheckinPath(room.get()) ); return getQRImage(qrUri, width, height); } @GetMapping(value = "/event/{eventId}", produces = MediaType.IMAGE_PNG_VALUE) public byte[] eventQRCode( @PathVariable long eventId, @RequestParam(required = false, defaultValue = "400") int width, @RequestParam(required = false, defaultValue = "400") int height, HttpServletRequest request) { val event = eventService.getEventById(eventId); if (!event.isPresent()) { throw new ResponseStatusException(HttpStatus.NOT_FOUND); } val qrUri = utilities.getUriToLocalPath(request.getScheme(), String.format(veranstaltungPath, event.get().getId())); return getQRImage(qrUri, width, height); } private byte[] getQRImage(UriComponents uri, int requestedWidth, int requestedHeight) { return contentService.getQRCodePNGImage(uri, Math.min(requestedWidth, maxSizeInPx), Math.min(requestedHeight, maxSizeInPx)); } }
3,940
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
RoomController.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/controller/RoomController.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.controller; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.server.ResponseStatusException; import de.hs_mannheim.informatik.ct.controller.exception.InvalidRoomPinException; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.model.RoomVisit; import de.hs_mannheim.informatik.ct.model.RoomVisit.Data; import de.hs_mannheim.informatik.ct.model.Visitor; import de.hs_mannheim.informatik.ct.persistence.InvalidEmailException; import de.hs_mannheim.informatik.ct.persistence.InvalidExternalUserdataException; import de.hs_mannheim.informatik.ct.persistence.services.RoomService; import de.hs_mannheim.informatik.ct.persistence.services.RoomVisitService; import de.hs_mannheim.informatik.ct.persistence.services.VisitorService; import lombok.val; import lombok.extern.slf4j.Slf4j; @Controller @RequestMapping("/r") @Slf4j public class RoomController { @Autowired private RoomService roomService; @Autowired private VisitorService visitorService; @Autowired private RoomVisitService roomVisitService; @Value("${allow_full_room_checkIn:false}") private boolean allowFullRoomCheckIn; @Value("${warning_for_full_room:true}") private boolean warningForFullRoom; /** * Shows the check-in form page for the given room. * * @param roomId The room id of the room. * @param roomIdFromRequest The room id as a request param for the search function. RoomId has to be set to 'noId'. * @param overrideFullRoom Shows the form even if the room is full. * @param model The Spring model param. * @return A spring template string. */ // TODO: Can we handle rooms with non ASCII names? @GetMapping("/{roomId}") public String checkIn(@PathVariable String roomId, @RequestParam(required = false, value = "roomId") Optional<String> roomIdFromRequest, @RequestParam(required = false, defaultValue = "false") Boolean privileged, @RequestParam(required = false, value = "pin") Optional<String> roomPinFromRequest, @RequestParam(required = false, value = "override", defaultValue = "false") boolean overrideFullRoom, Model model) throws InvalidRoomPinException { if (!allowFullRoomCheckIn) { overrideFullRoom = false; } // get room by room id if ("noId".equals(roomId) && roomIdFromRequest.isPresent()) roomId = roomIdFromRequest.get(); val room = roomService.getRoomOrThrow(roomId); // check room pin String roomPin = ""; Boolean roomPinSet = true; if (roomPinFromRequest.isPresent() && !roomPinFromRequest.get().isEmpty()){ roomPin = roomPinFromRequest.get(); if (!(roomPin.equals(room.getRoomPin()))) { throw new InvalidRoomPinException(); } } else { roomPinSet = false; } if (warningForFullRoom && !overrideFullRoom && roomVisitService.isRoomFull(room)) { return "forward:roomFull/" + room.getId(); } Room.Data roomData = new Room.Data(room); model.addAttribute("room", room); model.addAttribute("visitorCount", roomVisitService.getVisitorCount(room)); model.addAttribute("roomData", roomData); model.addAttribute("visitData", new RoomVisit.Data(roomData)); model.addAttribute("privileged", privileged); model.addAttribute("roomPin", roomPin); model.addAttribute("checkInOverwrite", overrideFullRoom); model.addAttribute("roomPinSet", roomPinSet); log.debug("forwarding to check-in page with room data: " + roomData.toString()); return "rooms/checkIn"; } @PostMapping("/checkIn") @Transactional public String checkIn(@ModelAttribute RoomVisit.Data visitData, Model model) throws UnsupportedEncodingException, InvalidRoomPinException, InvalidEmailException, InvalidExternalUserdataException { isRoomPinValidOrThrow(visitData); val room = roomService.getRoomOrThrow(visitData.getRoomId()); val visitorEmail = visitData.getVisitorEmail(); val visitor = getOrCreateVisitorOrThrow(visitorEmail, visitData.getName(), visitData.getNumber(), visitData.getAddress()); isRoomPinEqualOrThrow(visitData.getRoomPin(), room.getRoomPin()); val notCheckedOutVisits = roomVisitService.checkOutVisitor(visitor); // String autoCheckoutValue = null; // what was this about? if (notCheckedOutVisits.size() != 0) { val checkedOutRoom = notCheckedOutVisits.get(0).getRoom(); // autoCheckoutValue = checkedOutRoom.getName(); // If the user is automatically checked out of the same room they're trying to // check into, show them the checked out page instead (Auto checkout after scanning room qr code twice) if (room.getId().equals(checkedOutRoom.getId())) { log.debug("visitor checked out from same room via qr-code."); return "forward:checkedOut/"; } } if (!allowFullRoomCheckIn && roomVisitService.isRoomFull(room) && !visitData.isPrivileged()) { log.debug("room {} full!", room.getId()); return "forward:roomFull/" + room.getId(); } // room manager should always be allowed to check-in // and needs to be checked in before the browser is forwarded to a different page! val visit = roomVisitService.visitRoom(visitor, room); if (visitData.isPrivileged()) { val encodedVisitorEmail = URLEncoder.encode(visitorEmail, "UTF-8"); log.debug("privileged check-in to {}", room.getId()); return "redirect:/r/" + room.getId() + "/event-manager-portal?visitorEmail=" + encodedVisitorEmail; } val currentVisitCount = roomVisitService.getVisitorCount(room); visitData = new RoomVisit.Data(visit, currentVisitCount); model.addAttribute("visitData", visitData); return "rooms/checkedIn"; } private void isRoomPinEqualOrThrow(String sendRoomPin, String actualRoomPin) throws InvalidRoomPinException { if (!sendRoomPin.equals(actualRoomPin)) throw new InvalidRoomPinException(); } private void isRoomPinValidOrThrow(Data visitData) throws InvalidRoomPinException { val roomPin = visitData.getRoomPin(); if(roomPin == null || roomPin.isEmpty()) throw new InvalidRoomPinException(); try { Long.parseLong(roomPin); } catch (NumberFormatException err) { throw new InvalidRoomPinException(); } } /** * Check into a room even though it is full */ @PostMapping("/checkInOverride") @Transactional public String checkInWithOverride(@ModelAttribute RoomVisit.Data visitData, Model model) throws UnsupportedEncodingException, InvalidEmailException, InvalidExternalUserdataException, InvalidRoomPinException { // TODO: this method is very similar with the normal check-in, maybe this should be refactored? if (!allowFullRoomCheckIn) { throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Checking into a full room is not allowed"); } isRoomPinValidOrThrow(visitData); val visitorEmail = visitData.getVisitorEmail(); val room = roomService.getRoomOrThrow(visitData.getRoomId()); val visitor = getOrCreateVisitorOrThrow(visitorEmail, visitData.getName(), visitData.getNumber(), visitData.getAddress()); roomVisitService.checkOutVisitor(visitor); val visit = roomVisitService.visitRoom(visitor, room); val currentVisitCount = roomVisitService.getVisitorCount(room); visitData = new RoomVisit.Data(visit, currentVisitCount); model.addAttribute("visitData", visitData); return "rooms/checkedIn"; } @PostMapping("/checkOut") public String checkOut(@ModelAttribute RoomVisit.Data visitData) { val visitor = getVisitorOrThrow(visitData.getVisitorEmail()); roomVisitService.checkOutVisitor(visitor); return "redirect:/r/checkedOut"; } @GetMapping("/{roomId}/checkOut") public String checkoutPage(@PathVariable String roomId, Model model) { val room = roomService.getRoomOrThrow(roomId); Room.Data roomData = new Room.Data(room); model.addAttribute("room", room); model.addAttribute("checkout", true); model.addAttribute("roomData", roomData); model.addAttribute("visitData", new RoomVisit.Data(roomData)); model.addAttribute("privileged", false); return "rooms/checkIn"; } @GetMapping("/{roomId}/roomReset") public String roomReset(@PathVariable String roomId, Model model) { val room = roomService.getRoomOrThrow(roomId); Room.Data roomData = new Room.Data(room); model.addAttribute("roomData", roomData); return "rooms/roomReset"; } @GetMapping("/{roomId}/event-manager-portal") public String eventManagerPortal( @PathVariable String roomId, @RequestParam(required = true, value = "visitorEmail") String encodedVisitorEmail, Model model) throws UnsupportedEncodingException { val visitorEmail = URLDecoder.decode(encodedVisitorEmail, "UTF-8"); val room = roomService.getRoomOrThrow(roomId); val currentRoomVisitorCount = roomVisitService.getVisitorCount(room); val isRoomOvercrowded = room.getMaxCapacity() <= currentRoomVisitorCount; // why is this here? // val redirectURI = URLEncoder.encode("/r/" + roomId + "/event-manager-portal?visitorEmail=" + encodedVisitorEmail, "UTF-8"); val roomData = new Room.Data(room); model.addAttribute("roomData", roomData); model.addAttribute("currentRoomVisitorCount", currentRoomVisitorCount); model.addAttribute("isRoomOvercrowded", isRoomOvercrowded); model.addAttribute("visitorEmail", visitorEmail); return "rooms/veranstaltungsleitenden-portal"; } @PostMapping("/{roomId}/executeRoomReset") public String executeRoomReset( @PathVariable String roomId, Model model, @RequestParam(required = false, value = "redirectURI") Optional<String> redirectURIRequest) throws UnsupportedEncodingException { val room = roomService.getRoomOrThrow(roomId); String redirectURI = "/r/" + roomId + "?&privileged=true"; if (redirectURIRequest.isPresent()) redirectURI = URLDecoder.decode(redirectURIRequest.get(), "UTF-8"); roomVisitService.resetRoom(room); return "redirect:" + redirectURI; } @PostMapping(value = "/{roomId}/reset", produces = MediaType.APPLICATION_JSON_VALUE) public @ResponseBody RestResponse roomReset( @PathVariable String roomId, @RequestParam(required = true, value = "roomPin") Optional<String> roomPinRequested, Model model) { try { if (!roomPinRequested.isPresent()) throw new Exception("roomPin not found"); val roomPin = roomPinRequested.get(); val room = roomService.getRoomOrThrow(roomId); if(!room.getRoomPin().equals(roomPin)) throw new Exception("roomPin invalid"); roomVisitService.resetRoom(room); return new RestResponse(true); } catch (Exception e) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); } } public static class RestResponse { public String message; public boolean success; public RestResponse(boolean success) { this.success = success; } public RestResponse(boolean success, String message) { this(success); this.message = message; } } @RequestMapping("/roomFull/{roomId}") public String roomFull(@PathVariable String roomId, Model model) { val room = roomService.getRoomOrThrow(roomId); Room.Data roomData = new Room.Data(room); model.addAttribute("roomData", roomData); return "rooms/full"; } @RequestMapping("/checkedOut") public String checkedOutPage() { return "rooms/checkedOut"; } @GetMapping("/import") public String roomImport() { return "rooms/roomImport"; } @PostMapping("/import") public String roomTableImport(@RequestParam("file") MultipartFile file, Model model) { String fileName = file.getOriginalFilename(); String extension = fileName.substring(fileName.indexOf(".")); try (InputStream is = file.getInputStream()) { if (extension.equals(".csv")) roomService.importFromCsv(new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))); else if (extension.equals(".xlsm")) roomService.importFromExcel(is); else throw new InvalidFileUploadException(); } catch (IOException e) { e.printStackTrace(); } return "rooms/importCompleted"; } public static String getRoomCheckinPath(Room room) { return "r/" + room.getId(); } @ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Room not found") public static class RoomNotFoundException extends RuntimeException { } @ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Visitor not found") public static class VisitorNotFoundException extends RuntimeException { } @ResponseStatus(code = HttpStatus.UNSUPPORTED_MEDIA_TYPE, reason = "Not a supported filetype, only .csv or .xlsm will work!") public static class InvalidFileUploadException extends RuntimeException { } /** * Gets a visitor by email or throws a VisitorNotFoundException if a visitor with that email doesn't exist (yet). * * @param email The visitors email. * @return The visitor. */ private Visitor getVisitorOrThrow(String email) { Optional<Visitor> visitor = visitorService.findVisitorByEmail(email); if (!visitor.isPresent()) { throw new VisitorNotFoundException(); } return visitor.get(); } /** * Gets an existing visitor by email or creates a new one. Throws a 'bad request' ResponseStatusException if an InvalidEmailException is thrown. * * @param email The visitors email. * @return The visitor. */ private Visitor getOrCreateVisitorOrThrow(String email, String name, String number, String address) throws InvalidEmailException, InvalidExternalUserdataException { return visitorService.findOrCreateVisitor(email, name, number, address); } }
16,878
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
PrintOutController.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/controller/PrintOutController.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.controller; import java.io.IOException; import java.util.ArrayList; import java.util.zip.ZipOutputStream; import javax.servlet.http.HttpServletRequest; import org.apache.xmlbeans.XmlException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody; import de.hs_mannheim.informatik.ct.model.Room; import de.hs_mannheim.informatik.ct.persistence.services.BuildingService; import de.hs_mannheim.informatik.ct.persistence.services.DynamicContentService; import lombok.val; @Controller @RequestMapping("/printout") public class PrintOutController { @Autowired private BuildingService buildingService; @Autowired private DynamicContentService contentService; @Autowired private Utilities utilities; @Value("${server.port}") private String port; @Value("${hostname}") private String host; private int threadCount = 4; @GetMapping(value = "/rooms") public String getRoomPrintoutList(Model model) { return "rooms/roomPrintout"; } @RequestMapping(value = "/rooms/download") public ResponseEntity<StreamingResponseBody> getRoomPrintout(HttpServletRequest request, @RequestParam(value = "privileged") boolean privileged) { val allRooms = buildingService.getAllRooms(); System.out.println("Privileged: " + privileged+" | "+request.toString()); StreamingResponseBody responseBody = outputStream -> { try (val zos = new ZipOutputStream(outputStream)) { val listOfTheads = new ArrayList<Thread>(); for (int i = 0; i < threadCount; i++) { int counter = i; Thread t = new Thread(() -> { for (Room room : allRooms.subList(allRooms.size() * counter / threadCount, allRooms.size() * (counter + 1) / threadCount)) { try { contentService.addRoomPrintOutDocx( room, privileged, zos, uriToPath -> { val scheme = request.getScheme(); val localPath = RoomController.getRoomCheckinPath(room); if(privileged){ return utilities.getUriToLocalPath(scheme, localPath, "privileged=true"); }else{ return utilities.getUriToLocalPath(scheme, localPath); } } ); } catch (IOException e) { e.printStackTrace(); } catch (XmlException e) { e.printStackTrace(); } } } ); listOfTheads.add(t); t.start(); } for (Thread thread : listOfTheads) { thread.join(); } } catch (Exception e) { throw new RuntimeException(e); } }; if (privileged) { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"PrivilegedRoomNotes.zip\"") .header(HttpHeaders.CONTENT_TYPE, "application/zip") .body(responseBody); } else { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"RoomNotes.zip\"") .header(HttpHeaders.CONTENT_TYPE, "application/zip") .body(responseBody); } } }
5,268
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
InvalidRoomPinException.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/controller/exception/InvalidRoomPinException.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.controller.exception; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(code = HttpStatus.BAD_REQUEST, reason = "Invalid Pin") public class InvalidRoomPinException extends Exception { }
1,065
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
WebSecurityConfig.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/web/WebSecurityConfig.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.web; import java.util.Arrays; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.NoOpPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect; import lombok.val; import lombok.extern.slf4j.Slf4j; @Configuration @EnableWebSecurity @Slf4j public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Value("${server_env:production}") private String serverEnvironment; @Value("${user_credentials:#{null}}") private String credentialsEnv; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/besuch", "/templates/datenschutz.html").permitAll() .antMatchers("/neu", "/neuVer", "/veranstaltungen", "/templates/veranstaltungsliste.html").access("hasAnyRole('USER', 'PROF', 'ADMIN')") .mvcMatchers("/tracing/**").hasAnyRole("TRACER", "ADMIN") .antMatchers("/suche", "/suchen", "/liste", "/loeschen", "/download", "/h2-console/**", "/r/import", "/printout/rooms", "/printout/rooms/download").access("hasRole('ADMIN')") .and().formLogin().loginPage("/login").permitAll() .and().csrf().ignoringAntMatchers("/h2-console/**") .and().headers().frameOptions().sameOrigin(); } @Autowired public void globalSecurityConfiguration(AuthenticationManagerBuilder auth) throws Exception { if (isDevEnv()) { log.warn("Server is running in developer mode with default credentials!"); // Use plain text passwords for local development auth.inMemoryAuthentication().withUser("user").password("user").roles("USER"); auth.inMemoryAuthentication().withUser("prof").password("prof").roles("PROF"); auth.inMemoryAuthentication().withUser("admin").password("admin").roles("PROF", "ADMIN"); } else { if (credentialsEnv == null) { throw new RuntimeException("No credentials passed as environment variable."); } val userCredentials = credentialsEnv.split(";"); for (val credentials : userCredentials) { val tokens = credentials.split(","); val username = tokens[0]; val hashedPassword = tokens[1]; val roles = Arrays.copyOfRange(tokens, 2, tokens.length); auth.inMemoryAuthentication() .withUser(username) .password(hashedPassword) .roles(roles); log.info("Added user " + username); } } } @Bean public SpringSecurityDialect springSecurityDialect() { return new SpringSecurityDialect(); } @Bean public PasswordEncoder passwordEncoder() { if (isDevEnv()) { // The plain passwords are only used in the dev environment // noinspection deprecation return NoOpPasswordEncoder.getInstance(); } else { return new BCryptPasswordEncoder(); } } private boolean isDevEnv() { return serverEnvironment.equalsIgnoreCase("dev"); } }
4,667
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ScheduledMaintenanceTasks.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/util/ScheduledMaintenanceTasks.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.util; import java.time.LocalTime; import java.time.Period; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import de.hs_mannheim.informatik.ct.persistence.services.EventVisitService; import de.hs_mannheim.informatik.ct.persistence.services.RoomVisitService; import lombok.extern.slf4j.Slf4j; /** * Schedules maintenance queries such as signing out visitors at the end of the day and deleting expired personal data */ @Component @Slf4j public class ScheduledMaintenanceTasks { @Autowired private RoomVisitService roomVisitService; @Autowired private EventVisitService eventVisitService; private final int CRON_HOUR = 3; private final int CRON_MINUTE = 55; private final String FORCED_END_TIME = "00:00:00"; //@Scheduled(fixedRate = 5 * 60 * 1000) // Every 5 Minutes @Scheduled(cron = "0 " + CRON_MINUTE + " " + CRON_HOUR + " * * *") // 3:55 AM public void doMaintenance() { log.info("Auto-Checkout and deletion of old records triggered."); signOutAllVisitors(LocalTime.parse(FORCED_END_TIME)); deleteExpiredVisitRecords(Period.ofWeeks(4)); } public void signOutAllVisitors(LocalTime forcedEndTime) { roomVisitService.checkOutAllVisitors(forcedEndTime); } public void deleteExpiredVisitRecords(Period recordLifeTime) { eventVisitService.deleteExpiredRecords(recordLifeTime); roomVisitService.deleteExpiredRecords(recordLifeTime); } }
2,396
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
ContactListGenerator.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/util/ContactListGenerator.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.util; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.function.Function; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import de.hs_mannheim.informatik.ct.model.Contact; import de.hs_mannheim.informatik.ct.persistence.services.DateTimeService; import lombok.val; import lombok.var; public class ContactListGenerator { private final DateTimeService dateTimeService; private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy, HH:mm", Locale.GERMANY); private final String sheetName = "Kontaktliste"; private final int columnWidth = 30 * 256; private final Function<String, String> headerText = email -> String.format("Mögliche Kontakte von %s an der Hochschule Mannheim", email); private final Function<LocalDateTime, String> timestampText = (timestamp) -> String.format("Stand: %s", dateTimeFormatter.format(timestamp)); private final List<String> tableHeadings; private final List<Function<Contact<?>, String>> tableCellValues; private final String footerNotice = "Erstellt mit CTT, dem Corona Tracking Tool der Hochschule Mannheim"; private final FontStyler headerFontStyler = font -> font.setFontHeightInPoints((short) 16); private final FontStyler timeStampStyler = font -> font.setItalic(true); private final FontStyler tableHeadingsStyler = font -> font.setBold(true); private final FontStyler footerStyler = font -> font.setItalic(true); private final FontStyler contactStyler = font -> { val redColorCode = (short) 10; font.setBold(true); font.setColor(redColorCode); }; public ContactListGenerator(DateTimeService dateTimeService, List<String> tableHeadings, List<Function<Contact<?>, String>> tableCellValues) { this.dateTimeService = dateTimeService; this.tableHeadings = tableHeadings; this.tableCellValues = tableCellValues; } public Workbook generateWorkbook(Iterable<Contact<?>> contacts, String targetEmail) { val workbook = new XSSFWorkbook(); val sheet = workbook.createSheet(sheetName); writeText(appendRow(sheet), headerText.apply(targetEmail), styleWithFont(workbook, headerFontStyler)); writeText(appendRow(sheet), timestampText.apply(dateTimeService.getNow()), styleWithFont(workbook, timeStampStyler)); appendRow(sheet); writeCells(appendRow(sheet), tableHeadings, styleWithFont(workbook, tableHeadingsStyler)); writeContacts(contacts, targetEmail, workbook, sheet); appendRow(sheet); writeText(appendRow(sheet), footerNotice, styleWithFont(workbook, footerStyler)); for (int columnIndex = 0; columnIndex < tableHeadings.size(); columnIndex++) { sheet.setColumnWidth(columnIndex, this.columnWidth); } return workbook; } private void writeContacts(Iterable<Contact<?>> contacts, String targetEmail, Workbook workbook, Sheet sheet) { val defaultStyle = workbook.createCellStyle(); val contactStyle = styleWithFont(workbook, contactStyler); for (val contact : contacts) { var rowStyle = defaultStyle; if (targetEmail.equals(contact.getTarget().getEmail())) { rowStyle = contactStyle; } writeCells( appendRow(sheet), applyTextGenerators(contact, tableCellValues), defaultStyle ); } } private static void writeText(Row row, String headerText, CellStyle style) { val cell = row.createCell(0); cell.setCellValue(headerText); cell.setCellStyle(style); } private static void writeCells(Row row, Iterable<String> cellTexts, CellStyle style) { var cellIndex = 0; for (val cellText : cellTexts) { val cell = row.createCell(cellIndex++); cell.setCellValue(cellText); cell.setCellStyle(style); } } private static <T> Iterable<String> applyTextGenerators(T data, Iterable<Function<T, String>> generators) { val texts = new ArrayList<String>(); for (val generator : generators) { texts.add(generator.apply(data)); } return texts; } private static Row appendRow(Sheet sheet) { return sheet.createRow(sheet.getLastRowNum() + 1); } private static CellStyle styleWithFont(Workbook workbook, FontStyler fontStyler) { val font = workbook.createFont(); val style = workbook.createCellStyle(); fontStyler.style(font); style.setFont(font); return style; } private interface FontStyler { void style(Font font); } }
5,876
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z
TimeUtil.java
/FileExtraction/Java_unseen/informatik-mannheim_HSMA-CTT/src/main/java/de/hs_mannheim/informatik/ct/util/TimeUtil.java
/* * Corona Tracking Tool der Hochschule Mannheim * Copyright (c) 2021 Hochschule Mannheim * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package de.hs_mannheim.informatik.ct.util; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.util.Date; public class TimeUtil { public static LocalDate convertToLocalDate(Date date) { return date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate(); } public static LocalTime convertToLocalTime(Date date) { return date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalTime(); } public static LocalDateTime convertToLocalDateTime(Date date) { return date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDateTime(); } public static Date convertToDate(LocalDateTime dateTime) { return java.sql.Timestamp.valueOf(dateTime); } }
1,645
Java
.java
informatik-mannheim/HSMA-CTT
12
2
40
2020-12-18T16:46:41Z
2024-02-21T00:00:36Z