Wildfly ignoring jackson annotations and not using #Provider class - java

I have looked around here and don't think this is a duplicate of any of these:
using Jackson annotations in Wildfly
jackson annotations being ignored
Wildfly and Jackson #JsonIgnore annotation
Using Wildfly 10 and deploying a war with the following class:
#Provider
public class JaxApplication implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public JaxApplication() {
mapper = new ObjectMapper();
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//throw new RuntimeException("HERE");
}
#Override
public ObjectMapper getContext(Class<?> type) {
throw new RuntimeException("HERE");
//return mapper;
}
}
I see the exception in the constructor thrown when I deploy if it's not commented, but I don't see the one from the getContext method when I make a request to my REST service.
I have a #JsonIgnore annotation on an entity and it's not working, nor is the #JsonIdentityInfo annotation I'm using
That class looks like this (imports included, to verify I'm using com.fasterxml.*)
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* Created by mb995a on 7/29/2016.
*/
#Entity
#JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="#request_id", scope=Request.class)
public class Request extends BaseEntity {
Do I need to do something special in my REST config?
#ApplicationPath("api")
public class RestApplication extends Application {
public RestApplication() {
super();
}
}
Any ideas?
Edited to say: I also have a unit test that uses an ObjectMapper and it serializes properly.

For anyone else, I figured this out. The problem was that I had jackson jars in my pom that were not marked as "provided" scope. This meant that I had jars in my war file's WEB-INF/lib directory.
Even though they are the exact same version of Wildfly's jars (I use the same version properties as the WF version I'm using) they do not work properly. Looks like the hashCode() is different for the same annotation from different jars even if they are the exact same (checksum and everything).
So, the solution was to mark the dependencies as provided in maven for all Jackson stuff.

Related

How to get a list of Java class dependencies programmatically

Essentially I'm asking something similar to this: How do I get a list of Java class dependencies for a main class? but I'd like to do it using a Java API. I'd prefer not to exec jdeps and scrape the output.
Extra points if it uses https://github.com/classgraph/classgraph since our project already uses that library and it is awesome for scanning classes without actually instantiating everything it processes.
Oh, and this would be restricted to working on JDK 8.
[Update]
Here is a bit more background. Let's say I have a bundled application. Perhaps a Spring Boot app or something that can be deployed to a cloud platform like Cloud Foundry or Heroku. The app probably contains framework jars (like Spring), utility jars (logging, templating, json/xml processing, etc.), application domain classes and then all necessary transitive dependencies. Assume this is all either bundled into an uber-jar or referenced via a classpath.
My use case would be: Given a class, and the uber-jar/classpath, what is the subset of jars (out of that uber-jar) that my given class requires as dependencies to instantiate it?
Turns out that I can do what I want with classgraph. The key is to set enableInterClassDependencies. Given a class, the following will process all dependencies, of that class, and determine which jars contain the relevant dependent classes:
import java.net.URI;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ClassInfo;
import io.github.classgraph.ClassInfoList;
import io.github.classgraph.ScanResult;
public class DependencyFinder {
private final String clazz;
public DependencyFinder(String clazz) {
this.clazz = clazz;
}
public Set<URI> process() {
ScanResult scanResult = new ClassGraph()
.whitelistPackages()
.enableInterClassDependencies()
.scan();
ClassInfo rootClass = scanResult.getClassInfo(clazz);
Map<ClassInfo, ClassInfoList> dependencyMap = scanResult.getClassDependencyMap();
Set<URI> results = new HashSet<>();
Set<ClassInfo> seen = new HashSet<>();
accumulateJars(new HashSet<>(dependencyMap.get(rootClass)), dependencyMap, results, seen);
return results;
}
private void accumulateJars(Set<ClassInfo> roots, Map<ClassInfo, ClassInfoList> dependencies, Set<URI> accumulated, Set<ClassInfo> seen) {
Set<ClassInfo> nextRoots = new HashSet<>();
for (ClassInfo info : roots) {
if (seen.contains(info)) {
continue;
}
accumulated.add(info.getClasspathElementURI());
seen.add(info);
nextRoots.addAll(dependencies.get(info));
}
if (nextRoots.size() > 0) {
accumulateJars(nextRoots, dependencies, accumulated, seen);
}
}
}

Resteasy exports dates in textual format on wildfly 14 (Java 11) as opposed to numeric format in wildfly 9 (Java 8)

I have a project that works fine on Java 8 running on Wildfly 9.
I use some REST endpoints to serialize some Java objects to JSON. This is configured with Resteasy and #Produces(MediaType.APPLICATION_JSON).
I'm now trying to convert the project to work on wildfly 14 and Java 11.
For some reason in the previous version, Dateobjects were exported as a numeric value. In the new environment, dates are exported in a textual format (e.g. 2018-12-03T10:05:33.39Z[UTC]).
The strange thing is that some data properties of some objects are still exported in the numeric format and others are exported in the textual format.
I've tried enabling the WRITE_DATES_AS_TIMESTAMPS feature but this doesn't change the result.
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
#Provider
#Produces(MediaType.APPLICATION_JSON)
public class JacksonConfig implements ContextResolver<ObjectMapper> {
private final ObjectMapper objectMapper;
public JacksonConfig()
{
objectMapper = new ObjectMapper();
objectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
#Override
public ObjectMapper getContext(Class<?> objectType)
{
return objectMapper;
}
}
The issue was related to the switch from jackson to jsonb.
It is further explained in this thread.

Can't make Jackson and Lombok work together

I am experimenting in combining Jackson and Lombok. Those are my classes:
package testelombok;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Value;
import lombok.experimental.Wither;
#Value
#Wither
#AllArgsConstructor(onConstructor=#__(#JsonCreator))
public class TestFoo {
#JsonProperty("xoom")
private String x;
private int z;
}
package testelombok;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xebia.jacksonlombok.JacksonLombokAnnotationIntrospector;
import java.io.IOException;
public class TestLombok {
public static void main(String[] args) throws IOException {
TestFoo tf = new TestFoo("a", 5);
System.out.println(tf.withX("b"));
ObjectMapper om = new ObjectMapper().setAnnotationIntrospector(new JacksonLombokAnnotationIntrospector());
System.out.println(om.writeValueAsString(tf));
TestFoo tf2 = om.readValue(om.writeValueAsString(tf), TestFoo.class);
System.out.println(tf2);
}
}
Those are the JARs that I'm adding into the classpth:
Lombok: https://projectlombok.org/downloads/lombok.jar (version 1.16.10)
Jackson annotations: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.8.2/jackson-annotations-2.8.2.jar
Jackson core: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.8.2/jackson-core-2.8.2.jar
Jackson databind: http://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.8.2/jackson-databind-2.8.2.jar
Jackson-lombok: http://repo1.maven.org/maven2/io/paradoxical/jackson-lombok/1.1/jackson-lombok-1.1.jar
I am compiling it with Netbeans (I don't think that this is really relevant, but I am reporting this anyway to make it perfectly and faithfully reproducible). The five JARs above are kept in a folder called "lib" inside the project folder (along with "src", "nbproject", "test" and "build"). I added them to Netbeans via the "Add JAR/Folder" button in the project properties and they are listed in the exact order as the list above. The project is a standard "Java application" type project.
Further, the Netbeans project is configured to "do NOT compile on save", "generate debugging info", "report deprecated APIs", "track java dependencies", "activacte annotation proccessing" and "activacte annotation proccessing in the editor". No annotation processor or annotation processing option is explicitly configured in Netbeans. Also, the "-Xlint:all" command line option is passed in the compiler command line, and the compiler runs on an external VM.
My javac's version is 1.8.0_72 and my java's version is 1.8.0_72-b15. My Netbeans is 8.1.
My project compiles fine. However, it throws an exception in its execution. The exception don't seems to be anything that looks easily or obvious fixable. Here is the output, including the stacktrace:
TestFoo(x=b, z=5)
{"z":5,"xoom":"a"}
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Argument #0 of constructor [constructor for testelombok.TestFoo, annotations: {interface java.beans.ConstructorProperties=#java.beans.ConstructorProperties(value=[x, z]), interface com.fasterxml.jackson.annotation.JsonCreator=#com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator
at [Source: {"z":5,"xoom":"a"}; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:296)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:269)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:475)
at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3890)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3785)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2833)
at testelombok.TestLombok.main(TestLombok.java:14)
Caused by: java.lang.IllegalArgumentException: Argument #0 of constructor [constructor for testelombok.TestFoo, annotations: {interface java.beans.ConstructorProperties=#java.beans.ConstructorProperties(value=[x, z]), interface com.fasterxml.jackson.annotation.JsonCreator=#com.fasterxml.jackson.annotation.JsonCreator(mode=DEFAULT)}] has no property name annotation; must have name when multiple-parameter constructor annotated as Creator
at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._addDeserializerConstructors(BasicDeserializerFactory.java:511)
at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory._constructDefaultValueInstantiator(BasicDeserializerFactory.java:323)
at com.fasterxml.jackson.databind.deser.BasicDeserializerFactory.findValueInstantiator(BasicDeserializerFactory.java:253)
at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:219)
at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:141)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:406)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:352)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
... 7 more
I already tried about randomly poking with the #Value and #AllArgsConstructor annotations, but I couldn't make it any better.
I google'd the exception and found an old bug report on jackson, and another one that is open, but seems to be related to something else. However, this still do not tells anything about what is this bug or how to fix it. Also, I could not find anything useful looking that somewhere else.
Since what I am trying to do is very basic usage of both lombok and jackson, it seems odd that I couldn't find any more useful information about how to workaround this issue. Maybe I missed something?
Other than just saying "don't use lombok" or "don't use jackson", do anybody has any idea about how to solve this?
If you want immutable but a json serializable POJO using lombok and jackson.
Use jacksons new annotation on your lomboks builder #JsonPOJOBuilder(withPrefix = "")
I tried this solution and it works very well.
Sample usage
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import lombok.Builder;
import lombok.Value;
#JsonDeserialize(builder = Detail.DetailBuilder.class)
#Value
#Builder
public class Detail {
private String url;
private String userName;
private String password;
private String scope;
#JsonPOJOBuilder(withPrefix = "")
public static class DetailBuilder {
}
}
If you have too many classes with #Builder and you want don't want the boilerplate code empty annotation you can override the annotation interceptor to have empty withPrefix
mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
#Override
public JsonPOJOBuilder.Value findPOJOBuilderConfig(AnnotatedClass ac) {
if (ac.hasAnnotation(JsonPOJOBuilder.class)) {//If no annotation present use default as empty prefix
return super.findPOJOBuilderConfig(ac);
}
return new JsonPOJOBuilder.Value("build", "");
}
});
And you can remove the empty builder class with #JsonPOJOBuilder annotation.
Immutable + Lombok + Jackson can be achieved in next way:
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Value;
#Value
#NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
#AllArgsConstructor
public class LocationDto {
double longitude;
double latitude;
}
class ImmutableWithLombok {
public static void main(String[] args) throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String stringJsonRepresentation = objectMapper.writeValueAsString(new LocationDto(22.11, 33.33));
System.out.println(stringJsonRepresentation);
LocationDto locationDto = objectMapper.readValue(stringJsonRepresentation, LocationDto.class);
System.out.println(locationDto);
}
}
I tried several of the above and they were all temperamental.
What really worked for me is the the answer I found here.
on your project's root directory add a lombok.config file (if you haven't done already)
lombok.config
and inside paste this
lombok.anyConstructor.addConstructorProperties=true
Then you can define your pojos like the following:
#Data
#AllArgsConstructor
public class MyPojo {
#JsonProperty("Description")
private String description;
#JsonProperty("ErrorCode")
private String errorCode;
}
Here is an example by using
#Jacksonized annotation:
import lombok.Value;
import lombok.Builder;
import lombok.extern.jackson.Jacksonized;
#Jacksonized
#Builder
#Value
public class User {
String name;
String surname;
}
It does require you to use #Builder annotation.
I had exactly the same issue, "solved" it by adding the suppressConstructorProperties = true parameter (using your example):
#Value
#Wither
#AllArgsConstructor(suppressConstructorProperties = true)
public class TestFoo {
#JsonProperty("xoom")
private String x;
private int z;
}
Jackson apparently does not like the java.beans.ConstructorProperties annotation added to constructors. The suppressConstructorProperties = true parameter tells Lombok not to add it (it does by default).
It can be done simpler, without extra annotations and the problem can be with the inheritance, i.e. child classes should be deserializable as well. So, my example:
Requirements:
lombok.config inside the project root directory with body containing:
lombok.anyConstructor.addConstructorProperties=true
/** The parent class **/
#Value
#NonFinal
#SuperBuilder
#RequiredArgsConstructor
public class Animal {
String name;
}
/** The child class **/
#Value
#SuperBuilder
#RequiredArgsConstructor
public class Cat {
Long tailLength;
#ConstructorProperties({"tailLength", "name})
public Cat(Long tailLength, String name) {
super(name);
this.tailLength = tailLength;
}
}
It:
Allows building of objects including fields of the parent
Serializes/Deserializes with the default ObjectMapper and Jackson
Instances of the parent and children classes are immutable
My advice against other examples:
Try not to put custom annotations on particular classes, it makes it inhomogeneous. Any way, you will come to a generic solution one day.
Try not to put Jackson annotations on any fields on constructors, it creates coupling, when Jackson is capable to serialize/deserialize without any annotations.
Do not use #AllArgsConstructor for immutable entities. When your class has only final fields, conceptually right is #RequiredArgsConstructor, that's how you guarantee that class-clients always will rely only on a constructor with the immutable entity. Will #AllArgsConstructor it might lead to passing nulls.
I found two options to solve this problem if you want to use #Builder with Jackson.
Option 1
Add private default noArgs and allArgs constructors.
#Builder
#Getter
#Setter
#JsonIgnoreProperties(ignoreUnknown = true)
#AllArgsConstructor(access = AccessLevel.PRIVATE)
#NoArgsConstructor(access = AccessLevel.PRIVATE)
public class Person {
#JsonProperty("user_name")
private String name;
}
Option 2
Thanks to this article.
Jackson expects the builder methods to start like .withProperty(...) but Lombok generates .property(...).
What you can do is to create the builder class yourself so that you can add Jackson annotations to it. Lombok will then re-use this class and add all the builder methods to it.
#JsonDeserialize(builder = MyDto.MyDtoBuilder.class)
#Builder
#Getter
public class MyDto {
#JsonProperty("user_id")
private String userId;
#JsonPOJOBuilder(withPrefix = "")
#JsonIgnoreProperties(ignoreUnknown = true)
public static class MyDtoBuilder {
}
}
You need to do some manual work
Still much better than writing the Builder yourself
Also note that additional properties like #JsonIgnorePropertie go on the builder
An additional drawback is that refactorings will not automatically rename the MyDtoBuilder. I hope in a future Lombok/Jackson version this issue is solved.
Update: I've found another solution (tested with lombok 1.18.20 and spring boot 2.4.5), added as Option 1.
#AllArgsConstructor(suppressConstructorProperties = true) is deprecated. Define lombok.anyConstructor.suppressConstructorProperties=true (https://projectlombok.org/features/configuration) and change POJO's lombok annotation from #Value to #Data + #NoArgsConstructor + #AllArgsConstructor works for me.
From Jan Rieke's Answer
Since lombok 1.18.4, you can configure what annotations are copied to
the constructor parameters. Insert this into your lombok.config:
lombok.copyableAnnotations += com.fasterxml.jackson.annotation.JsonProperty
Then just add #JsonProperty to your fields:
...
You'll need a #JsonProperty on every field even if the name matches, but that is a good practice to follow anyway. You can also set your fields to public final using this, which I prefer over getters.
#ToString
#EqualsAndHashCode
#Wither
#AllArgsConstructor(onConstructor=#__(#JsonCreator))
public class TestFoo {
#JsonProperty("xoom")
public final String x;
#JsonProperty("z")
public final int z;
}
It should also work with getters (+setters) though.
I've all my classes annotated like this:
#JsonAutoDetect(fieldVisibility = Visibility.ANY)
#JsonInclude(JsonInclude.Include.NON_DEFAULT)
#Data
#Accessors(fluent = true)
#NoArgsConstructor
#AllArgsConstructor
It worked with all Lombok and Jackson versions for, at least, a couple of years.
Example:
#JsonAutoDetect(fieldVisibility = Visibility.ANY)
#JsonInclude(JsonInclude.Include.NON_DEFAULT)
#Data
#Accessors(fluent = true)
#NoArgsConstructor
#AllArgsConstructor
public class Person {
String id;
String first;
String last;
}
And that's it.
Lombok and Jackson play together like a charm.
For me it worked when I have updated lombok version to:
'org.projectlombok:lombok:1.18.0'
I have managed to keep my classes immutable and also deserialize them by using this lombok annotation:
#NoArgsConstructor(force = true)
You can get Jackson to play with just about anything if you use its "mixin" pattern. Basically, it gives you a way to add Jackson annotations onto an existing class without actually modifying that class. I'm leaning towards recommending it here rather than a Lombok solution because this is solves a problem Jackson is having with a Jackson feature, so it's more likely to work long-term.
I would suggest you to use Gson as it does not give you all this hassle.
I added this in my spring boot app
spring.mvc.converters.preferred-json-mapper=gson
along with the dependency in maven and I solved all the problems. I didn't need to modify my lombok annotated pojos
#JsonInclude(JsonInclude.Include.NON_NULL)
#Data
public class Person {
String id;
String first;
String last;
}
Additional to the Data Class, it should be correct configured the ObjectMapper.
In this case, it is working ok with a ParameterNamesModule configuration, and setting visibility of Fields and Creator Methods
om.registerModule(new ParameterNamesModule());
om.setVisibility(FIELD, JsonAutoDetect.Visibility.ANY);
om.setVisibility(CREATOR, JsonAutoDetect.Visibility.ANY);
Then it should work as expected.
I was having issues with getting Lombok to not add the ConstructorProperies annotation so went the other way and disabled Jackson from looking at that annotation.
The culprit is JacksonAnnotationIntrospector.findCreatorAnnotation. Notice:
if (_cfgConstructorPropertiesImpliesCreator
&& config.isEnabled(MapperFeature.INFER_CREATOR_FROM_CONSTRUCTOR_PROPERTIES)
Also notice JacksonAnnotationIntrospector.setConstructorPropertiesImpliesCreator:
public JacksonAnnotationIntrospector setConstructorPropertiesImpliesCreator(boolean b)
{
_cfgConstructorPropertiesImpliesCreator = b;
return this;
}
So two options, either set the MapperFeature.INFER_CREATOR_FROM_CONSTRUCTOR_PROPERTIES to false or create a JacksonAnnotationIntrospector set setConstructorPropertiesImpliesCreator to false and set this AnnotationIntrospector into the ObjectMapper via ObjectMapper.setAnnotationIntrospector.
Notice a couple things, I am using Jackson 2.8.10 and in that version MapperFeature.INFER_CREATOR_FROM_CONSTRUCTOR_PROPERTIES does not exist. I am not sure in which version of Jackson it was added. So if it is not there, use the JacksonAnnotationIntrospector.setConstructorPropertiesImpliesCreator mechanism.
You need to have this module as well.
https://github.com/FasterXML/jackson-modules-java8
then turn on -parameters flag for your compiler.
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
I struggled with this for a moment as well. But looking through the documentation here
I can see that the onConstructor annotation parameter is considered experimental and is not supported well on my IDE (STS 4). According to the Jackson documentation, private members are not (de)serialized by default. There are quick ways to resolve this.
Add JsonAutoDetect annotation and set it appropriately to detect protected/private members. This is convenient for DTOs
#JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class SomeClass
Add a factory function with #JsonCreator annotation, this works best if you need some object validation or additional transforms.
public class SomeClass {
// some code here
#JsonCreator
public static SomeClass factory(/* params here dressing them in #JsonProperty annotations*/) {
return new SomeClass();
}
}
Of course you could just manually add the constructor in yourself also as well.
Options which worked for me
This worked for me just by adding #AllArgsConstructor in my bean.
Add mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); object mapper instance.
None of the above answers worked for me, but this below did.
What happens is that Jackson does not support the fluent getters, BUT you can tell it to use reflection to read the fields.
Try this:
#Value
#Accessors(chain = true, fluent = true)
#Builder(builderClassName = "Builder")
public static class TestFoo {
// ...
}
var foo = ...
var writer = new ObjectMapper()
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.writer();
writer.writeValueAsString(foo);
I had a different issue and it was with the boolean primitive types.
private boolean isAggregate;
It was throwing the following error as a result
Exception: Unrecognized field "isAggregate" (class
Lambok converts isAggregate to isAggregate() as a getter making the property internally to lombok as aggregate instead isAggregate. The Jackson library doesn't like it and it needs isAggregate property instead.
I updated the primitive boolean to Wrapper Boolean to work around this issue. There are other options for you if you are dealing with boolean types, see the reference below.
Sol:
private Boolean isAggregate;
ref: https://www.baeldung.com/lombok-getter-boolean

Unreferenced static inner classes treated differently by MOXy and the RI

Let's say I have the following two classes:
package example.model;
public class Model {
public static class Inner {}
public Other prop;
}
and
package example.model;
public class Other {
public static class Inner {}
public String prop;
}
and I create a JAXB context with JAXBContext.newInstance(example.model.Model.class).
With the default JAXB implementation from Java 6 this works without any annotations, and a generated model does not mention "inner". with EclipseLink I get a "Name collision. Two classes have the XML type with uri and name inner."
I know that making at least one of the inner classes #XmlTransient gets rid of the problem. What I would like to know is how this difference relates to the JAXB standard,
and, I guess, also if there is any other way to make MOXy ignore these classes like the default JAXB implementation does.
This appears to be a bug in EclipseLink JAXB (MOXy). We are currently working on a fix for the EclipseLink 2.3.3 and 2.4.0 streams. You can track our progress using the following link:
https://bugs.eclipse.org/374429
Once the fix is available you will be able to download a nightly build from the following link:
http://www.eclipse.org/eclipselink/downloads/nightly.php
Workaround
As you mention you can mark the static inner class with #XmlTransient.
package example.model;
public class Model {
#XmlTransient
public static class Inner {}
public Other prop;
}

System wide adapter in Jersey?

I'm trying configure a "system wide" custom javax.xml.bind.annotation.adapters.XmlAdapter for the java.util.Locale type in Jersey. It's easy enough to use #XmlJavaTypeAdapter on classes I control but that's not always the case (3rd party code that I can't annotate).
It seems like it would be a pretty common problem but I can't find any good examples or doco on how to handle it.
So, is it possible?
Thanks!
I can see three possible options:
Register the converter with the marshaller with setAdapter(). You can have a static builder function which adds all your 'system level' type adapters to all marshallers which you use in your application. It all depends on your definition of 'system level'
Use a delegate
Do some fancy bytecode trickery to add the annotations to existing class files.
My advice would be to use approach 1, which is simple and straightforward.
If you need to annotate classes you can't modify, you could always use the externalized metadata feature of EclipseLink JAXB (MOXy).
The metadata file would look something like:
<xml-bindings xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/oxm">
<java-types>
<java-type name="java.util.Locale">
<xml-java-type-adapter value="some.package.YourAdapter"/>
</java-type>
</java-types>
</xml-bindings>
To you EclipseLink MOXy you need to add a jaxb.properties file in with your model classes with the following entry:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
You may also want to look at JAXBIntroductions project which is intended for similar purpose. The annotation configuration is kept in a file, without requiring modification to source code. It does work nicely with Jersey, by implementing a JAX-RS provider. You can check out my blog entry which explains this in detail with an example. Here is a simple JAXBContextResolver provide for JAXBIntroductions that can be used in your Jersey application.
import com.sun.xml.bind.api.JAXBRIContext;
import org.jboss.jaxb.intros.IntroductionsAnnotationReader;
import org.jboss.jaxb.intros.IntroductionsConfigParser;
import org.jboss.jaxb.intros.configmodel.JaxbIntros;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import java.util.*;
#Provider
public class JAXBContextResolverForJAXBIntroductions implements ContextResolver<JAXBContext> {
private final JAXBContext context;
private final Set<Class> types;
private final Class[] cTypes = {Customer.class};
public JAXBContextResolverForJAXBIntroductions() throws Exception {
this.types = new HashSet(Arrays.asList(cTypes));
JaxbIntros config = IntroductionsConfigParser.parseConfig(this.getClass().getResourceAsStream("/intro-config.xml"));
IntroductionsAnnotationReader reader = new IntroductionsAnnotationReader(config);
Map<String, Object> jaxbConfig = new HashMap<String, Object>();
jaxbConfig.put(JAXBRIContext.ANNOTATION_READER, reader);
this.context = JAXBContext.newInstance(cTypes, jaxbConfig);
}
public JAXBContext getContext(Class<?> objectType) {
return (types.contains(objectType)) ? context : null;
}
}

Categories