#133 - Made JsonPathLinkDiscoverer more robust.

JsonPathLinkDiscoverer now handles InvalidPathExceptions that might occur if the representation doesn't contain the link container element.
This commit is contained in:
Oliver Gierke
2013-12-29 18:59:35 +01:00
parent bc68707e73
commit 6673f1987f
3 changed files with 24 additions and 3 deletions

View File

@@ -30,6 +30,7 @@ import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import com.jayway.jsonpath.InvalidPathException;
import com.jayway.jsonpath.JsonPath;
/**
@@ -88,8 +89,12 @@ public class JsonPathLinkDiscoverer implements LinkDiscoverer {
@Override
public List<Link> findLinksWithRel(String rel, String representation) {
Object parseResult = getExpression(rel).read(representation);
return createLinksFrom(parseResult, rel);
try {
Object parseResult = getExpression(rel).read(representation);
return createLinksFrom(parseResult, rel);
} catch (InvalidPathException e) {
return Collections.emptyList();
}
}
/*

View File

@@ -22,6 +22,7 @@ import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.LinkDiscoverer;
@@ -63,12 +64,20 @@ public abstract class AbstractLinkDiscovererUnitTest {
}
@Test
public void returnsForInxistingLinkFromInputStream() throws Exception {
public void returnsForInexistingLinkFromInputStream() throws Exception {
InputStream inputStream = new ByteArrayInputStream(getInputString().getBytes("UTF-8"));
assertThat(getDiscoverer().findLinkWithRel("something", inputStream), is(nullValue()));
}
@Test
public void returnsNullForNonExistingLinkContainer() {
assertThat(getDiscoverer().findLinksWithRel("something", getInputStringWithoutLinkContainer()),
is(Matchers.<Link> empty()));
assertThat(getDiscoverer().findLinkWithRel("something", getInputStringWithoutLinkContainer()), is(nullValue()));
}
/**
* Return the {@link LinkDiscoverer} to be tested.
*
@@ -82,4 +91,6 @@ public abstract class AbstractLinkDiscovererUnitTest {
* @return
*/
protected abstract String getInputString();
protected abstract String getInputStringWithoutLinkContainer();
}

View File

@@ -40,4 +40,9 @@ public class HalLinkDiscovererUnitTest extends AbstractLinkDiscovererUnitTest {
protected String getInputString() {
return SAMPLE;
}
@Override
protected String getInputStringWithoutLinkContainer() {
return "{}";
}
}