Skip to content

Commit

Permalink
Add a URL cache to ValidatorContext
Browse files Browse the repository at this point in the history
This caches JsonElement values parsed from the resource.
  • Loading branch information
ssilverman committed Jun 8, 2020
1 parent e694d8a commit ef957b3
Showing 1 changed file with 26 additions and 3 deletions.
29 changes: 26 additions & 3 deletions src/main/java/com/qindesign/json/schema/ValidatorContext.java
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,26 @@ private static Map<String, Keyword> findKeywords() throws IOException {
private final Map<URI, Id> idsByURI;
private final Map<URI, URL> knownURLs;

// https://www.baeldung.com/java-sneaky-throws
@SuppressWarnings("unchecked")
private static <E extends Throwable> void sneakyThrow(Throwable e) throws E {
throw (E) e;
}

// URL cache
private static final int MAX_URL_CACHE_SIZE = 10;
// Function throws IOException (checked) or JsonParseException (unchecked)
private final LRUCache<URL, JsonElement> urlCache = new LRUCache<>(
MAX_URL_CACHE_SIZE,
url -> {
try (InputStream in = url.openStream()) {
return JSON.parse(in);
} catch (IOException ex) {
sneakyThrow(ex);
return null;
}
});

/**
* Tracks schemas that have either been validated or in the process of being
* validated, to avoid $schema recursion.
Expand Down Expand Up @@ -570,9 +590,12 @@ public JsonElement findAndSetRoot(URI id) {
// Try the resource
URL url = knownURLs.get(uri);
if (url != null) {
try (InputStream in = new URL(url, sb.toString()).openStream()) {
state.schemaObject = null;
return JSON.parse(in);
try {
JsonElement data = urlCache.access(new URL(url, sb.toString()));
if (data != null) {
state.schemaObject = null;
return data;
}
} catch (IOException | JsonParseException ex) {
// Ignore and try next
}
Expand Down

0 comments on commit ef957b3

Please sign in to comment.