use of io.swagger.v3.oas.models.media.Encoding in project swagger-core by swagger-api.
the class SwaggerMojo method readStructuredDataFromFile.
/**
* Read the content of given file as either json or yaml and maps it to given class
*
* @param filePath to read content from
* @param outputClass to map to
* @param configName for logging, what user config will be read
* @param <T> mapped type
* @return empty optional if not path was given or the file was empty, read instance otherwis
* @throws MojoFailureException if given path is not file, could not be read or is not proper json or yaml
*/
private <T> Optional<T> readStructuredDataFromFile(String filePath, Class<T> outputClass, String configName) throws MojoFailureException {
try {
// ignore if config is not provided
if (StringUtils.isBlank(filePath)) {
return Optional.empty();
}
Path pathObj = Paths.get(filePath);
// if file does not exist or is not an actual file, finish with error
if (!pathObj.toFile().exists() || !pathObj.toFile().isFile()) {
throw new IllegalArgumentException(format("passed path does not exist or is not a file: '%s'", filePath));
}
String fileContent = new String(Files.readAllBytes(pathObj), encoding);
// if provided file is empty, log warning and finish
if (StringUtils.isBlank(fileContent)) {
getLog().warn(format("It seems that file '%s' defined in config %s is empty", pathObj.toString(), configName));
return Optional.empty();
}
// get mappers in the order based on file extension
List<BiFunction<String, Class<T>, T>> mappers = getSortedMappers(pathObj);
T instance = null;
Throwable caughtEx = null;
// iterate through mappers and see if one is able to parse
for (BiFunction<String, Class<T>, T> mapper : mappers) {
try {
instance = mapper.apply(fileContent, outputClass);
break;
} catch (Exception e) {
caughtEx = e;
}
}
// if no mapper could read the content correctly, finish with error
if (instance == null) {
if (caughtEx == null) {
caughtEx = new IllegalStateException("undefined state");
}
getLog().error(format("Could not read file '%s' for config %s", pathObj.toString(), configName), caughtEx);
throw new IllegalStateException(caughtEx.getMessage(), caughtEx);
}
return Optional.of(instance);
} catch (Exception e) {
getLog().error(format("Error reading/deserializing config %s file", configName), e);
throw new MojoFailureException(e.getMessage(), e);
}
}
Aggregations