Search in sources :

Example 66 with JavaType

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());
            }
        }
    };
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) TypeDeserializer(com.fasterxml.jackson.databind.jsontype.TypeDeserializer) BeanProperty(com.fasterxml.jackson.databind.BeanProperty)

Example 67 with JavaType

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);
}
Also used : Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) JavaType(com.fasterxml.jackson.databind.JavaType) MediaType(org.springframework.http.MediaType) Type(java.lang.reflect.Type) MockHttpInputMessage(org.springframework.http.MockHttpInputMessage) MockHttpOutputMessage(org.springframework.http.MockHttpOutputMessage) MediaType(org.springframework.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) Nullable(org.springframework.lang.Nullable) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test)

Example 68 with JavaType

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);
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) ResolvableType(org.springframework.core.ResolvableType)

Example 69 with 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);
}
Also used : JavaType(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType) StringWriter(java.io.StringWriter) HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) DefaultFullHttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf)

Example 70 with JavaType

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);
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) SimpleChannelInboundHandler(org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler) MessageParameters(org.apache.flink.runtime.rest.messages.MessageParameters) FullHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpResponse) ChunkedWriteHandler(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedWriteHandler) OutboundChannelHandlerFactory(org.apache.flink.runtime.io.network.netty.OutboundChannelHandlerFactory) MemoryAttribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.MemoryAttribute) LoggerFactory(org.slf4j.LoggerFactory) ExceptionUtils(org.apache.flink.util.ExceptionUtils) JsonParser(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser) JsonNode(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode) NetUtils(org.apache.flink.util.NetUtils) EmptyMessageParameters(org.apache.flink.runtime.rest.messages.EmptyMessageParameters) EmptyRequestBody(org.apache.flink.runtime.rest.messages.EmptyRequestBody) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) RequestBody(org.apache.flink.runtime.rest.messages.RequestBody) HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) RestClientException(org.apache.flink.runtime.rest.util.RestClientException) Path(java.nio.file.Path) ChannelHandlerContext(org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext) DefaultFullHttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultFullHttpRequest) Attribute(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.Attribute) ExecutorThreadFactory(org.apache.flink.util.concurrent.ExecutorThreadFactory) RestConstants(org.apache.flink.runtime.rest.util.RestConstants) Collection(java.util.Collection) NioEventLoopGroup(org.apache.flink.shaded.netty4.io.netty.channel.nio.NioEventLoopGroup) HttpVersion(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpVersion) HttpObjectAggregator(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpObjectAggregator) IdleStateHandler(org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateHandler) ServiceLoader(java.util.ServiceLoader) JavaType(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JavaType) Preconditions(org.apache.flink.util.Preconditions) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf) Collectors(java.util.stream.Collectors) List(java.util.List) SocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel) HttpClientCodec(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpClientCodec) DefaultHttpDataFactory(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.DefaultHttpDataFactory) Optional(java.util.Optional) IdleStateEvent(org.apache.flink.shaded.netty4.io.netty.handler.timeout.IdleStateEvent) Time(org.apache.flink.api.common.time.Time) RestMapperUtils(org.apache.flink.runtime.rest.util.RestMapperUtils) Bootstrap(org.apache.flink.shaded.netty4.io.netty.bootstrap.Bootstrap) ChannelInitializer(org.apache.flink.shaded.netty4.io.netty.channel.ChannelInitializer) ConfigurationException(org.apache.flink.util.ConfigurationException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SSLHandlerFactory(org.apache.flink.runtime.io.network.netty.SSLHandlerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) ChannelHandler(org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandler) MessageHeaders(org.apache.flink.runtime.rest.messages.MessageHeaders) HttpResponseStatus(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus) ArrayList(java.util.ArrayList) FutureUtils(org.apache.flink.util.concurrent.FutureUtils) ByteBufInputStream(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufInputStream) HttpHeaders(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders) REQUEST_ENTITY_TOO_LARGE(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE) ObjectMapper(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper) ConfigConstants(org.apache.flink.configuration.ConfigConstants) RestOptions(org.apache.flink.configuration.RestOptions) RestAPIVersion(org.apache.flink.runtime.rest.versioning.RestAPIVersion) ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) ErrorResponseBody(org.apache.flink.runtime.rest.messages.ErrorResponseBody) ChannelOption(org.apache.flink.shaded.netty4.io.netty.channel.ChannelOption) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) AutoCloseableAsync(org.apache.flink.util.AutoCloseableAsync) Files(java.nio.file.Files) Executor(java.util.concurrent.Executor) StringWriter(java.io.StringWriter) Configuration(org.apache.flink.configuration.Configuration) Unpooled(org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled) IOException(java.io.IOException) JsonProcessingException(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException) File(java.io.File) VisibleForTesting(org.apache.flink.annotation.VisibleForTesting) TimeUnit(java.util.concurrent.TimeUnit) NioSocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel) ResponseBody(org.apache.flink.runtime.rest.messages.ResponseBody) TooLongFrameException(org.apache.flink.shaded.netty4.io.netty.handler.codec.TooLongFrameException) HttpPostRequestEncoder(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.multipart.HttpPostRequestEncoder) HttpMethod(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpMethod) Comparator(java.util.Comparator) Collections(java.util.Collections) Channel(org.apache.flink.shaded.netty4.io.netty.channel.Channel) InputStream(java.io.InputStream) CompletableFuture(java.util.concurrent.CompletableFuture) SocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.socket.SocketChannel) NioSocketChannel(org.apache.flink.shaded.netty4.io.netty.channel.socket.nio.NioSocketChannel) Channel(org.apache.flink.shaded.netty4.io.netty.channel.Channel) IOException(java.io.IOException)

Aggregations

JavaType (com.fasterxml.jackson.databind.JavaType)322 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)36 Test (org.junit.Test)29 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)25 IOException (java.io.IOException)25 BeanPropertyDefinition (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)22 ArrayList (java.util.ArrayList)21 TypeFactory (com.fasterxml.jackson.databind.type.TypeFactory)17 Property (io.swagger.models.properties.Property)16 List (java.util.List)16 Map (java.util.Map)14 ModelImpl (io.swagger.models.ModelImpl)13 StringProperty (io.swagger.models.properties.StringProperty)13 Annotation (java.lang.annotation.Annotation)12 Method (java.lang.reflect.Method)11 Type (java.lang.reflect.Type)11 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)10 BodyParameter (io.swagger.models.parameters.BodyParameter)10 MapProperty (io.swagger.models.properties.MapProperty)10 JsonDeserializer (com.fasterxml.jackson.databind.JsonDeserializer)9