Skip to content

Commit 96b69b7

Browse files
authored
feature: Convenience method to get path segments (#10)
Easier and less expensive than calling `getPath().split("/")`.
1 parent 694c7ed commit 96b69b7

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

src/main/java/com/widen/urlbuilder/UrlBuilder.java

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import java.net.URL;
2121
import java.util.ArrayList;
2222
import java.util.Arrays;
23+
import java.util.Collections;
2324
import java.util.Iterator;
2425
import java.util.LinkedHashMap;
2526
import java.util.List;
@@ -46,13 +47,13 @@ public class UrlBuilder {
4647

4748
private int port;
4849

49-
private List<String> path = new ArrayList<String>();
50+
private List<String> path = new ArrayList<>();
5051

5152
private boolean trailingPathSlash = false;
5253

5354
private String fragment;
5455

55-
List<QueryParam> queryParams = new ArrayList<QueryParam>();
56+
List<QueryParam> queryParams = new ArrayList<>();
5657

5758
private GenerationMode mode = GenerationMode.HOSTNAME_RELATIVE;
5859

@@ -134,7 +135,6 @@ public UrlBuilder(String hostname, int port, String path) {
134135
mode = GenerationMode.FULLY_QUALIFIED;
135136
}
136137

137-
138138
public boolean isSslEnabled() {
139139
return ssl;
140140
}
@@ -147,10 +147,24 @@ public String getHostname() {
147147
return hostname;
148148
}
149149

150+
/**
151+
* Get the full path string of the URL.
152+
*
153+
* @return The URL path.
154+
*/
150155
public String getPath() {
151156
return "/" + StringUtilsInternal.join(path, "/");
152157
}
153158

159+
/**
160+
* Get the path segments in the URL. This effectively returns the path split on "/" in an efficient way.
161+
*
162+
* @return A read-only list of path segments.
163+
*/
164+
public List<String> getPathSegments() {
165+
return Collections.unmodifiableList(path);
166+
}
167+
154168
public String getFragment() {
155169
return fragment;
156170
}

src/test/groovy/com/widen/urlbuilder/UrlBuilderSpec.groovy

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,21 @@ class UrlBuilderSpec extends Specification {
3030
]
3131
}
3232

33+
def "Path segments are parsed correctly"() {
34+
when:
35+
def builder = new UrlBuilder(url)
36+
37+
then:
38+
builder.path == path
39+
builder.pathSegments == segments
40+
41+
where:
42+
url | path | segments
43+
"http://my.host.com" | "/" | []
44+
"http://my.host.com/foo/bar" | "/foo/bar" | ["foo", "bar"]
45+
"http://my.host.com/foo//bar/" | "/foo/bar" | ["foo", "bar"]
46+
}
47+
3348
def "Query parameters as map"() {
3449
when:
3550
def builder = new UrlBuilder('https://my.host.com/bar?a=x&b=2&c=3&c=4&a&d#foo')

0 commit comments

Comments
 (0)