From 25c40ac1ca61f4e77b4af4e0fe0cfa667b51b275 Mon Sep 17 00:00:00 2001 From: DiegoMarti2 <150871541+DiegoMarti2@users.noreply.github.com> Date: Thu, 25 Jan 2024 20:58:17 +0200 Subject: [PATCH] baeldung-articles : BAEL-6777 (#15719) * baeldung-articles : BAEL-6777 Normalize a URL in Java (commit) * Update URLNormalizationUnitTest.java --- .../URLNormalizationUnitTest.java | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 core-java-modules/core-java-networking-4/urlnormalization/URLNormalizationUnitTest.java diff --git a/core-java-modules/core-java-networking-4/urlnormalization/URLNormalizationUnitTest.java b/core-java-modules/core-java-networking-4/urlnormalization/URLNormalizationUnitTest.java new file mode 100644 index 0000000000..13d2abc62c --- /dev/null +++ b/core-java-modules/core-java-networking-4/urlnormalization/URLNormalizationUnitTest.java @@ -0,0 +1,50 @@ +package com.baeldung.urlnormalization; + +import org.junit.jupiter.api.Test; +import org.apache.commons.validator.routines.UrlValidator; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class URLNormalizationUnitTest { + String originalUrl = "https://www.example.com:8080/path/to/resource?param1=value1¶m2=value2#fragment"; + String expectedNormalizedUrl = "https://www.example.com:8080/path/to/resource"; + + @Test + public void givenOriginalUrl_whenUsingApacheCommonsValidator_thenValidatedAndMaybeManuallyNormalized() { + UrlValidator urlValidator = new UrlValidator(); + if (urlValidator.isValid(originalUrl)) { + String normalizedUri = originalUrl.split("\\?")[0]; + assertEquals(expectedNormalizedUrl, normalizedUri); + } else { + throw new IllegalArgumentException("Invalid URL: " + originalUrl); + } + } + + @Test + public void givenOriginalUrl_whenUsingJavaURIClass_thenNormalizedUrl() throws URISyntaxException { + URI uri = new URI(originalUrl); + URI normalizedUri = new URI(uri.getScheme(), uri.getAuthority(), uri.getPath(), null, null); + String normalizedUrl = normalizedUri.toString(); + assertEquals(expectedNormalizedUrl, normalizedUrl); + } + + @Test + public void givenOriginalUrl_whenUsingRegularExpression_thenNormalizedUrl() throws URISyntaxException, UnsupportedEncodingException { + String regex = "^(https?://[^/]+/[^?#]+)"; + Pattern pattern = Pattern.compile(regex); + Matcher matcher = pattern.matcher(originalUrl); + + if (matcher.find()) { + String normalizedUrl = matcher.group(1); + assertEquals(expectedNormalizedUrl, normalizedUrl); + } else { + throw new IllegalArgumentException("Invalid URL: " + originalUrl); + } + } +}