Last active
August 29, 2015 14:07
-
-
Save enginer/230e2dc2f1d213a825d5 to your computer and use it in GitHub Desktop.
Append relative path to java.net.URI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.URI; | |
import java.net.URISyntaxException; | |
public class URIBuilder extends org.apache.http.client.utils.URIBuilder { | |
public URIBuilder() { | |
} | |
public URIBuilder(String string) throws URISyntaxException { | |
super(string); | |
} | |
public URIBuilder(URI uri) { | |
super(uri); | |
} | |
public org.apache.http.client.utils.URIBuilder addPath(String subPath) { | |
if (subPath == null || subPath.isEmpty() || "/".equals(subPath)) { | |
return this; | |
} | |
return setPath(appendSegmentToPath(getPath(), subPath)); | |
} | |
private String appendSegmentToPath(String path, String segment) { | |
if (path == null || path.isEmpty()) { | |
path = "/"; | |
} | |
if (path.charAt(path.length() - 1) == '/' || segment.startsWith("/")) { | |
return path + segment; | |
} | |
return path + "/" + segment; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.Test; | |
import static org.junit.Assert.assertEquals; | |
public class URIBuilderTest { | |
@Test | |
public void testAddPath() throws Exception { | |
String url = "http://example.com/test"; | |
String expected = "http://example.com/test/example"; | |
URIBuilder builder = new URIBuilder(url); | |
builder.addPath("/example"); | |
assertEquals(expected, builder.toString()); | |
builder = new URIBuilder(url); | |
builder.addPath("example"); | |
assertEquals(expected, builder.toString()); | |
builder.addPath(""); | |
builder.addPath(null); | |
assertEquals(expected, builder.toString()); | |
url = "http://example.com"; | |
expected = "http://example.com/example"; | |
builder = new URIBuilder(url); | |
builder.addPath("/"); | |
assertEquals(url, builder.toString()); | |
builder.addPath("/example"); | |
assertEquals(expected, builder.toString()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment