use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType in project dropwizard by dropwizard.
the class ConfigurationMetadata method expectObjectFormat.
@Override
public JsonObjectFormatVisitor expectObjectFormat(JavaType type) throws JsonMappingException {
// store the pointer to the own instance
final ConfigurationMetadata thiss = this;
return new JsonObjectFormatVisitor.Base() {
@Override
public void optionalProperty(BeanProperty prop) throws JsonMappingException {
// don't run into an infinite loop with circular dependencies
if (currentDepth >= MAX_DEPTH) {
return;
}
// check if we already visited the same property
if (parentProps.contains(prop)) {
return;
}
if (prop.getAnnotation(JsonIgnore.class) != null) {
return;
}
// build the complete field path
String name = !currentPrefix.isEmpty() ? currentPrefix + "." + prop.getName() : prop.getName();
// set state for the recursive traversal
int oldFieldSize = fields.size();
String oldPrefix = currentPrefix;
currentPrefix = name;
currentDepth++;
// the type of the field
JavaType fieldType = prop.getType();
// to the path
if (fieldType.isCollectionLikeType() || fieldType.isArrayType()) {
fieldType = fieldType.getContentType();
currentPrefix += "[*]";
}
// get the type deserializer
TypeDeserializer typeDeserializer = mapper.getDeserializationConfig().findTypeDeserializer(fieldType);
// get the default impl if available
Class<?> defaultImpl = typeDeserializer != null ? typeDeserializer.getDefaultImpl() : null;
// remember current property
parentProps.add(prop);
// visit the type of the property (or its defaultImpl).
try {
mapper.acceptJsonFormatVisitor(defaultImpl == null ? fieldType.getRawClass() : defaultImpl, thiss);
} catch (NoClassDefFoundError | TypeNotPresentException e) {
// that case, just ignore the default implementation
if (defaultImpl != null) {
return;
} else {
// implementation, so re-throw it
throw e;
}
} finally {
// reset state after the recursive traversal
parentProps.remove(prop);
currentDepth--;
currentPrefix = oldPrefix;
}
// if no new fields are discovered, we assume that we are at an primitive field
if (oldFieldSize == fields.size()) {
fields.put(name, prop.getType());
}
}
};
}
use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType in project spring-framework by spring-projects.
the class MappingJackson2HttpMessageConverterTests method readAndWriteGenerics.
@Test
@SuppressWarnings("unchecked")
public void readAndWriteGenerics() throws Exception {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter() {
@Override
protected JavaType getJavaType(Type type, @Nullable Class<?> contextClass) {
if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) {
return new ObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, MyBean.class);
} else {
return super.getJavaType(type, contextClass);
}
}
};
String body = "[{" + "\"bytes\":\"AQI=\"," + "\"array\":[\"Foo\",\"Bar\"]," + "\"number\":42," + "\"string\":\"Foo\"," + "\"bool\":true," + "\"fraction\":42.0}]";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes(StandardCharsets.UTF_8));
inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
List<MyBean> results = (List<MyBean>) converter.read(List.class, inputMessage);
assertThat(results.size()).isEqualTo(1);
MyBean result = results.get(0);
assertThat(result.getString()).isEqualTo("Foo");
assertThat(result.getNumber()).isEqualTo(42);
assertThat(result.getFraction()).isCloseTo(42F, within(0F));
assertThat(result.getArray()).isEqualTo(new String[] { "Foo", "Bar" });
assertThat(result.isBool()).isTrue();
assertThat(result.getBytes()).isEqualTo(new byte[] { 0x1, 0x2 });
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(results, MediaType.APPLICATION_JSON, outputMessage);
JSONAssert.assertEquals(body, outputMessage.getBodyAsString(StandardCharsets.UTF_8), true);
}
use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType in project spring-framework by spring-projects.
the class AbstractJackson2Decoder method getObjectReader.
private ObjectReader getObjectReader(ObjectMapper mapper, ResolvableType elementType, @Nullable Map<String, Object> hints) {
Assert.notNull(elementType, "'elementType' must not be null");
Class<?> contextClass = getContextClass(elementType);
if (contextClass == null && hints != null) {
contextClass = getContextClass((ResolvableType) hints.get(ACTUAL_TYPE_HINT));
}
JavaType javaType = getJavaType(elementType.getType(), contextClass);
Class<?> jsonView = (hints != null ? (Class<?>) hints.get(Jackson2CodecSupport.JSON_VIEW_HINT) : null);
return jsonView != null ? mapper.readerWithView(jsonView).forType(javaType) : mapper.readerFor(javaType);
}
use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType in project flink by apache.
the class RestClient method sendRequest.
public <M extends MessageHeaders<R, P, U>, U extends MessageParameters, R extends RequestBody, P extends ResponseBody> CompletableFuture<P> sendRequest(String targetAddress, int targetPort, M messageHeaders, U messageParameters, R request, Collection<FileUpload> fileUploads, RestAPIVersion apiVersion) throws IOException {
Preconditions.checkNotNull(targetAddress);
Preconditions.checkArgument(NetUtils.isValidHostPort(targetPort), "The target port " + targetPort + " is not in the range [0, 65535].");
Preconditions.checkNotNull(messageHeaders);
Preconditions.checkNotNull(request);
Preconditions.checkNotNull(messageParameters);
Preconditions.checkNotNull(fileUploads);
Preconditions.checkState(messageParameters.isResolved(), "Message parameters were not resolved.");
if (!messageHeaders.getSupportedAPIVersions().contains(apiVersion)) {
throw new IllegalArgumentException(String.format("The requested version %s is not supported by the request (method=%s URL=%s). Supported versions are: %s.", apiVersion, messageHeaders.getHttpMethod(), messageHeaders.getTargetRestEndpointURL(), messageHeaders.getSupportedAPIVersions().stream().map(RestAPIVersion::getURLVersionPrefix).collect(Collectors.joining(","))));
}
String versionedHandlerURL = "/" + apiVersion.getURLVersionPrefix() + messageHeaders.getTargetRestEndpointURL();
String targetUrl = MessageParameters.resolveUrl(versionedHandlerURL, messageParameters);
LOG.debug("Sending request of class {} to {}:{}{}", request.getClass(), targetAddress, targetPort, targetUrl);
// serialize payload
StringWriter sw = new StringWriter();
objectMapper.writeValue(sw, request);
ByteBuf payload = Unpooled.wrappedBuffer(sw.toString().getBytes(ConfigConstants.DEFAULT_CHARSET));
Request httpRequest = createRequest(targetAddress + ':' + targetPort, targetUrl, messageHeaders.getHttpMethod().getNettyHttpMethod(), payload, fileUploads);
final JavaType responseType;
final Collection<Class<?>> typeParameters = messageHeaders.getResponseTypeParameters();
if (typeParameters.isEmpty()) {
responseType = objectMapper.constructType(messageHeaders.getResponseClass());
} else {
responseType = objectMapper.getTypeFactory().constructParametricType(messageHeaders.getResponseClass(), typeParameters.toArray(new Class<?>[typeParameters.size()]));
}
return submitRequest(targetAddress, targetPort, httpRequest, responseType);
}
use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType in project flink by apache.
the class RestClient method submitRequest.
private <P extends ResponseBody> CompletableFuture<P> submitRequest(String targetAddress, int targetPort, Request httpRequest, JavaType responseType) {
final ChannelFuture connectFuture = bootstrap.connect(targetAddress, targetPort);
final CompletableFuture<Channel> channelFuture = new CompletableFuture<>();
connectFuture.addListener((ChannelFuture future) -> {
if (future.isSuccess()) {
channelFuture.complete(future.channel());
} else {
channelFuture.completeExceptionally(future.cause());
}
});
return channelFuture.thenComposeAsync(channel -> {
ClientHandler handler = channel.pipeline().get(ClientHandler.class);
CompletableFuture<JsonResponse> future;
boolean success = false;
try {
if (handler == null) {
throw new IOException("Netty pipeline was not properly initialized.");
} else {
httpRequest.writeTo(channel);
future = handler.getJsonFuture();
success = true;
}
} catch (IOException e) {
future = FutureUtils.completedExceptionally(new ConnectionException("Could not write request.", e));
} finally {
if (!success) {
channel.close();
}
}
return future;
}, executor).thenComposeAsync((JsonResponse rawResponse) -> parseResponse(rawResponse, responseType), executor);
}
Aggregations