Consider a code:
URI one = URI.create("http://localhost:8081/contextRoot/main.html?one=1&second=2");
URI second = URI.create("http://localhost:8081/contextRoot/main.html?second=2&one=1");
System.out.println(one.equals(second));
And it prints false. Is there a way to test URI without URI parameters order?
Unforunately, equals methods of URI/URL objects are not always do, what you are exactly waiting for. That is why, to compare 2 URI with different parameters order (if you think, the order is not important for you), you should use some utility logic. For example, as follows:
public static void main(String... args) {
URI one = URI.create("http://localhost:8081/contextRoot/main.html?one=1&second=2");
URI second = URI.create("http://localhost:8081/contextRoot/main.html?second=2&one=1");
System.out.println(one.equals(second));
System.out.println(areEquals(one, second));
}
private static boolean areEquals(URI url1, URI url2) {
//compare the commons part of URI
if (!url1.getScheme().equals(url1.getScheme()) ||
!url1.getAuthority().equals(url2.getAuthority()) ||
url1.getPort() != url2.getPort() ||
!url1.getHost().equals(url2.getHost())) {
return false;
}
//extract query parameters
String params1 = url1.getQuery();
String params2 = url2.getQuery();
if ((params1 != null && params2 != null) && (params1.length() == params2.length())) {
//get sorted list of parameters
List<String> list1 = extractParameters(params1);
List<String> list2 = extractParameters(params2);
//since list are sorted and contain String objects,
//we can compare the lists objects
return list1.equals(list2);
} else {
return false;
}
}
//return sorted list of parameters with the values
private static List<String> extractParameters(String paramsString) {
List<String> parameters = new ArrayList<>();
String[] paramAr = paramsString.split("&");
for (String parameter : paramAr) {
parameters.add(parameter);
}
Collections.sort(parameters);
return parameters;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With