move networking articles, update readme

This commit is contained in:
Loredana
2018-12-25 14:05:10 +02:00
parent 68f1cb23dd
commit fb66f1bc78
13 changed files with 19 additions and 15 deletions

View File

@@ -8,4 +8,6 @@
- [Broadcasting and Multicasting in Java](http://www.baeldung.com/java-broadcast-multicast)
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
- [Sending Emails with Java](http://www.baeldung.com/java-email)
- [Console I/O in Java](http://www.baeldung.com/java-console-input-output)
- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java)
- [A Guide to the Java URL](http://www.baeldung.com/java-url)
- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces)

View File

@@ -19,6 +19,11 @@
<artifactId>mail</artifactId>
<version>${javax.mail.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
@@ -27,5 +32,6 @@
<properties>
<javax.mail.version>1.5.0-b01</javax.mail.version>
<commons-io.version>2.5</commons-io.version>
</properties>
</project>

View File

@@ -1,26 +0,0 @@
package com.baeldung.console;
import java.io.Console;
public class ConsoleConsoleClass {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.out.print("No console available");
return;
}
String progLanguauge = console.readLine("Enter your favourite programming language: ");
console.printf(progLanguauge + " is very interesting!");
char[] pass = console.readPassword("To finish, enter password: ");
if ("BAELDUNG".equals(pass.toString().toUpperCase()))
console.printf("Good! Regards!");
else
console.printf("Nice try. Regards.");
}
}

View File

@@ -1,76 +0,0 @@
package com.baeldung.console;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.regex.Pattern;
public class ConsoleScannerClass {
public static void main(String[] args) {
System.out.println("Please enter your name and surname: ");
Scanner scanner = new Scanner(System.in);
String nameSurname = scanner.nextLine();
System.out.println("Please enter your gender: ");
char gender = scanner.next().charAt(0);
System.out.println("Please enter your age: ");
int age = scanner.nextInt();
System.out.println("Please enter your height in meters: ");
double height = scanner.nextDouble();
System.out.println(nameSurname + ", " + age + ", is a great " + (gender == 'm' ? "guy" : "girl") + " with " + height + " meters height" + " and " + (gender == 'm' ? "he" : "she") + " reads Baeldung.");
System.out.print("Have a good");
System.out.print(" one!");
System.out.println("\nPlease enter number of years of experience as a developer: ");
BufferedReader buffReader = new BufferedReader(new InputStreamReader(System.in));
int i = 0;
try {
i = Integer.parseInt(buffReader.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("You are a " + (i > 5 ? "great" : "good") + " developer!");
int sum = 0, count = 0;
System.out.println("Please enter your college degrees. To finish, enter baeldung website url");
while (scanner.hasNextInt()) {
int nmbr = scanner.nextInt();
sum += nmbr;
count++;
}
int mean = sum / count;
System.out.println("Your average degree is " + mean);
if (scanner.hasNext(Pattern.compile("www.baeldung.com")))
System.out.println("Correct!");
else
System.out.println("Baeldung website url is www.baeldung.com");
if (scanner != null)
scanner.close();
}
}

View File

@@ -1,5 +0,0 @@
### Relevant Articles:
- [A Guide To UDP In Java](http://www.baeldung.com/udp-in-java)
- [A Guide To HTTP Cookies In Java](http://www.baeldung.com/cookies-java)
- [A Guide to the Java URL](http://www.baeldung.com/java-url)
- [Working with Network Interfaces in Java](http://www.baeldung.com/java-network-interfaces)

View File

@@ -0,0 +1,91 @@
package com.baeldung.networking.uriurl;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class URIDemo {
private final Logger logger = LoggerFactory.getLogger(URIDemo.class);
String URISTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
String URISCHEME = "https";
String URISCHEMESPECIFIC;
String URIHOST = "wordpress.org";
String URIAUTHORITY = "wordpress.org:443";
String URIPATH = "/support/topic/page-jumps-within-wordpress/";
int URIPORT = 443;
String URIQUERY = "replies=3";
String URIFRAGMENT = "post-2278484";
String URIUSERINFO;
String URICOMPOUND = URISCHEME + "://" + URIHOST + ":" + URIPORT + URIPATH + "?" + URIQUERY + "#" + URIFRAGMENT;
URI uri;
URL url;
BufferedReader in = null;
String URIContent = "";
private String getParsedPieces(URI uri) {
logger.info("*** List of parsed pieces ***");
URISCHEME = uri.getScheme();
logger.info("URISCHEME: " + URISCHEME);
URISCHEMESPECIFIC = uri.getSchemeSpecificPart();
logger.info("URISCHEMESPECIFIC: " + URISCHEMESPECIFIC);
URIHOST = uri.getHost();
URIAUTHORITY = uri.getAuthority();
logger.info("URIAUTHORITY: " + URIAUTHORITY);
logger.info("URIHOST: " + URIHOST);
URIPATH = uri.getPath();
logger.info("URIPATH: " + URIPATH);
URIPORT = uri.getPort();
logger.info("URIPORT: " + URIPORT);
URIQUERY = uri.getQuery();
logger.info("URIQUERY: " + URIQUERY);
URIFRAGMENT = uri.getFragment();
logger.info("URIFRAGMENT: " + URIFRAGMENT);
try {
url = uri.toURL();
} catch (MalformedURLException e) {
logger.info("MalformedURLException thrown: " + e.getMessage());
e.printStackTrace();
} catch (IllegalArgumentException e) {
logger.info("IllegalArgumentException thrown: " + e.getMessage());
e.printStackTrace();
}
return url.toString();
}
public String testURIAsNew(String URIString) {
// creating URI object
try {
uri = new URI(URIString);
} catch (URISyntaxException e) {
logger.info("URISyntaxException thrown: " + e.getMessage());
e.printStackTrace();
throw new IllegalArgumentException();
}
return getParsedPieces(uri);
}
public String testURIAsCreate(String URIString) {
// creating URI object
uri = URI.create(URIString);
return getParsedPieces(uri);
}
public static void main(String[] args) throws Exception {
URIDemo demo = new URIDemo();
String contentCreate = demo.testURIAsCreate(demo.URICOMPOUND);
demo.logger.info(contentCreate);
String contentNew = demo.testURIAsNew(demo.URICOMPOUND);
demo.logger.info(contentNew);
}
}

View File

@@ -0,0 +1,70 @@
package com.baeldung.networking.uriurl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class URLDemo {
private final Logger log = LoggerFactory.getLogger(URLDemo.class);
String URLSTRING = "https://wordpress.org:443/support/topic/page-jumps-within-wordpress/?replies=3#post-2278484";
// parsed locator
String URLPROTOCOL = "https";
// final static String URLAUTHORITY = "wordpress.org:443";
String URLHOST = "wordpress.org";
String URLPATH = "/support/topic/page-jumps-within-wordpress/";
// final static String URLFILENAME = "/support/topic/page-jumps-within-wordpress/?replies=3";
// final static int URLPORT = 443;
int URLDEFAULTPORT = 443;
String URLQUERY = "replies=3";
String URLREFERENCE = "post-2278484";
String URLCOMPOUND = URLPROTOCOL + "://" + URLHOST + ":" + URLDEFAULTPORT + URLPATH + "?" + URLQUERY + "#" + URLREFERENCE;
URL url;
URLConnection urlConnection = null;
HttpURLConnection connection = null;
BufferedReader in = null;
String urlContent = "";
public String testURL(String urlString) throws IOException, IllegalArgumentException {
String urlStringCont = "";
// comment the if clause if experiment with URL
/*if (!URLSTRING.equals(urlString)) {
throw new IllegalArgumentException("URL String argument is not proper: " + urlString);
}*/
// creating URL object
url = new URL(urlString);
// get URL connection
urlConnection = url.openConnection();
connection = null;
// we can check, if connection is proper type
if (urlConnection instanceof HttpURLConnection) {
connection = (HttpURLConnection) urlConnection;
} else {
log.info("Please enter an HTTP URL");
throw new IOException("HTTP URL is not correct");
}
// we can check response code (200 OK is expected)
log.info(connection.getResponseCode() + " " + connection.getResponseMessage());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String current;
while ((current = in.readLine()) != null) {
urlStringCont += current;
}
return urlStringCont;
}
public static void main(String[] args) throws Exception {
URLDemo demo = new URLDemo();
String content = demo.testURL(demo.URLCOMPOUND);
demo.log.info(content);
}
}

View File

@@ -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);
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}

View File

@@ -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);
}
}

View File

@@ -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());
}
}