use of org.glassfish.grizzly.http.util.ContentType in project Payara by payara.
the class JwtKeyStoreUtils method readKeyFromURL.
private static CacheableString readKeyFromURL(URL keyURL, Duration defaultCacheTTL) throws IOException {
URLConnection urlConnection = keyURL.openConnection();
Charset charset = Charset.defaultCharset();
ContentType contentType = ContentType.newContentType(urlConnection.getContentType());
if (contentType != null) {
String charEncoding = contentType.getCharacterEncoding();
if (charEncoding != null) {
try {
if (!Charset.isSupported(charEncoding)) {
LOGGER.warning("Charset " + charEncoding + " for remote key not supported, using default charset instead");
} else {
charset = Charset.forName(contentType.getCharacterEncoding());
}
} catch (IllegalCharsetNameException ex) {
LOGGER.severe("Charset " + ex.getCharsetName() + " for remote key not supported, Cause: " + ex.getMessage());
}
}
}
// There's no guarantee that the response will contain at most one Cache-Control header and at most one max-age
// directive. Here, we apply the smallest of all max-age directives.
Duration cacheTTL = urlConnection.getHeaderFields().entrySet().stream().filter(e -> e.getKey() != null && e.getKey().trim().equalsIgnoreCase("Cache-Control")).flatMap(headers -> headers.getValue().stream()).flatMap(headerValue -> Stream.of(headerValue.split(","))).filter(directive -> directive.trim().startsWith("max-age")).map(maxAgeDirective -> {
String[] keyValue = maxAgeDirective.split("=", 2);
String maxAge = keyValue[keyValue.length - 1];
try {
return Duration.ofSeconds(Long.parseLong(maxAge));
} catch (NumberFormatException e) {
return null;
}
}).filter(Objects::nonNull).min(Duration::compareTo).orElse(defaultCacheTTL);
try (InputStream inputStream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset))) {
String keyContents = reader.lines().collect(Collectors.joining(System.lineSeparator()));
return CacheableString.from(keyContents, cacheTTL);
}
}
Aggregations