Skip to content

Commit

Permalink
Merge branch '__rultor'
Browse files Browse the repository at this point in the history
  • Loading branch information
rultor committed Feb 9, 2016
2 parents a749f6a + 3b62276 commit 5e45dfe
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
34 changes: 33 additions & 1 deletion src/main/java/org/takes/misc/Href.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
Expand Down Expand Up @@ -87,7 +88,7 @@ public Href() {
)
public Href(final CharSequence txt) {
this.params = new ConcurrentHashMap<String, List<String>>(0);
final URI link = URI.create(txt.toString());
final URI link = Href.createURI(txt.toString());
final String query = link.getRawQuery();
if (query == null) {
this.uri = link;
Expand Down Expand Up @@ -291,4 +292,35 @@ private static String decode(final String txt) {
}
}

/**
* Parses the specified content to create the corresponding {@code URI}
* instance. In case of an {@code URISyntaxException}, it will automatically
* encode the character that causes the issue then it will try again
* if it is possible otherwise an {@code IllegalArgumentException} will
* be thrown.
* @param txt The content to parse
* @return The {@code URI} corresponding to the specified content.
* @throws IllegalArgumentException in case the content could not be parsed
* @throws IllegalStateException in case an invalid character could not be
* encoded properly.
*/
private static URI createURI(final String txt) {
URI result;
try {
result = new URI(txt);
} catch (final URISyntaxException ex) {
final int index = ex.getIndex();
if (index == -1) {
throw new IllegalArgumentException(ex.getMessage(), ex);
}
final StringBuilder value = new StringBuilder(txt);
value.replace(
index,
index + 1,
Href.encode(value.substring(index, index + 1))
);
result = Href.createURI(value.toString());
}
return result;
}
}
12 changes: 12 additions & 0 deletions src/test/java/org/takes/misc/HrefTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,16 @@ public void acceptsEncodedQuery() {
Matchers.equalTo(url)
);
}

/**
* Href can accept non properly encoded URL.
*/
@Test
public void acceptsNonProperlyEncodedURL() {
MatcherAssert.assertThat(
// @checkstyle LineLength (2 lines)
new Href("http://www.netbout.com/[foo/bar]/read?file=%5B%5D%28%29.txt").toString(),
Matchers.equalTo("http://www.netbout.com/%5Bfoo/bar%5D/read?file=%5B%5D%28%29.txt")
);
}
}

0 comments on commit 5e45dfe

Please sign in to comment.