private ConfigurationFactory(Class<T> klass, Validator validator, Iterable<Module> modules) { this.klass = klass; this.json = new Json(); json.enable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES); for (Module module : modules) { json.registerModule(module); } this.validator = validator; }
@Override public Object readFrom( Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException { boolean validating = false; for (Annotation annotation : annotations) { validating = validating || (annotation.annotationType() == Valid.class); } final Object value = json.readValue(entityStream, genericType); if (validating) { final ImmutableList<String> errors = VALIDATOR.validate(value); if (!errors.isEmpty()) { final StringBuilder msg = new StringBuilder("The request entity had the following errors:\n"); for (String error : errors) { msg.append(" * ").append(error).append('\n'); } throw new WebApplicationException( Response.status(UNPROCESSABLE_ENTITY) .entity(msg.toString()) .type(MediaType.TEXT_PLAIN_TYPE) .build()); } } return value; }
public T build(File file) throws IOException, ConfigurationException { final JsonNode node = parse(file); for (Map.Entry<Object, Object> pref : System.getProperties().entrySet()) { final String prefName = (String) pref.getKey(); if (prefName.startsWith(PROPERTY_PREFIX)) { final String configName = prefName.substring(PROPERTY_PREFIX.length()); addOverride(node, configName, System.getProperty(prefName)); } } final T config = json.readValue(node, klass); validate(file, config); return config; }
@Override public void writeTo( Object t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { try { json.writeValue(entityStream, t); } catch (EofException ignored) { // we don't care about these } catch (IOException e) { LOG.error(e, "Error writing response"); } }
private JsonNode parse(File file) throws IOException { if (file.getName().endsWith(".yaml") || file.getName().endsWith(".yml")) { return json.readYamlValue(file, JsonNode.class); } return json.readValue(file, JsonNode.class); }
@Override public boolean isReadable( Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) { return json.canDeserialize(type); }
public JacksonMessageBodyProvider(Iterable<Module> modules) { this.json = new Json(); for (Module module : modules) { json.registerModule(module); } }