[BAEL-9555] - Created a core-java-modules folder
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
package com.baeldung.encoderdecoder;
|
||||
|
||||
import static java.util.stream.Collectors.joining;
|
||||
import static org.hamcrest.CoreMatchers.is;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import org.hamcrest.CoreMatchers;
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.util.UriUtils;
|
||||
|
||||
public class EncoderDecoderUnitTest {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
|
||||
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
|
||||
private static final String testUrlWithPath = "http://www.baeldung.com/path+1?key1=value+1&key2=value%40%21%242&key3=value%253";
|
||||
|
||||
private String encodeValue(String value) {
|
||||
String encoded = null;
|
||||
try {
|
||||
encoded = URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||
}
|
||||
return encoded;
|
||||
}
|
||||
|
||||
private String decode(String value) {
|
||||
String decoded = null;
|
||||
try {
|
||||
decoded = URLDecoder.decode(value, StandardCharsets.UTF_8.toString());
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
|
||||
URL url = new URL(testUrl);
|
||||
|
||||
Assert.assertThat(url.getProtocol(), is("http"));
|
||||
Assert.assertThat(url.getHost(), is("www.baeldung.com"));
|
||||
Assert.assertThat(url.getQuery(), is("key1=value+1&key2=value%40%21%242&key3=value%253"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
|
||||
Map<String, String> requestParams = new HashMap<>();
|
||||
requestParams.put("key1", "value 1");
|
||||
requestParams.put("key2", "value@!$2");
|
||||
requestParams.put("key3", "value%3");
|
||||
|
||||
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com?", ""));
|
||||
|
||||
Assert.assertThat(testUrl, is(encodedURL));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
|
||||
URL url = new URL(testUrl);
|
||||
|
||||
String query = url.getQuery();
|
||||
|
||||
String decodedQuery = Arrays.stream(query.split("&")).map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1])).collect(joining("&"));
|
||||
|
||||
Assert.assertEquals("http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
|
||||
}
|
||||
|
||||
private String encodePath(String path) {
|
||||
try {
|
||||
path = UriUtils.encodePath(path, "UTF-8");
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
LOGGER.error("Error encoding parameter {}", e.getMessage(), e);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathSegment_thenEncodeDecode() throws UnsupportedEncodingException {
|
||||
String pathSegment = "/Path 1/Path+2";
|
||||
String encodedPathSegment = encodePath(pathSegment);
|
||||
String decodedPathSegment = UriUtils.decode(encodedPathSegment, "UTF-8");
|
||||
Assert.assertEquals("/Path%201/Path+2", encodedPathSegment);
|
||||
Assert.assertEquals("/Path 1/Path+2", decodedPathSegment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPathAndRequestParam_whenUTF8Scheme_thenEncode() throws Exception {
|
||||
Map<String, String> requestParams = new HashMap<>();
|
||||
requestParams.put("key1", "value 1");
|
||||
requestParams.put("key2", "value@!$2");
|
||||
requestParams.put("key3", "value%3");
|
||||
|
||||
String path = "path+1";
|
||||
|
||||
String encodedURL = requestParams.keySet().stream().map(key -> key + "=" + encodeValue(requestParams.get(key))).collect(joining("&", "http://www.baeldung.com/" + encodePath(path) + "?", ""));
|
||||
|
||||
Assert.assertThat(testUrlWithPath, is(encodedURL));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.baeldung.http;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.DataOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.Reader;
|
||||
import java.net.CookieManager;
|
||||
import java.net.HttpCookie;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
public class HttpRequestLiveTest {
|
||||
|
||||
@Test
|
||||
public void whenGetRequest_thenOk() throws IOException {
|
||||
URL url = new URL("http://example.com");
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
|
||||
Map<String, String> parameters = new HashMap<>();
|
||||
parameters.put("param1", "val");
|
||||
con.setDoOutput(true);
|
||||
DataOutputStream out = new DataOutputStream(con.getOutputStream());
|
||||
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
|
||||
out.flush();
|
||||
out.close();
|
||||
|
||||
con.setConnectTimeout(5000);
|
||||
con.setReadTimeout(5000);
|
||||
|
||||
int status = con.getResponseCode();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
||||
String inputLine;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
content.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
assertEquals("status code incorrect", status, 200);
|
||||
assertTrue("content incorrect", content.toString()
|
||||
.contains("Example Domain"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPostRequest_thenOk() throws IOException {
|
||||
URL url = new URL("http://example.com");
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("POST");
|
||||
con.setRequestProperty("Content-Type", "application/json");
|
||||
|
||||
Map<String, String> parameters = new HashMap<>();
|
||||
parameters.put("param1", "val");
|
||||
con.setDoOutput(true);
|
||||
DataOutputStream out = new DataOutputStream(con.getOutputStream());
|
||||
out.writeBytes(ParameterStringBuilder.getParamsString(parameters));
|
||||
out.flush();
|
||||
out.close();
|
||||
|
||||
int status = con.getResponseCode();
|
||||
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
||||
String inputLine;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
content.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
assertEquals("status code incorrect", status, 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetCookies_thenOk() throws IOException {
|
||||
URL url = new URL("http://example.com");
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
|
||||
CookieManager cookieManager = new CookieManager();
|
||||
String cookiesHeader = con.getHeaderField("Set-Cookie");
|
||||
Optional<HttpCookie> usernameCookie = null;
|
||||
if (cookiesHeader != null) {
|
||||
List<HttpCookie> cookies = HttpCookie.parse(cookiesHeader);
|
||||
cookies.forEach(cookie -> cookieManager.getCookieStore()
|
||||
.add(null, cookie));
|
||||
usernameCookie = cookies.stream()
|
||||
.findAny()
|
||||
.filter(cookie -> cookie.getName()
|
||||
.equals("username"));
|
||||
}
|
||||
|
||||
if (usernameCookie == null) {
|
||||
cookieManager.getCookieStore()
|
||||
.add(null, new HttpCookie("username", "john"));
|
||||
}
|
||||
|
||||
con.disconnect();
|
||||
|
||||
con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestProperty("Cookie", StringUtils.join(cookieManager.getCookieStore()
|
||||
.getCookies(), ";"));
|
||||
|
||||
int status = con.getResponseCode();
|
||||
|
||||
assertEquals("status code incorrect", status, 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRedirect_thenOk() throws IOException {
|
||||
URL url = new URL("http://example.com");
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
|
||||
con.setInstanceFollowRedirects(true);
|
||||
int status = con.getResponseCode();
|
||||
|
||||
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM) {
|
||||
String location = con.getHeaderField("Location");
|
||||
URL newUrl = new URL(location);
|
||||
con = (HttpURLConnection) newUrl.openConnection();
|
||||
}
|
||||
|
||||
assertEquals("status code incorrect", con.getResponseCode(), 200);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFailedRequest_thenOk() throws IOException {
|
||||
URL url = new URL("http://example.com");
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("POST");
|
||||
|
||||
con.setConnectTimeout(5000);
|
||||
con.setReadTimeout(5000);
|
||||
|
||||
int status = con.getResponseCode();
|
||||
|
||||
Reader streamReader = null;
|
||||
|
||||
if (status > 299) {
|
||||
streamReader = new InputStreamReader(con.getErrorStream());
|
||||
} else {
|
||||
streamReader = new InputStreamReader(con.getInputStream());
|
||||
}
|
||||
|
||||
BufferedReader in = new BufferedReader(streamReader);
|
||||
String inputLine;
|
||||
StringBuilder content = new StringBuilder();
|
||||
while ((inputLine = in.readLine()) != null) {
|
||||
content.append(inputLine);
|
||||
}
|
||||
in.close();
|
||||
|
||||
con.disconnect();
|
||||
|
||||
assertEquals("status code incorrect", status, 411);
|
||||
assertTrue("error content", content.toString()
|
||||
.contains("411 - Length Required"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetRequestFullResponse_thenOk() throws IOException {
|
||||
URL url = new URL("http://example.com");
|
||||
HttpURLConnection con = (HttpURLConnection) url.openConnection();
|
||||
con.setRequestMethod("GET");
|
||||
|
||||
con.setConnectTimeout(5000);
|
||||
con.setReadTimeout(5000);
|
||||
|
||||
String fullResponse = FullResponseBuilder.getFullResponse(con);
|
||||
|
||||
con.disconnect();
|
||||
|
||||
assertEquals("status code incorrect", con.getResponseCode(), 200);
|
||||
assertTrue("header incorrect", fullResponse.contains("Content-Type: text/html; charset=UTF-8"));
|
||||
assertTrue("response incorrect", fullResponse.contains("<!doctype html><html><head>"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package com.baeldung.networking.interfaces;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.*;
|
||||
import java.util.Enumeration;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class NetworkInterfaceManualTest {
|
||||
@Test
|
||||
public void givenName_whenReturnsNetworkInterface_thenCorrect() throws SocketException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInExistentName_whenReturnsNull_thenCorrect() throws SocketException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("inexistent_name");
|
||||
assertNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIP_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
byte[] ip = new byte[] { 127, 0, 0, 1 };
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByAddress(ip));
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenHostName_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getByName("localhost"));
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalHost_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLocalHost());
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLoopBack_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByInetAddress(InetAddress.getLoopbackAddress());
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenIndex_whenReturnsNetworkInterface_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByIndex(0);
|
||||
assertNotNull(nif);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenReturnsInetAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
Enumeration<InetAddress> addressEnum = nif.getInetAddresses();
|
||||
InetAddress address = addressEnum.nextElement();
|
||||
assertEquals("127.0.0.1", address.getHostAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenReturnsInterfaceAddresses_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
|
||||
List<InterfaceAddress> addressEnum = nif.getInterfaceAddresses();
|
||||
InterfaceAddress address = addressEnum.get(0);
|
||||
InetAddress localAddress = address.getAddress();
|
||||
InetAddress broadCastAddress = address.getBroadcast();
|
||||
assertEquals("127.0.0.1", localAddress.getHostAddress());
|
||||
assertEquals("127.255.255.255", broadCastAddress.getHostAddress());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfLoopback_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.isLoopback());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfUp_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.isUp());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfPointToPoint_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertFalse(nif.isPointToPoint());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksIfVirtual_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertFalse(nif.isVirtual());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenChecksMulticastSupport_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
assertTrue(nif.supportsMulticast());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenGetsMacAddress_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("lo");
|
||||
byte[] bytes = nif.getHardwareAddress();
|
||||
assertNotNull(bytes);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenInterface_whenGetsMTU_thenCorrect() throws SocketException, UnknownHostException {
|
||||
NetworkInterface nif = NetworkInterface.getByName("net0");
|
||||
int mtu = nif.getMTU();
|
||||
assertEquals(1500, mtu);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.baeldung.networking.udp;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
|
||||
public class UDPLiveTest {
|
||||
private EchoClient client;
|
||||
|
||||
@Before
|
||||
public void setup() throws IOException {
|
||||
new EchoServer().start();
|
||||
client = new EchoClient();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCanSendAndReceivePacket_thenCorrect1() {
|
||||
String echo = client.sendEcho("hello server");
|
||||
assertEquals("hello server", echo);
|
||||
echo = client.sendEcho("server is working");
|
||||
assertFalse(echo.equals("hello server"));
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
stopEchoServer();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private void stopEchoServer() {
|
||||
client.sendEcho("end");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.networking.udp.broadcast;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class BroadcastLiveTest {
|
||||
private BroadcastingClient client;
|
||||
|
||||
@Test
|
||||
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
|
||||
int expectedServers = 4;
|
||||
initializeForExpectedServers(expectedServers);
|
||||
|
||||
int serversDiscovered = client.discoverServers("hello server");
|
||||
assertEquals(expectedServers, serversDiscovered);
|
||||
}
|
||||
|
||||
private void initializeForExpectedServers(int expectedServers) throws Exception {
|
||||
for (int i = 0; i < expectedServers; i++) {
|
||||
new BroadcastingEchoServer().start();
|
||||
}
|
||||
|
||||
client = new BroadcastingClient(expectedServers);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws IOException {
|
||||
stopEchoServer();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private void stopEchoServer() throws IOException {
|
||||
client.discoverServers("end");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.baeldung.networking.udp.multicast;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class MulticastLiveTest {
|
||||
private MulticastingClient client;
|
||||
|
||||
@Test
|
||||
public void whenBroadcasting_thenDiscoverExpectedServers() throws Exception {
|
||||
int expectedServers = 4;
|
||||
initializeForExpectedServers(expectedServers);
|
||||
|
||||
int serversDiscovered = client.discoverServers("hello server");
|
||||
assertEquals(expectedServers, serversDiscovered);
|
||||
}
|
||||
|
||||
private void initializeForExpectedServers(int expectedServers) throws Exception {
|
||||
for (int i = 0; i < expectedServers; i++) {
|
||||
new MulticastEchoServer().start();
|
||||
}
|
||||
|
||||
client = new MulticastingClient(expectedServers);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() throws IOException {
|
||||
stopEchoServer();
|
||||
client.close();
|
||||
}
|
||||
|
||||
private void stopEchoServer() throws IOException {
|
||||
client.discoverServers("end");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.baeldung.networking.uriurl;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.networking.uriurl.URLDemo;
|
||||
|
||||
@FixMethodOrder
|
||||
public class URIDemoLiveTest {
|
||||
private final Logger log = LoggerFactory.getLogger(URIDemoLiveTest.class);
|
||||
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
static String URISCHEME = "https";
|
||||
String URISCHEMESPECIFIC;
|
||||
static String URIHOST = "wordpress.org";
|
||||
static String URIAUTHORITY = "wordpress.org:443";
|
||||
|
||||
static String URIPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
int URIPORT = 443;
|
||||
static int URIDEFAULTPORT = 443;
|
||||
static String URIQUERY = "replies=3";
|
||||
static String URIFRAGMENT = "post-2278484";
|
||||
static String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIDEFAULTPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
|
||||
|
||||
static URI uri;
|
||||
URL url;
|
||||
BufferedReader in = null;
|
||||
String URIContent = "";
|
||||
|
||||
@BeforeClass
|
||||
public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws URISyntaxException {
|
||||
uri = new URI(URICOMPOUND);
|
||||
}
|
||||
|
||||
// check parsed URL
|
||||
@Test
|
||||
public void givenURI_whenURIIsParsed_thenSuccess() {
|
||||
assertNotNull("URI is null", uri);
|
||||
assertEquals("URI string is not equal", uri.toString(), URISTRING);
|
||||
assertEquals("Scheme is not equal", uri.getScheme(), URISCHEME);
|
||||
assertEquals("Authority is not equal", uri.getAuthority(), URIAUTHORITY);
|
||||
assertEquals("Host string is not equal", uri.getHost(), URIHOST);
|
||||
assertEquals("Path string is not equal", uri.getPath(), URIPATH);
|
||||
assertEquals("Port number is not equal", uri.getPort(), URIPORT);
|
||||
assertEquals("Query string is not equal", uri.getQuery(), URIQUERY);
|
||||
assertEquals("Fragment string is not equal", uri.getFragment(), URIFRAGMENT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baeldung.networking.uriurl;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.net.URL;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import static org.junit.Assert.*;
|
||||
import org.junit.Test;
|
||||
|
||||
public class URIvsURLUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenCreatingURIs_thenSameInfo() throws URISyntaxException {
|
||||
URI firstURI = new URI("somescheme://theuser:thepassword@someauthority:80/some/path?thequery#somefragment");
|
||||
URI secondURI = new URI("somescheme", "theuser:thepassword", "someuthority", 80, "/some/path", "thequery", "somefragment");
|
||||
|
||||
assertEquals(firstURI.getScheme(), secondURI.getScheme());
|
||||
assertEquals(firstURI.getPath(), secondURI.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingURLs_thenSameInfo() throws MalformedURLException {
|
||||
URL firstURL = new URL("http://theuser:thepassword@somehost:80/path/to/file?thequery#somefragment");
|
||||
URL secondURL = new URL("http", "somehost", 80, "/path/to/file");
|
||||
|
||||
assertEquals(firstURL.getHost(), secondURL.getHost());
|
||||
assertEquals(firstURL.getPath(), secondURL.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingURI_thenCorrect() {
|
||||
URI uri = URI.create("urn:isbn:1234567890");
|
||||
|
||||
assertNotNull(uri);
|
||||
}
|
||||
|
||||
@Test(expected = MalformedURLException.class)
|
||||
public void whenCreatingURLs_thenException() throws MalformedURLException {
|
||||
URL theURL = new URL("otherprotocol://somehost/path/to/file");
|
||||
|
||||
assertNotNull(theURL);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenObjects_whenConverting_thenCorrect() throws MalformedURLException, URISyntaxException {
|
||||
String aURIString = "http://somehost:80/path?thequery";
|
||||
URI uri = new URI(aURIString);
|
||||
URL url = new URL(aURIString);
|
||||
|
||||
URL toURL = uri.toURL();
|
||||
URI toURI = url.toURI();
|
||||
|
||||
assertNotNull(url);
|
||||
assertNotNull(uri);
|
||||
assertEquals(toURL.toString(), toURI.toString());
|
||||
}
|
||||
|
||||
@Test(expected = MalformedURLException.class)
|
||||
public void givenURI_whenConvertingToURL_thenException() throws MalformedURLException, URISyntaxException {
|
||||
URI uri = new URI("somescheme://someauthority/path?thequery");
|
||||
|
||||
URL url = uri.toURL();
|
||||
|
||||
assertNotNull(url);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenURL_whenGettingContents_thenCorrect() throws MalformedURLException, IOException {
|
||||
URL url = new URL("http://courses.baeldung.com");
|
||||
|
||||
String contents = IOUtils.toString(url.openStream());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.baeldung.networking.uriurl;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
import java.net.URLConnection;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.FixMethodOrder;
|
||||
import org.junit.Test;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.baeldung.networking.uriurl.URLDemo;
|
||||
|
||||
@FixMethodOrder
|
||||
public class URLDemoLiveTest {
|
||||
private final Logger log = LoggerFactory.getLogger(URLDemoLiveTest.class);
|
||||
static String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
|
||||
// parsed locator
|
||||
static String URLPROTOCOL = "https";
|
||||
String URLAUTHORITY = "wordpress.org:443";
|
||||
static String URLHOST = "wordpress.org";
|
||||
static String URLPATH = "/support/topic/page-jumps-within-wordpress/";
|
||||
String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
|
||||
int URLPORT = 443;
|
||||
static int URLDEFAULTPORT = 443;
|
||||
static String URLQUERY = "replies=3";
|
||||
static String URLREFERENCE = "post-2278484";
|
||||
static String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
|
||||
|
||||
static URL url;
|
||||
URLConnection urlConnection = null;
|
||||
HttpURLConnection connection = null;
|
||||
BufferedReader in = null;
|
||||
String urlContent = "";
|
||||
|
||||
@BeforeClass
|
||||
public static void givenEmplyURL_whenInitializeURL_thenSuccess() throws MalformedURLException {
|
||||
url = new URL(URLCOMPOUND);
|
||||
}
|
||||
|
||||
// check parsed URL
|
||||
@Test
|
||||
public void givenURL_whenURLIsParsed_thenSuccess() {
|
||||
assertNotNull("URL is null", url);
|
||||
assertEquals("URL string is not equal", url.toString(), URLSTRING);
|
||||
assertEquals("Protocol is not equal", url.getProtocol(), URLPROTOCOL);
|
||||
assertEquals("Authority is not equal", url.getAuthority(), URLAUTHORITY);
|
||||
assertEquals("Host string is not equal", url.getHost(), URLHOST);
|
||||
assertEquals("Path string is not equal", url.getPath(), URLPATH);
|
||||
assertEquals("File string is not equal", url.getFile(), URLFILENAME);
|
||||
assertEquals("Port number is not equal", url.getPort(), URLPORT);
|
||||
assertEquals("Default port number is not equal", url.getDefaultPort(), URLDEFAULTPORT);
|
||||
assertEquals("Query string is not equal", url.getQuery(), URLQUERY);
|
||||
assertEquals("Reference string is not equal", url.getRef(), URLREFERENCE);
|
||||
}
|
||||
|
||||
// Obtain the content from location
|
||||
@Test
|
||||
public void givenURL_whenOpenConnectionAndContentIsNotEmpty_thenSuccess() throws IOException {
|
||||
try {
|
||||
urlConnection = url.openConnection();
|
||||
} catch (IOException ex) {
|
||||
urlConnection = null;
|
||||
ex.printStackTrace();
|
||||
}
|
||||
assertNotNull("URL Connection is null", urlConnection);
|
||||
|
||||
connection = null;
|
||||
assertTrue("URLConnection is not HttpURLConnection", urlConnection instanceof HttpURLConnection);
|
||||
if (urlConnection instanceof HttpURLConnection) {
|
||||
connection = (HttpURLConnection) urlConnection;
|
||||
}
|
||||
assertNotNull("Connection is null", connection);
|
||||
|
||||
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
|
||||
|
||||
try {
|
||||
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
} catch (IOException ex) {
|
||||
in = null;
|
||||
ex.printStackTrace();
|
||||
}
|
||||
assertNotNull("Input stream failed", in);
|
||||
|
||||
String current;
|
||||
try {
|
||||
while ((current = in.readLine()) != null) {
|
||||
urlContent += current;
|
||||
}
|
||||
} catch (IOException ex) {
|
||||
urlContent = null;
|
||||
ex.printStackTrace();
|
||||
}
|
||||
assertNotNull("Content is null", urlContent);
|
||||
assertTrue("Content is empty", urlContent.length() > 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.baeldung.networking.url;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class UrlUnitTest {
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com");
|
||||
assertEquals("http", url.getProtocol());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com");
|
||||
assertEquals("baeldung.com", url.getHost());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
|
||||
assertEquals("/articles?topic=java&version=8", url.getFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com/guidelines.txt");
|
||||
assertEquals("/guidelines.txt", url.getFile());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
|
||||
assertEquals("/articles", url.getPath());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com/articles?topic=java");
|
||||
assertEquals("topic=java", url.getQuery());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com");
|
||||
assertEquals(-1, url.getPort());
|
||||
assertEquals(80, url.getDefaultPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
|
||||
final URL url = new URL("http://baeldung.com:8090");
|
||||
assertEquals(8090, url.getPort());
|
||||
assertEquals(80, url.getDefaultPort());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
|
||||
final URL baseUrl = new URL("http://baeldung.com");
|
||||
final URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
|
||||
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
|
||||
final URL baseUrl = new URL("http://baeldung.com");
|
||||
final URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
|
||||
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
|
||||
final String protocol = "http";
|
||||
final String host = "baeldung.com";
|
||||
final String file = "/guidelines.txt";
|
||||
final URL url = new URL(protocol, host, file);
|
||||
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
|
||||
final String protocol = "http";
|
||||
final String host = "baeldung.com";
|
||||
final String file = "/articles?topic=java&version=8";
|
||||
final URL url = new URL(protocol, host, file);
|
||||
assertEquals("http://baeldung.com/articles?topic=java&version=8", url.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
|
||||
final String protocol = "http";
|
||||
final String host = "baeldung.com";
|
||||
final int port = 9000;
|
||||
final String file = "/guidelines.txt";
|
||||
final URL url = new URL(protocol, host, port, file);
|
||||
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class EchoIntegrationTest {
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor()
|
||||
.submit(() -> new EchoServer().start(port));
|
||||
Thread.sleep(500);
|
||||
}
|
||||
|
||||
private EchoClient client = new EchoClient();
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client.startConnection("127.0.0.1", port);
|
||||
}
|
||||
|
||||
@After
|
||||
public void tearDown() {
|
||||
client.stopConnection();
|
||||
}
|
||||
|
||||
//
|
||||
|
||||
@Test
|
||||
public void givenClient_whenServerEchosMessage_thenCorrect() {
|
||||
String resp1 = client.sendMessage("hello");
|
||||
String resp2 = client.sendMessage("world");
|
||||
String resp3 = client.sendMessage("!");
|
||||
String resp4 = client.sendMessage(".");
|
||||
assertEquals("hello", resp1);
|
||||
assertEquals("world", resp2);
|
||||
assertEquals("!", resp3);
|
||||
assertEquals("good bye", resp4);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import org.junit.After;
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
|
||||
public class GreetServerIntegrationTest {
|
||||
|
||||
private GreetClient client;
|
||||
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor()
|
||||
.submit(() -> new GreetServer().start(port));
|
||||
Thread.sleep(500);
|
||||
}
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
client = new GreetClient();
|
||||
client.startConnection("127.0.0.1", port);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGreetingClient_whenServerRespondsWhenStarted_thenCorrect() {
|
||||
String response = client.sendMessage("hello server");
|
||||
assertEquals("hello client", response);
|
||||
}
|
||||
|
||||
@After
|
||||
public void finish() {
|
||||
client.stopConnection();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.baeldung.socket;
|
||||
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Ignore;
|
||||
import org.junit.Test;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.ServerSocket;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class SocketEchoMultiIntegrationTest {
|
||||
|
||||
private static int port;
|
||||
|
||||
@BeforeClass
|
||||
public static void start() throws InterruptedException, IOException {
|
||||
|
||||
// Take an available port
|
||||
ServerSocket s = new ServerSocket(0);
|
||||
port = s.getLocalPort();
|
||||
s.close();
|
||||
|
||||
Executors.newSingleThreadExecutor().submit(() -> new EchoMultiServer().start(port));
|
||||
Thread.sleep(500);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClient1_whenServerResponds_thenCorrect() {
|
||||
EchoClient client = new EchoClient();
|
||||
client.startConnection("127.0.0.1", port);
|
||||
String msg1 = client.sendMessage("hello");
|
||||
String msg2 = client.sendMessage("world");
|
||||
String terminate = client.sendMessage(".");
|
||||
|
||||
assertEquals(msg1, "hello");
|
||||
assertEquals(msg2, "world");
|
||||
assertEquals(terminate, "bye");
|
||||
client.stopConnection();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClient2_whenServerResponds_thenCorrect() {
|
||||
EchoClient client = new EchoClient();
|
||||
client.startConnection("127.0.0.1", port);
|
||||
String msg1 = client.sendMessage("hello");
|
||||
String msg2 = client.sendMessage("world");
|
||||
String terminate = client.sendMessage(".");
|
||||
assertEquals(msg1, "hello");
|
||||
assertEquals(msg2, "world");
|
||||
assertEquals(terminate, "bye");
|
||||
client.stopConnection();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClient3_whenServerResponds_thenCorrect() {
|
||||
EchoClient client = new EchoClient();
|
||||
client.startConnection("127.0.0.1", port);
|
||||
String msg1 = client.sendMessage("hello");
|
||||
String msg2 = client.sendMessage("world");
|
||||
String terminate = client.sendMessage(".");
|
||||
assertEquals(msg1, "hello");
|
||||
assertEquals(msg2, "world");
|
||||
assertEquals(terminate, "bye");
|
||||
client.stopConnection();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.socket.read;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
public class SocketReadAllDataLiveTest {
|
||||
|
||||
@Test
|
||||
public void givenServerAndClient_whenClientSendsAndServerReceivesData_thenCorrect() {
|
||||
//Run server in new thread
|
||||
Runnable runnable1 = () -> { runServer(); };
|
||||
Thread thread1 = new Thread(runnable1);
|
||||
thread1.start();
|
||||
//Wait for 10 seconds
|
||||
try {
|
||||
TimeUnit.SECONDS.sleep(10);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
//Run client in a new thread
|
||||
Runnable runnable2 = () -> { runClient(); };
|
||||
Thread thread2 = new Thread(runnable2);
|
||||
thread2.start();
|
||||
}
|
||||
|
||||
public static void runServer() {
|
||||
//Run Server
|
||||
Server server = new Server();
|
||||
server.runServer(5555);
|
||||
}
|
||||
|
||||
public static void runClient() {
|
||||
//Run Client
|
||||
Client client = new Client();
|
||||
client.runClient("127.0.0.1", 5555);
|
||||
}
|
||||
}
|
||||
13
core-java-modules/core-java-networking/src/test/resources/.gitignore
vendored
Normal file
13
core-java-modules/core-java-networking/src/test/resources/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
*.class
|
||||
|
||||
#folders#
|
||||
/target
|
||||
/neoDb*
|
||||
/data
|
||||
/src/main/webapp/WEB-INF/classes
|
||||
*/META-INF/*
|
||||
|
||||
# Packaged files #
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
Reference in New Issue
Block a user