Skip to content

Commit

Permalink
Merge pull request #5944 from Yoshani/master
Browse files Browse the repository at this point in the history
Add util method to get root domain
  • Loading branch information
Yoshani committed Sep 20, 2024
2 parents c2afbe4 + 8163d36 commit 6b455d7
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,29 @@ public static boolean isSubdomain(String domainName, String subdomainName) {
return subdomainName.endsWith("." + domainName);
}

/**
* Get the root domain of the given domain.
* Note: this assumes that the root domain only consists of two parts (eg: wso2.io). The method will not work for
* TLDs with more than two parts (eg: wso2.co.uk).
*
* @param domain Domain.
* @return Root domain.
*/
public static String getRootDomain(String domain) {

if (StringUtils.isBlank(domain)) {
return domain;
}
String[] domainParts = domain.split("\\.");
int length = domainParts.length;

if (length > 2) {
return domainParts[length - 2] + "." + domainParts[length - 1];
} else {
return domain;
}
}

private static StringBuilder getServerUrlWithPort(String hostName) {

String mgtTransport = CarbonUtils.getManagementTransport();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -838,6 +838,18 @@ public Object[][] getSubdomainData() {
};
}

@DataProvider(name = "rootDomainDataProvider")
public Object[][] getRootDomainData() {
return new Object[][] {
{"dev.api.wso2.io", "wso2.io"}, // Deeper subdomain
{"api.test.com", "test.com"}, // Typical subdomain
{"abc.com", "abc.com"}, // Root domain itself
{"localhost", "localhost"}, // Localhost
{null, null}, // Null case
{"", ""} // Empty string
};
}

@Test(dataProvider = "getClockSkewData")
public void testGetClockSkewInSeconds(String value, int expected) throws Exception {
Map<String, Object> mockConfiguration = new HashMap<>();
Expand All @@ -859,10 +871,18 @@ public void testIsSupportedByUserStore() throws Exception {

@Test(dataProvider = "getSubdomainData")
public void testCheckSubdomain(String domainName, String subdomainName, boolean expectedResult) throws Exception {

boolean result = IdentityUtil.isSubdomain(domainName, subdomainName);
assertEquals(result, expectedResult, "Subdomain check failed for: " + domainName + " and " + subdomainName);
}

@Test(dataProvider = "rootDomainDataProvider")
public void testGetRootDomain(String domain, String expectedRootDomain) {

String actualRootDomain = IdentityUtil.getRootDomain(domain);
assertEquals(actualRootDomain, expectedRootDomain, "Root domain extraction failed for: " + domain);
}

private void setPrivateStaticField(Class<?> clazz, String fieldName, Object newValue)
throws NoSuchFieldException, IllegalAccessException {

Expand Down

0 comments on commit 6b455d7

Please sign in to comment.