Search in sources :

Example 16 with SerdeException

use of io.micronaut.serde.exceptions.SerdeException in project micronaut-serialization by micronaut-projects.

the class OptionalMultiValuesSerializer method createSpecific.

@Override
public Serializer<OptionalMultiValues<V>> createSpecific(EncoderContext context, Argument<? extends OptionalMultiValues<V>> type) throws SerdeException {
    final Argument[] generics = type.getTypeParameters();
    if (ArrayUtils.isEmpty(generics)) {
        throw new SerdeException("Cannot serialize raw OptionalMultiValues");
    }
    final Argument generic = generics[0];
    final Argument listGeneric = Argument.listOf(generic);
    Serializer listSerializer = context.findSerializer(listGeneric).createSpecific(context, listGeneric);
    Serializer valueSerializer = context.findSerializer(generic).createSpecific(context, generic);
    return new Serializer<OptionalMultiValues<V>>() {

        @Override
        public void serialize(Encoder encoder, EncoderContext context, Argument<? extends OptionalMultiValues<V>> type, OptionalMultiValues<V> value) throws IOException {
            Objects.requireNonNull(value, "Values can't be null");
            Encoder objectEncoder = encoder.encodeObject(type);
            for (CharSequence key : value) {
                Optional<? extends List<V>> opt = value.get(key);
                if (opt.isPresent()) {
                    String fieldName = key.toString();
                    objectEncoder.encodeKey(fieldName);
                    List<V> list = opt.get();
                    if (alwaysSerializeErrorsAsList) {
                        listSerializer.serialize(objectEncoder, context, listGeneric, list);
                    } else {
                        if (list.size() == 1) {
                            valueSerializer.serialize(objectEncoder, context, generic, list.get(0));
                        } else {
                            listSerializer.serialize(objectEncoder, context, listGeneric, list);
                        }
                    }
                }
            }
            objectEncoder.finishStructure();
        }

        @Override
        public boolean isEmpty(EncoderContext context, OptionalMultiValues<V> value) {
            return value == null || value.isEmpty();
        }
    };
}
Also used : Argument(io.micronaut.core.type.Argument) Encoder(io.micronaut.serde.Encoder) SerdeException(io.micronaut.serde.exceptions.SerdeException) OptionalMultiValues(io.micronaut.core.value.OptionalMultiValues) CustomizableSerializer(io.micronaut.serde.util.CustomizableSerializer) Serializer(io.micronaut.serde.Serializer)

Example 17 with SerdeException

use of io.micronaut.serde.exceptions.SerdeException in project micronaut-serialization by micronaut-projects.

the class StreamSerializer method createSpecific.

@Override
public Serializer<Stream<T>> createSpecific(EncoderContext context, Argument<? extends Stream<T>> type) throws SerdeException {
    final Argument[] generics = type.getTypeParameters();
    if (ArrayUtils.isEmpty(generics)) {
        throw new SerdeException("Cannot serialize raw stream");
    }
    final Argument generic = generics[0];
    final Serializer componentSerializer = context.findSerializer(generic).createSpecific(context, type);
    return new Serializer<Stream<T>>() {

        @Override
        public void serialize(Encoder encoder, EncoderContext context, Argument<? extends Stream<T>> type, Stream<T> value) throws IOException {
            if (value == null) {
                throw new SerdeException("Stream is required");
            }
            Encoder arrayEncoder = encoder.encodeArray(type);
            Iterator<T> itr = value.iterator();
            while (itr.hasNext()) {
                componentSerializer.serialize(encoder, context, generic, itr.next());
            }
            arrayEncoder.finishStructure();
        }
    };
}
Also used : Argument(io.micronaut.core.type.Argument) Encoder(io.micronaut.serde.Encoder) SerdeException(io.micronaut.serde.exceptions.SerdeException) Stream(java.util.stream.Stream) CustomizableSerializer(io.micronaut.serde.util.CustomizableSerializer) Serializer(io.micronaut.serde.Serializer)

Example 18 with SerdeException

use of io.micronaut.serde.exceptions.SerdeException in project micronaut-serialization by micronaut-projects.

the class DefaultSerdeRegistry method findSerializer.

@Override
public <T> Serializer<? super T> findSerializer(Argument<? extends T> type) throws SerdeException {
    Objects.requireNonNull(type, "Type cannot be null");
    final TypeKey key = new TypeKey(type);
    final Serializer<?> serializer = serializerMap.get(key);
    if (serializer != null) {
        // noinspection unchecked
        return (Serializer<? super T>) serializer;
    } else {
        List<BeanDefinition<Serializer>> possibles = serializerDefMap.get(type.getType());
        if (possibles == null) {
            for (Map.Entry<Class<?>, List<BeanDefinition<Serializer>>> entry : serializerDefMap.entrySet()) {
                final Class<?> targetType = entry.getKey();
                if (targetType.isAssignableFrom(type.getType())) {
                    possibles = entry.getValue();
                    final Argument<?>[] params = type.getTypeParameters();
                    if (ArrayUtils.isNotEmpty(params)) {
                        // narrow for generics
                        possibles = new ArrayList<>(possibles);
                        final Iterator<BeanDefinition<Serializer>> i = possibles.iterator();
                        while (i.hasNext()) {
                            final BeanDefinition<Serializer> bd = i.next();
                            final Argument<?>[] candidateParams = bd.getTypeArguments(Serializer.class).get(0).getTypeParameters();
                            if (candidateParams.length == params.length) {
                                for (int j = 0; j < params.length; j++) {
                                    Argument<?> param = params[j];
                                    final Argument<?> candidateParam = candidateParams[j];
                                    if (!((param.getType() == candidateParam.getType()) || (candidateParam.isTypeVariable() && candidateParam.getType().isAssignableFrom(param.getType())))) {
                                        i.remove();
                                    }
                                }
                            } else {
                                i.remove();
                            }
                        }
                    }
                    break;
                }
            }
        }
        if (possibles != null) {
            if (possibles.size() == 1) {
                final BeanDefinition<Serializer> definition = possibles.iterator().next();
                final Serializer locatedSerializer = beanContext.getBean(definition);
                serializerMap.put(key, locatedSerializer);
                return locatedSerializer;
            } else if (possibles.isEmpty()) {
                throw new SerdeException("No serializers found for type: " + type);
            } else {
                final BeanDefinition<Serializer> definition = lastChanceResolve(type, possibles);
                final Serializer locatedSerializer = beanContext.getBean(definition);
                serializerMap.put(key, locatedSerializer);
                return locatedSerializer;
            }
        } else {
            serializerMap.put(key, objectSerializer);
        }
    }
    return objectSerializer;
}
Also used : Argument(io.micronaut.core.type.Argument) SerdeException(io.micronaut.serde.exceptions.SerdeException) BeanDefinition(io.micronaut.inject.BeanDefinition) TypeKey(io.micronaut.serde.support.util.TypeKey) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ObjectSerializer(io.micronaut.serde.support.serializers.ObjectSerializer) Serializer(io.micronaut.serde.Serializer)

Example 19 with SerdeException

use of io.micronaut.serde.exceptions.SerdeException in project micronaut-serialization by micronaut-projects.

the class EnumSetDeserializer method deserialize.

@Override
public EnumSet<E> deserialize(Decoder decoder, DecoderContext context, Argument<? super EnumSet<E>> type) throws IOException {
    final Argument[] generics = type.getTypeParameters();
    if (ArrayUtils.isEmpty(generics)) {
        throw new SerdeException("Cannot deserialize raw list");
    }
    @SuppressWarnings("unchecked") final Argument<E> generic = (Argument<E>) generics[0];
    final Decoder arrayDecoder = decoder.decodeArray();
    HashSet<E> set = new HashSet<>();
    while (arrayDecoder.hasNextArrayValue()) {
        set.add(Enum.valueOf(generic.getType(), arrayDecoder.decodeString()));
    }
    arrayDecoder.finishStructure();
    return EnumSet.copyOf(set);
}
Also used : Argument(io.micronaut.core.type.Argument) SerdeException(io.micronaut.serde.exceptions.SerdeException) Decoder(io.micronaut.serde.Decoder) HashSet(java.util.HashSet)

Example 20 with SerdeException

use of io.micronaut.serde.exceptions.SerdeException in project micronaut-serialization by micronaut-projects.

the class FormattedNumberSerde method deserializeNonNull.

@Override
public N deserializeNonNull(Decoder decoder, DecoderContext decoderContext, Argument<? super N> type) throws IOException {
    final String s = decoder.decodeString();
    final DecimalFormat decimalFormat = createDecimalFormat(type);
    try {
        final Number number = decimalFormat.parse(s);
        return (N) ConversionService.SHARED.convertRequired(number, type);
    } catch (Exception e) {
        throw new SerdeException("Error decoding number of type " + type + " using pattern " + pattern + ":" + e.getMessage(), e);
    }
}
Also used : DecimalFormat(java.text.DecimalFormat) SerdeException(io.micronaut.serde.exceptions.SerdeException) IOException(java.io.IOException) SerdeException(io.micronaut.serde.exceptions.SerdeException)

Aggregations

SerdeException (io.micronaut.serde.exceptions.SerdeException)20 Argument (io.micronaut.core.type.Argument)12 Encoder (io.micronaut.serde.Encoder)9 Serializer (io.micronaut.serde.Serializer)9 CustomizableSerializer (io.micronaut.serde.util.CustomizableSerializer)5 IOException (java.io.IOException)5 IntrospectionException (io.micronaut.core.beans.exceptions.IntrospectionException)4 Internal (io.micronaut.core.annotation.Internal)3 RuntimePersistentEntity (io.micronaut.data.model.runtime.RuntimePersistentEntity)3 Decoder (io.micronaut.serde.Decoder)3 AnnotationMetadata (io.micronaut.core.annotation.AnnotationMetadata)2 ConversionContext (io.micronaut.core.convert.ConversionContext)2 InstantiationException (io.micronaut.core.reflect.exception.InstantiationException)2 GeneratedValue (io.micronaut.data.annotation.GeneratedValue)2 MappedProperty (io.micronaut.data.annotation.MappedProperty)2 IdPropertyNamingStrategy (io.micronaut.data.document.serde.IdPropertyNamingStrategy)2 IdSerializer (io.micronaut.data.document.serde.IdSerializer)2 AttributeConverterRegistry (io.micronaut.data.model.runtime.AttributeConverterRegistry)2 AttributeConverter (io.micronaut.data.model.runtime.convert.AttributeConverter)2 CodecBsonDecoder (io.micronaut.serde.bson.custom.CodecBsonDecoder)2