org.apache.johnzon.jsonb.JsonbAccessMode Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.johnzon.jsonb;
import org.apache.johnzon.jsonb.converter.JohnzonJsonbAdapter;
import org.apache.johnzon.jsonb.converter.JsonbDateConverter;
import org.apache.johnzon.jsonb.converter.JsonbLocalDateConverter;
import org.apache.johnzon.jsonb.converter.JsonbLocalDateTimeConverter;
import org.apache.johnzon.jsonb.converter.JsonbNumberConverter;
import org.apache.johnzon.jsonb.converter.JsonbValueConverter;
import org.apache.johnzon.jsonb.converter.JsonbZonedDateTimeConverter;
import org.apache.johnzon.jsonb.serializer.JohnzonDeserializationContext;
import org.apache.johnzon.jsonb.serializer.JohnzonSerializationContext;
import org.apache.johnzon.jsonb.spi.JohnzonAdapterFactory;
import org.apache.johnzon.mapper.Adapter;
import org.apache.johnzon.mapper.JohnzonAny;
import org.apache.johnzon.mapper.ObjectConverter;
import org.apache.johnzon.mapper.TypeAwareAdapter;
import org.apache.johnzon.mapper.access.AccessMode;
import org.apache.johnzon.mapper.access.BaseAccessMode;
import org.apache.johnzon.mapper.access.FieldAccessMode;
import org.apache.johnzon.mapper.access.FieldAndMethodAccessMode;
import org.apache.johnzon.mapper.access.Meta;
import org.apache.johnzon.mapper.access.MethodAccessMode;
import org.apache.johnzon.mapper.converter.ReversedAdapter;
import org.apache.johnzon.mapper.internal.AdapterKey;
import org.apache.johnzon.mapper.internal.ConverterAdapter;
import javax.json.bind.JsonbException;
import javax.json.bind.adapter.JsonbAdapter;
import javax.json.bind.annotation.JsonbCreator;
import javax.json.bind.annotation.JsonbDateFormat;
import javax.json.bind.annotation.JsonbNillable;
import javax.json.bind.annotation.JsonbNumberFormat;
import javax.json.bind.annotation.JsonbProperty;
import javax.json.bind.annotation.JsonbPropertyOrder;
import javax.json.bind.annotation.JsonbTransient;
import javax.json.bind.annotation.JsonbTypeAdapter;
import javax.json.bind.annotation.JsonbTypeDeserializer;
import javax.json.bind.annotation.JsonbTypeSerializer;
import javax.json.bind.config.PropertyNamingStrategy;
import javax.json.bind.config.PropertyOrderStrategy;
import javax.json.bind.config.PropertyVisibilityStrategy;
import javax.json.bind.serializer.JsonbDeserializer;
import javax.json.bind.serializer.JsonbSerializer;
import javax.json.stream.JsonParserFactory;
import java.io.Closeable;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
import static java.util.Arrays.asList;
import static java.util.Optional.ofNullable;
import static org.apache.johnzon.mapper.reflection.Converters.matches;
public class JsonbAccessMode implements AccessMode, Closeable {
private final PropertyNamingStrategy naming;
private final String order;
private final PropertyVisibilityStrategy visibility;
private final FieldAndMethodAccessMode delegate;
private final boolean caseSensitive;
private final Map> defaultConverters;
private final JohnzonAdapterFactory factory;
private final Collection> toRelease = new ArrayList<>();
private final Supplier parserFactory;
private final ConcurrentMap, ParsingCacheEntry> parsingCache = new ConcurrentHashMap<>();
private final BaseAccessMode partialDelegate = new BaseAccessMode(false, false) {
@Override
protected Map doFindReaders(Class> clazz) {
throw new UnsupportedOperationException();
}
@Override
protected Map doFindWriters(Class> clazz) {
throw new UnsupportedOperationException();
}
};
public JsonbAccessMode(final PropertyNamingStrategy propertyNamingStrategy, final String orderValue,
final PropertyVisibilityStrategy visibilityStrategy, final boolean caseSensitive,
final Map> defaultConverters, final JohnzonAdapterFactory factory,
final Supplier parserFactory) {
this.naming = propertyNamingStrategy;
this.order = orderValue;
this.visibility = visibilityStrategy;
this.caseSensitive = caseSensitive;
this.delegate = new FieldAndMethodAccessMode(true, true, false);
this.defaultConverters = defaultConverters;
this.factory = factory;
this.parserFactory = parserFactory;
}
@Override
public Comparator fieldComparator(final Class> clazz) {
final Comparator orderComparator = orderComparator(clazz);
return caseSensitive ? orderComparator : ((o1, o2) -> o1.equalsIgnoreCase(o2) ? 0 : orderComparator.compare(o1, o2));
}
@Override
public Factory findFactory(final Class> clazz) {
Constructor> constructor = null;
Method factory = null;
for (final Constructor> c : clazz.getConstructors()) {
if (c.isAnnotationPresent(JsonbCreator.class)) {
if (constructor != null) {
throw new IllegalArgumentException("Only one constructor or method can have @JsonbCreator");
}
constructor = c;
}
}
for (final Method m : clazz.getMethods()) {
final int modifiers = m.getModifiers();
if (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers) && m.isAnnotationPresent(JsonbCreator.class)) {
if (constructor != null || factory != null) {
throw new IllegalArgumentException("Only one constructor or method can have @JsonbCreator");
}
factory = m;
}
}
final Constructor> finalConstructor = constructor;
final Method finalFactory = factory;
final Type[] types;
final String[] params;
final Adapter, ?>[] converters;
final Adapter, ?>[] itemConverters;
if (finalConstructor != null || finalFactory != null) {
types = finalConstructor != null ? finalConstructor.getGenericParameterTypes() : finalFactory.getGenericParameterTypes();
params = new String[types.length];
converters = new Adapter, ?>[types.length];
itemConverters = new Adapter, ?>[types.length];
int i = 0;
for (final Parameter parameter : (finalConstructor == null ? finalFactory : finalConstructor).getParameters()) {
final JsonbProperty property = getAnnotation(parameter, JsonbProperty.class);
params[i] = property != null ? property.value() : parameter.getName();
final JsonbTypeAdapter adapter = getAnnotation(parameter, JsonbTypeAdapter.class);
final JsonbDateFormat dateFormat = getAnnotation(parameter, JsonbDateFormat.class);
final JsonbNumberFormat numberFormat = getAnnotation(parameter, JsonbNumberFormat.class);
if (adapter == null && dateFormat == null && numberFormat == null) {
converters[i] = defaultConverters.get(parameter.getType());
itemConverters[i] = null;
} else {
validateAnnotations(parameter, adapter, dateFormat, numberFormat);
try {
final Adapter converter = toConverter(parameter.getType(), adapter, dateFormat, numberFormat);
if (matches(parameter.getParameterizedType(), converter)) {
converters[i] = converter;
itemConverters[i] = null;
} else {
converters[i] = null;
itemConverters[i] = converter;
}
} catch (final InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
}
i++;
}
} else {
types = null;
params = null;
converters = null;
itemConverters = null;
}
return constructor == null && factory == null ? delegate.findFactory(clazz) : (
constructor != null ?
new Factory() {
@Override
public Object create(final Object[] params) {
try {
return finalConstructor.newInstance(params);
} catch (final InstantiationException | IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (final InvocationTargetException e) {
throw new IllegalStateException(e.getCause());
}
}
@Override
public Type[] getParameterTypes() {
return types;
}
@Override
public String[] getParameterNames() {
return params;
}
@Override
public Adapter, ?>[] getParameterConverter() {
return converters;
}
@Override
public Adapter, ?>[] getParameterItemConverter() {
return itemConverters;
}
} :
new Factory() {
@Override
public Object create(final Object[] params) {
try {
final Object invoke = finalFactory.invoke(null, params);
if (!clazz.isInstance(invoke)) {
throw new IllegalArgumentException(invoke + " is not a " + clazz.getName());
}
return invoke;
} catch (final IllegalAccessException e) {
throw new IllegalStateException(e);
} catch (final InvocationTargetException e) {
throw new IllegalStateException(e.getCause());
}
}
@Override
public Type[] getParameterTypes() {
return types;
}
@Override
public String[] getParameterNames() {
return params;
}
@Override
public Adapter, ?>[] getParameterConverter() {
return converters;
}
@Override
public Adapter, ?>[] getParameterItemConverter() {
return itemConverters;
}
});
}
private void validateAnnotations(final Object parameter,
final JsonbTypeAdapter adapter, final JsonbDateFormat dateFormat,
final JsonbNumberFormat numberFormat) {
int notNull = adapter != null ? 1 : 0;
notNull += dateFormat != null ? 1 : 0;
notNull += numberFormat != null ? 1 : 0;
if (notNull > 1) {
throw new IllegalArgumentException("Conflicting @JsonbXXX on " + parameter);
}
}
private Adapter, ?> toConverter(final Type type,
final JsonbTypeAdapter adapter, final JsonbDateFormat dateFormat,
final JsonbNumberFormat numberFormat) throws InstantiationException, IllegalAccessException {
final Adapter converter;
if (adapter != null) {
final Class extends JsonbAdapter> value = adapter.value();
final ParameterizedType pt = findPt(value, JsonbAdapter.class);
if (pt == null) {
throw new IllegalArgumentException(value + " doesn't implement JsonbAdapter");
}
final JohnzonAdapterFactory.Instance extends JsonbAdapter> instance = newInstance(value);
toRelease.add(instance);
final Type[] actualTypeArguments = pt.getActualTypeArguments();
converter = new JohnzonJsonbAdapter(instance.getValue(), actualTypeArguments[0], actualTypeArguments[1]);
} else if (dateFormat != null) { // TODO: support lists, LocalDate?
if (Date.class == type) {
converter = new ConverterAdapter<>(new JsonbDateConverter(dateFormat));
} else if (LocalDateTime.class == type) {
converter = new ConverterAdapter<>(new JsonbLocalDateTimeConverter(dateFormat));
} else if (LocalDate.class == type) {
converter = new ConverterAdapter<>(new JsonbLocalDateConverter(dateFormat));
} else if (ZonedDateTime.class == type) {
converter = new ConverterAdapter<>(new JsonbZonedDateTimeConverter(dateFormat));
} else {
throw new IllegalArgumentException(type + " not a supported date type");
}
} else if (numberFormat != null) { // TODO: support lists?
converter = new ConverterAdapter<>(new JsonbNumberConverter(numberFormat));
} else {
converter = new ConverterAdapter<>(new JsonbValueConverter());
}
return converter;
}
private ParameterizedType findPt(final Class> value, final Class> type) {
return ParameterizedType.class.cast(
Stream.of(value.getGenericInterfaces())
.filter(i -> ParameterizedType.class.isInstance(i) && ParameterizedType.class.cast(i).getRawType() == type).findFirst().orElse(null));
}
private JohnzonAdapterFactory.Instance newInstance(final Class> value) {
return factory.create(value);
}
@Override
public Map findReaders(final Class> clazz) {
final Map readers = delegate.findReaders(clazz);
final Comparator keyComparator = fieldComparator(clazz);
final Map result = keyComparator == null ? new HashMap<>() : new TreeMap<>(keyComparator);
for (final Map.Entry entry : readers.entrySet()) {
final Reader initialReader = entry.getValue();
if (isTransient(initialReader, visibility) || initialReader.getAnnotation(JohnzonAny.class) != null) {
continue;
}
final Reader finalReader;
if (FieldAndMethodAccessMode.CompositeDecoratedType.class.isInstance(initialReader)) { // unwrap to use the right reader
final FieldAndMethodAccessMode.CompositeDecoratedType decoratedType = FieldAndMethodAccessMode.CompositeDecoratedType.class.cast(initialReader);
final DecoratedType type2 = decoratedType.getType2();
if (MethodAccessMode.MethodReader.class.isInstance(type2)) {
finalReader = Reader.class.cast(type2);
} else {
finalReader = initialReader;
}
} else {
finalReader = initialReader;
}
// handle optionals since mapper is still only java 7
final Type type;
final Function
© 2015 - 2025 Weber Informatics LLC | Privacy Policy