MappingJackson2HttpMessageConverter & Serialization - rest

Based on the below guide
https://spring.io/guides/gs/rest-service/
MappingJackson2HttpMessageConverter converts the Greeting Object to JSON. Question is, why isn't Greeting Object implementing Serializable? Is it a miss in the guide or not required?

Implementing Serializable is necessary for native Java serialization.
JSON marshalling with Jackson doesn't need it.

Related

Can't map property String to JAXBElement<String> using MapStruct

so I was playing a bit with Mapstruct, reading the reference Documentation for the Version 1.1.0.Final, and arrived at the point:
implicit type conversions
where is defined the following statement:
Between JAXBElement < T> and T
I tried that, but the error what I received was:
Can't map property "java.lang.String xmlElement" "javax.xml.bind.JAXBElement<java.lang.String> xmlElement".
Consider to declare/implement a mapping method:
javax.xml.bind.JAXBElement<java.lang.String> map(java.lang.String value)".
I know thisi is the same thread asCan't map property when using MapStruct but since then Mapstruct released a new version.
Am I doing something wrong or this feature really is missing?
Thank you.
Mapping from JAXBElement<T> to T works out of the box. For the reverse you need to make sure that the ObjectFactory(ies) are in the Mapper#uses, MapStruct uses those methods to create the types.
You can also have a look at this integration test.
In case this happens on Java 9 or higher and you use implementation of type JAXBElement from maven library (in my case'javax.xml.bind:jaxb-api') make sure it is on the classpath of the annotation processor - this resolved the issue for me.
If your JAXBElement was generated by a wsdl client generator (eg. xjc) you need to provide the corresponding ObjectFactory.class generated by the client generator:
#Mapper(uses = ObjectFactory.class)
public interface OrderMapper {
Order orderEntityToExternalOrder(OrderEntity orderEntity);
}
See:
MapStruct 1.0.0.Beta1 is out with JAXB support, custom factories, decorators and more

Implementing Hypermedia in RESTful JAX-RS Apache CXF

I am working in a RESTful application developed in Apache CXF and I would like to introduce hypermedia functionality to it.
Most of our jaxrs:serviceBeans follow this template:
#GET
#Path("/{exampleId}")
public ExampleJSON get(#PathParam("exampleId") Integer exampleId) {
ExampleJSON example;
// Load data from repository here...
// Add link to self.
String href = javax.ws.rs.core.Link.fromResource(ExampleService.class).build().getUri().toString();
// HypermediaLink is a custom object to hold a "href" and "rel" strings
HypermediaLink linkToSelf = new HypermediaLink();
linkToSelf.setHref(href + example.getId());
linkToSelf.setRel("self");
// Inherited method, just adds a HypermediaLink to a collection in the parent class
example.addHypermediaLink(linkToSelf);
// Return JSON compatible object, JACKSON will serialize it nicely.
return example;
}
This is the basic concept. Keep in mind that I simplified this code for explanation purposes; so, it can be easily understood.
This code works fine; but I am wondering if there is a better way to do this with Apache CXF. I have some ideas for how to enhancing it; however, it will require some custom annotations.
I see some examples using Jersey, but I would like to stick with Apache CXF.
Any help would be appreciated.
Thanks
I would leverage some features of JAX-RS and / or Jackson to implement the link adding under the hood at the serialization level. So you wouldn't need to have a specific field for the link within the bean itself.
You could implement a custom MessageBodyWriter to generate a different JSON payload (for example) for your POJOs than the default. So you could dynamically add the link.
See this answer for more details: How to write an XML MessageBodyWriter provider with jersey.
If you use Jackson for the serialization, you could implement a custom serializer. Note that this is generic and will work for all supported format of Jackson.
Below is a sample code:
public class LinkBeanSerializer extends JsonSerializer<SomeBean> {
#Override
public void serialize(SomeBean bean, JsonGenerator jgen,
SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.writeStartObject();
// Fields
jgen.writeNumberField("id", bean.getId());
// Things could be generic using reflection
// Link
String href = javax.ws.rs.core.Link.fromResource(SomeBean.class).build().getUri().toString();
HypermediaLink linkToSelf = new HypermediaLink();
linkToSelf.setHref(href + bean.getId());
linkToSelf.setRel("self");
jgen.writeObjectField("hypermediaLink", linkToSelf);
jgen.writeEndObject();
}
}
Note that we could make this serializer more generic I think (something like extends JsonSerializer<Object>)
See this answer for more details: Processing JSON response using JAX-RS (how to register the custom serializer within JAX-RS, ...).
Perhaps implementing a WriterInterceptor could solve your problem but there is impact on the beans since you need to have field hypermediaLink. The interceptor could be responsible of filling the field.
See this answer for more details: Jersey Update Entity Property MessageBodyWriter.
IMO the more convenient solution is the second one. It's transparent and support all the formats supported by Jackson.
Hope it helps you,
Thierry

Custom field serializer / deserializer

I am able to load some entities into ElasticSearch with out-of-the box Spring Data ElasticSearch. The thing is my model classes contemplate many properties and for some of those I don't want my representation (typing) be reflected into ES.
#Field(serializer = MyCustomSerializer, deserializer = MyCustomDeserializer)
private SomeClass someObject;
I'd like, for example, for SomeClass to be serialized as a String, so I can query it as such. Also, when reading data from ES, I want to be able to write a custom deserializer (MyCustomDeserializer) to convert this String into my own model.
Is there any way I can accomplish that??
Thanks
Spring Data ElasticSearch uses jackson to serialize the fields, so you could achieve custom serialization logic by defining:
#JsonSerialize(using = MyCustomSerializer.class)
#JsonDeserialize(using = MyCustomDeserializer.class)
private SomeClass someObject;
Or configure your mapping globally in a jackson ObjectMapper, replacing the default EntityMapper from spring-data-elasticsearch. More on that here.

how to readResolve the object deserialized by Spring Data from Mongodb

We are using flyweight pattern for some objects in our system. Those objects are also saved in database (mongodb). After loading the object back from db using Spring Data, there is no easy way to replace the object constructed by Spring Data with the object in the flyweight cache. For Java deserialization, there is readResolve() method. I wonder if Spring Data can add something similar to support this use case.
Is there any solutions with the current Spring Data implementation (1.4.1 release)?
They must have something otherwise enums wouldn't work either... I'd consider custom converters, e.g. here (look for the last section with PersonReadConverer):
http://docs.spring.io/spring-data/mongodb/docs/1.4.x/reference/html/mapping-chapter.html
I just hope it works when Person is a nested field inside another class - didn't get a chance to test it .
Good luck
Thanks #Pelit_Mamani for some suggestions. I did try to implement a converter and set it in mongo mapping converter and it seems to work. It works even when the object is embedded in other object.
<mongo:mapping-converter id="mappingConverter" base-package="com.mytest.domain" db-factory-ref="mongoDbFactory" disable-validation="true">
<mongo:custom-converters>
<mongo:converter>
<bean class="com.mytest.repo.converter.MyReadConverter" />
</mongo:converter>
</mongo:custom-converters>
</mongo:mapping-converter>
And the converter class:
public class MyReadConverter implements Converter<DBObject, MyObject>

Hibernate, Gilead and GWT

I'm experiencing some problems with GWT and Gilead/Hibernate
I did my code according to the tutorial but it fails with
com.google.gwt.user.client.rpc.SerializationException: Type 'ru.atamur.entity.UserEntity_gilead_15' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = ru.atamur.entity.UserEntity_gilead_15#133fa82
Looking at the source code I can see that Gilead transformed my UserEntity into UserEntity_gilead_15 inside GileadRPCHelper.parseReturnValue(returnValue, _beanManager)
I can see that this was deliberately done by ProxyClassMapper (I'm trying to use proxy mode), so I was wondering where Gilead was expecting to tell GWT Serilization mechanism about this new proxy class it introduced ...
Can you share your code ?
before that I want to say that SerializationException is thrown when your class doesn't implement isSerializable interface that you send it to the server.
Every class that you send to the server should implement isSerializable interface