Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: [#820] Support for JAXB #914

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ Not yet released
* Only expose `Serializable` `EntityViewManager` wrapper in special methods or callbacks
* Support `@PostCreate` and other lifecycle methods with default and even private visibility
* Support `@ViewFilter` inheritance
* Fix collection deserialization issues with Jackson

### Backwards-incompatible changes

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,13 @@
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMember;
import javassist.CtMethod;
import javassist.CtPrimitiveType;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.AccessFlag;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.AttributeInfo;
import javassist.bytecode.BadBytecode;
import javassist.bytecode.Bytecode;
Expand All @@ -81,6 +83,8 @@
import javassist.bytecode.SignatureAttribute;
import javassist.bytecode.StackMap;
import javassist.bytecode.StackMapTable;
import javassist.bytecode.annotation.Annotation;
import javassist.bytecode.annotation.EnumMemberValue;
import javassist.compiler.CompileError;
import javassist.compiler.JvstCodeGen;
import javassist.compiler.Lex;
Expand Down Expand Up @@ -385,6 +389,13 @@ private <T> Class<? extends T> createProxyClass(EntityViewManager entityViewMana
CtClass cc = pool.makeClass(proxyClassName);
CtClass superCc;

// ConstPool constPool = cc.getClassFile().getConstPool();
// AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
// Annotation annotation = new Annotation("javax.xml.bind.annotation.XmlAccessorType", constPool);
// annotation.addMemberValue("value", new EnumMemberValue(constPool.addUtf8Info("javax.xml.bind.annotation.XmlAccessType"), constPool.addUtf8Info("PROPERTY"), constPool));
// annotationsAttribute.addAnnotation(annotation);
// cc.getClassFile().addAttribute(annotationsAttribute);

ClassPath classPath = new ClassClassPath(clazz);
pool.insertClassPath(classPath);

Expand Down Expand Up @@ -423,6 +434,7 @@ private <T> Class<? extends T> createProxyClass(EntityViewManager entityViewMana
cc.addInterface(pool.get(DirtyStateTrackable.class.getName()));
initialStateField = new CtField(pool.get(Object[].class.getName()), "$$_initialState", cc);
initialStateField.setModifiers(getModifiers(false));
annotateInternalField(initialStateField);
cc.addField(initialStateField);

addGetter(cc, initialStateField, "$$_getInitialState");
Expand All @@ -432,6 +444,7 @@ private <T> Class<? extends T> createProxyClass(EntityViewManager entityViewMana
cc.addInterface(pool.get(DirtyTracker.class.getName()));
mutableStateField = new CtField(pool.get(Object[].class.getName()), "$$_mutableState", cc);
mutableStateField.setModifiers(getModifiers(false));
annotateInternalField(mutableStateField);
cc.addField(mutableStateField);

CtField initializedField = new CtField(CtClass.booleanType, "$$_initialized", cc);
Expand All @@ -441,12 +454,15 @@ private <T> Class<? extends T> createProxyClass(EntityViewManager entityViewMana
readOnlyParentsField = new CtField(pool.get(List.class.getName()), "$$_readOnlyParents", cc);
readOnlyParentsField.setModifiers(getModifiers(true));
readOnlyParentsField.setGenericSignature(Descriptor.of(List.class.getName()) + "<" + Descriptor.of(Object.class.getName()) + ">;");
annotateInternalField(readOnlyParentsField);
cc.addField(readOnlyParentsField);
parentField = new CtField(pool.get(DirtyTracker.class.getName()), "$$_parent", cc);
parentField.setModifiers(getModifiers(true));
annotateInternalField(parentField);
cc.addField(parentField);
parentIndexField = new CtField(CtClass.intType, "$$_parentIndex", cc);
parentIndexField.setModifiers(getModifiers(true));
annotateInternalField(parentIndexField);
cc.addField(parentIndexField);

dirtyChecking = true;
Expand Down Expand Up @@ -479,6 +495,8 @@ private <T> Class<? extends T> createProxyClass(EntityViewManager entityViewMana
idAttribute = (AbstractMethodAttribute<? super T, ?>) viewType.getIdAttribute();
versionAttribute = (AbstractMethodAttribute<? super T, ?>) viewType.getVersionAttribute();
idField = addMembersForAttribute(idAttribute, clazz, cc, null, false, true, mutableStateField != null);
// TODO: Copy JAXB annotations from getter and setter?
annotateField(idField, "javax.xml.bind.annotation.XmlElement");
fieldMap.put(idAttribute.getName(), idField);
attributeFields[0] = idField;
attributeTypes[0] = idField.getType();
Expand Down Expand Up @@ -533,6 +551,7 @@ private <T> Class<? extends T> createProxyClass(EntityViewManager entityViewMana
} else {
dirtyField = new CtField(CtClass.longType, "$$_dirty", cc);
dirtyField.setModifiers(getModifiers(true));
annotateInternalField(dirtyField);
cc.addField(dirtyField);

boolean allSupportDirtyTracking = true;
Expand Down Expand Up @@ -572,6 +591,7 @@ private <T> Class<? extends T> createProxyClass(EntityViewManager entityViewMana

if (hasEmptyConstructor) {
// Create constructor for create models
cc.addConstructor(createEmptyConstructor(cc));
cc.addConstructor(createCreateConstructor(entityViewManager, managedViewType, cc, attributeFields, attributeTypes, idField, initialStateField, mutableStateField, methodAttributes, mutableAttributeCount, alwaysDirtyMask, unsafe));
}

Expand Down Expand Up @@ -617,6 +637,13 @@ private <T> Class<? extends T> createProxyClass(EntityViewManager entityViewMana
}
}

private CtConstructor createEmptyConstructor(CtClass cc) throws CannotCompileException {
CtConstructor constructor = new CtConstructor(new CtClass[0], cc);
constructor.setModifiers(Modifier.PUBLIC);
constructor.setBody("this((" + cc.getName() + ") null, " + cc.getName() + "#" + SerializableEntityViewManager.EVM_FIELD_NAME + ".getOptionalParameters());");
return constructor;
}

private void createSerializationSubclass(ManagedViewTypeImplementor<?> managedViewType, CtClass cc) throws Exception {
boolean hasSelfConstructor = false;
OUTER: for (MappingConstructor<?> constructor : managedViewType.getConstructors()) {
Expand Down Expand Up @@ -1148,6 +1175,7 @@ private void addIsNewMembers(ManagedViewType<?> managedViewType, CtClass cc, Cla
if (managedViewType.isCreatable()) {
CtField isNewField = new CtField(CtClass.booleanType, "$$_isNew", cc);
isNewField.setModifiers(getModifiers(true));
annotateInternalField(isNewField);
cc.addField(isNewField);

addGetter(cc, isNewField, "$$_isNew");
Expand All @@ -1162,6 +1190,21 @@ private void addIsNewMembers(ManagedViewType<?> managedViewType, CtClass cc, Cla
}
}
}

private void annotateInternalField(CtMember member) {
annotateField(member, "javax.xml.bind.annotation.XmlTransient");
}

private void annotateField(CtMember member, String fqn) {
// ConstPool constPool = member.getDeclaringClass().getClassFile().getConstPool();
// AnnotationsAttribute annotationsAttribute = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
// annotationsAttribute.addAnnotation(new Annotation(fqn, constPool));
// if (member instanceof CtField) {
// ((CtField) member).getFieldInfo().addAttribute(annotationsAttribute);
// } else {
// ((CtMethod) member).getMethodInfo().addAttribute(annotationsAttribute);
// }
}

private CtMethod addGetter(CtClass cc, CtField field, String methodName) throws CannotCompileException {
return addGetter(cc, field, methodName, field.getFieldInfo().getDescriptor(), false);
Expand Down Expand Up @@ -1240,6 +1283,9 @@ private void createGettersAndSetters(AbstractMethodAttribute<?, ?> attribute, Cl
List<Method> bridgeGetters = getBridgeGetters(clazz, attribute, getter);

CtMethod attributeGetter = addGetter(cc, attributeField, getter.getName());
if (isId) {
annotateInternalField(attributeGetter);
}

if (genericSignature != null) {
String getterGenericSignature = "()" + genericSignature;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1434,6 +1434,7 @@ private static void printConstructors(StringBuilder sb, MetaEntityView entity, C
boolean postLoadReflection = preparePostLoad(sb, entity, context);
if (entity.hasEmptyConstructor()) {
if (entity.getMembers().size() > 0) {
printEmptyConstructor(sb, entity, context);
printCreateConstructor(sb, entity, context);
sb.append(NEW_LINE);
}
Expand Down Expand Up @@ -1760,6 +1761,12 @@ private static void printTupleAssignmentConstructor(StringBuilder sb, MetaConstr
sb.append(NEW_LINE);
}

private static void printEmptyConstructor(StringBuilder sb, MetaEntityView entity, Context context) {
sb.append(" public ").append(entity.getSimpleName()).append(IMPL_CLASS_NAME_SUFFIX).append("() {").append(NEW_LINE);
sb.append(" super((").append(entity.getSimpleName()).append(IMPL_CLASS_NAME_SUFFIX).append(") null, ").append(EVM_FIELD_NAME).append(".getOptionalParameters());").append(NEW_LINE);
sb.append(" }").append(NEW_LINE);
}

private static void printCreateConstructor(StringBuilder sb, MetaEntityView entity, Context context) {
boolean postCreateReflection = false;
if (entity.getPostCreate() != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,14 @@ public class CatRestController {
@Autowired
private CatViewRepository catViewRepository;

@RequestMapping(path = "/cats", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(path = "/cats", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<String> createCat(@RequestBody CatCreateView catCreateView) {
catViewRepository.save(catCreateView);

return ResponseEntity.ok(catCreateView.getId().toString());
}

@RequestMapping(path = "/cats/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(path = "/cats/{id}", method = RequestMethod.PUT, consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<String> updateCat(@PathVariable("id") long id, @RequestBody CatUpdateView catUpdateView) {
catViewRepository.save(catUpdateView);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,15 @@
import com.blazebit.persistence.view.CreatableEntityView;
import com.blazebit.persistence.view.EntityView;

import javax.xml.bind.annotation.XmlRootElement;

/**
* @author Christian Beikov
* @since 1.4.0
*/
@CreatableEntityView
@EntityView(Cat.class)
@XmlRootElement(name = "cat")
public interface CatCreateView extends CatUpdateView {

PersonIdView getOwner();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@
import com.blazebit.persistence.view.EntityView;
import com.blazebit.persistence.view.UpdatableEntityView;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
* @author Christian Beikov
* @since 1.4.0
*/
@UpdatableEntityView
@EntityView(Cat.class)
@XmlRootElement(name = "cat")
public interface CatUpdateView extends CatSimpleView {

void setName(String name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
Expand All @@ -33,6 +34,7 @@

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;

/**
* @author Christian Beikov
Expand Down Expand Up @@ -61,6 +63,10 @@ public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, Bean
}
});
objectMapper.registerModule(module);
// We need this property, otherwise Jackson thinks it can use non-visible setters as mutators
objectMapper.configure(MapperFeature.INFER_PROPERTY_MUTATORS, false);
// Obviously, we don't want fields to be set which are final because these are read-only
objectMapper.configure(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS, false);
objectMapper.setVisibility(new VisibilityChecker.Std(JsonAutoDetect.Visibility.DEFAULT) {
@Override
public boolean isGetterVisible(Method m) {
Expand All @@ -81,6 +87,20 @@ public boolean isIsGetterVisible(Method m) {
public boolean isIsGetterVisible(AnnotatedMethod m) {
return metamodel.managedView(m.getDeclaringClass()) == null && super.isGetterVisible(m);
}

// We make setters for collections "invisible" so that is uses a SetterlessProperty to always merge values into existing collections

@Override
public boolean isSetterVisible(Method m) {
Class<?> rawParameterType;
return super.isSetterVisible(m) && !Collection.class.isAssignableFrom(rawParameterType = m.getParameterTypes()[0]) && !Map.class.isAssignableFrom(rawParameterType);
}

@Override
public boolean isSetterVisible(AnnotatedMethod m) {
Class<?> rawParameterType;
return super.isSetterVisible(m) && !Collection.class.isAssignableFrom(rawParameterType = m.getRawParameterType(0)) && !Map.class.isAssignableFrom(rawParameterType);
}
});

this.objectMapper = objectMapper;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;

/**
* @author Christian Beikov
Expand Down Expand Up @@ -233,4 +234,49 @@ interface CreatableAndUpdatableViewWithNested {
CreatableAndUpdatableViewWithSetters getParent();
void setParent(CreatableAndUpdatableViewWithSetters parent);
}

@Test
public void testCreatableWithCollection() throws Exception {
EntityViewAwareObjectMapper mapper = mapper(CreatableWithCollection.class, CreatableAndUpdatableViewWithSetters.class, NameView.class);
ObjectReader objectReader = mapper.readerFor(mapper.getObjectMapper().constructType(CreatableWithCollection.class));
CreatableWithCollection view = objectReader.readValue("{\"name\": \"test\", \"children\": [{\"name\": \"parent\"}]}");
Assert.assertTrue(((EntityViewProxy) view).$$_isNew());
Assert.assertEquals("test", view.getName());
Assert.assertEquals(mapper.getEntityViewManager().getChangeModel(view).get("children").getInitialState(), view.getChildren());
Assert.assertEquals(1, view.getChildren().size());
}

@EntityView(SomeEntity.class)
@CreatableEntityView
@UpdatableEntityView
interface CreatableWithCollection {
@IdMapping
long getId();
String getName();
void setName(String name);
Set<CreatableAndUpdatableViewWithSetters> getChildren();
}

@Test
public void testCreatableWithCollectionWithSetter() throws Exception {
EntityViewAwareObjectMapper mapper = mapper(CreatableWithCollectionWithSetter.class, CreatableAndUpdatableViewWithSetters.class, NameView.class);
ObjectReader objectReader = mapper.readerFor(mapper.getObjectMapper().constructType(CreatableWithCollectionWithSetter.class));
CreatableWithCollectionWithSetter view = objectReader.readValue("{\"name\": \"test\", \"children\": [{\"name\": \"parent\"}]}");
Assert.assertTrue(((EntityViewProxy) view).$$_isNew());
Assert.assertEquals("test", view.getName());
Assert.assertEquals(mapper.getEntityViewManager().getChangeModel(view).get("children").getInitialState(), view.getChildren());
Assert.assertEquals(1, view.getChildren().size());
}

@EntityView(SomeEntity.class)
@CreatableEntityView
@UpdatableEntityView
interface CreatableWithCollectionWithSetter {
@IdMapping
long getId();
String getName();
void setName(String name);
Set<CreatableAndUpdatableViewWithSetters> getChildren();
void setChildren(Set<CreatableAndUpdatableViewWithSetters> children);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@

import com.blazebit.persistence.integration.jackson.EntityViewIdValueAccessor;
import com.blazebit.persistence.spring.data.webmvc.KeysetPageableArgumentResolver;
import com.blazebit.persistence.spring.data.webmvc.impl.json.EntityViewAwareMappingJackson2HttpMessageConverter;
import com.blazebit.persistence.spring.data.webmvc.impl.json.EntityViewIdHandlerInterceptor;
import com.blazebit.persistence.spring.data.webmvc.impl.json.EntityViewIdValueHolder;
import com.blazebit.persistence.view.EntityViewManager;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
Expand Down Expand Up @@ -73,6 +70,7 @@ public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentRes
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// Add it to the beginning so it has precedence over the builtin
converters.add(0, new EntityViewAwareMappingJackson2HttpMessageConverter(entityViewManager, idAttributeAccessor()));
converters.add(1, new EntityViewAwareJaxb2RootElementHttpMessageConverter(entityViewManager));
}

@Override
Expand Down
Loading