Skip to content

Commit

Permalink
Merge pull request #30 from elisherer/feature/retry_with_https
Browse files Browse the repository at this point in the history
mimic follow redirects of http to https in case content received empty
  • Loading branch information
jimblackler authored Oct 2, 2023
2 parents 56889e3 + 61c19f2 commit dc8f040
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 9 deletions.
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package net.jimblackler.jsonschemafriend;

import static net.jimblackler.jsonschemafriend.StreamUtils.streamToString;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URI;
import java.nio.file.FileSystem;
Expand All @@ -24,18 +21,17 @@ public String load(URI uri, boolean cacheSchema) throws IOException {
.resolve(uri.getHost() + uri.getPath());
if (Files.exists(diskCacheName)) {
LOG.fine("Cache loading: " + uri + System.lineSeparator() + "From: " + diskCacheName);
return streamToString(diskCacheName.toUri().toURL().openStream());
return UrlUtils.readFromStream(diskCacheName.toUri().toURL());
}
String content = streamToString(uri.toURL().openStream());
String content = UrlUtils.readFromStream(uri.toURL());
diskCacheName.getParent().toFile().mkdirs();
try (PrintWriter out = new PrintWriter(diskCacheName.toFile())) {
out.println(content);
}
return content;
}
LOG.fine("Loading :" + uri);
try (InputStream stream = uri.toURL().openStream()) {
return streamToString(stream);
}

return UrlUtils.readFromStream(uri.toURL());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package net.jimblackler.jsonschemafriend;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import static net.jimblackler.jsonschemafriend.StreamUtils.streamToString;

public class UrlUtils {
static String readFromStream(URL url) throws IOException {
String result;
try (InputStream stream = url.openStream()) {
result = streamToString(stream);
}
if (result.isEmpty() && "http".equals(url.getProtocol())) {
// in case tried http and received empty content, try to connect to same url with https
URL secureUrl = new URL(url.toString().replaceFirst("http", "https"));
try (InputStream stream = secureUrl.openStream()) {
result = streamToString(stream);
}
}
return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -731,7 +731,7 @@ public void validate(Schema schema, InputStream inputStream)

public void validate(Schema schema, URL url, Consumer<ValidationError> errorConsumer)
throws IOException {
validate(schema, new ObjectMapper().readValue(url.openStream(), Object.class), errorConsumer);
validate(schema, new ObjectMapper().readValue(UrlUtils.readFromStream(url), Object.class), errorConsumer);
}

public void validate(Schema schema, URI uri, Consumer<ValidationError> errorConsumer)
Expand Down

0 comments on commit dc8f040

Please sign in to comment.