Skip to content

Commit

Permalink
feature: Convenience method to get path segments (#10)
Browse files Browse the repository at this point in the history
Easier and less expensive than calling `getPath().split("/")`.
  • Loading branch information
sagebind authored May 9, 2019
1 parent 694c7ed commit 96b69b7
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/main/java/com/widen/urlbuilder/UrlBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
Expand All @@ -46,13 +47,13 @@ public class UrlBuilder {

private int port;

private List<String> path = new ArrayList<String>();
private List<String> path = new ArrayList<>();

private boolean trailingPathSlash = false;

private String fragment;

List<QueryParam> queryParams = new ArrayList<QueryParam>();
List<QueryParam> queryParams = new ArrayList<>();

private GenerationMode mode = GenerationMode.HOSTNAME_RELATIVE;

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


public boolean isSslEnabled() {
return ssl;
}
Expand All @@ -147,10 +147,24 @@ public String getHostname() {
return hostname;
}

/**
* Get the full path string of the URL.
*
* @return The URL path.
*/
public String getPath() {
return "/" + StringUtilsInternal.join(path, "/");
}

/**
* Get the path segments in the URL. This effectively returns the path split on "/" in an efficient way.
*
* @return A read-only list of path segments.
*/
public List<String> getPathSegments() {
return Collections.unmodifiableList(path);
}

public String getFragment() {
return fragment;
}
Expand Down
15 changes: 15 additions & 0 deletions src/test/groovy/com/widen/urlbuilder/UrlBuilderSpec.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,21 @@ class UrlBuilderSpec extends Specification {
]
}

def "Path segments are parsed correctly"() {
when:
def builder = new UrlBuilder(url)

then:
builder.path == path
builder.pathSegments == segments

where:
url | path | segments
"http://my.host.com" | "/" | []
"http://my.host.com/foo/bar" | "/foo/bar" | ["foo", "bar"]
"http://my.host.com/foo//bar/" | "/foo/bar" | ["foo", "bar"]
}

def "Query parameters as map"() {
when:
def builder = new UrlBuilder('https://my.host.com/bar?a=x&b=2&c=3&c=4&a&d#foo')
Expand Down

0 comments on commit 96b69b7

Please sign in to comment.