How to send multiple types of classes into Spring stream source - jackson

I upgraded my spring stream from 1.3.0 to 2.1.2 and the default serializer was changed from Kyro (deprecated) into Jackson.
I have a kafka topic that more than one type of messages can be sent to. With Kyro I used to deserialize it into Object.class and then cast it to the relevant type of class.
With jackson I can't achieve this functionality, because I have to specify the type of class I want to deserialize to in advance, otherwise, it's been deserialized into a string.
I tried to find an example but couldn't find anything. Any ideas how can I achieve the same functionality? I want to make it as efficient as possible.

You can add hints to the Jackson encoding so it is decoded to the right concrete type:
#JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="#class")
#SpringBootApplication
#EnableBinding(Processor.class)
public class So56753956Application {
public static void main(String[] args) {
SpringApplication.run(So56753956Application.class, args);
}
#StreamListener(Processor.INPUT)
public void listen(Foo foo) {
System.out.println(foo);
}
#Bean
public ApplicationRunner runner(MessageChannel output) {
return args -> {
output.send(new GenericMessage<>(new Bar("fiz")));
output.send(new GenericMessage<>(new Baz("buz")));
};
}
#JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="#class")
public static abstract class Foo {
private String bar;
public Foo() {
super();
}
public Foo(String bar) {
this.bar = bar;
}
public String getBar() {
return this.bar;
}
public void setBar(String bar) {
this.bar = bar;
}
#Override
public String toString() {
return getClass().getName() + " [bar=" + this.bar + "]";
}
}
public static class Bar extends Foo {
public Bar() {
super();
}
public Bar(String bar) {
super(bar);
}
}
public static class Baz extends Foo {
public Baz() {
super();
}
public Baz(String bar) {
super(bar);
}
}
}
and
com.example.So56753956Application$Bar [bar=fiz]
com.example.So56753956Application$Baz [bar=buz]
See here.

You can still use Kryo if you want. You can just add it manually using #StreamMessageConverter- https://cloud.spring.io/spring-cloud-stream/spring-cloud-stream.html#spring-cloud-stream-overview-user-defined-message-converters.
With regard to "With jackson I can't achieve this functionality, because I have to specify the type of class. . ." - that is not accurate since the type of the class gets picked up from the signature of the handler method and it is transparent to you as a user.

Related

How do you adjust json config in Quarkus?

I am attempting to add a mixin to the Jackson's ObjectMapper in a Quarkus project. I have some code that looks likes this:
#Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
this.mapper = createObjectMapper();
}
#Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
private ObjectMapper createObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(MyModel.class, MyMixin.class);
return mapper;
}
}
This code worked perfectly in a Thorntail project I had. For some reason, Quarkus isn't picking this up, and the object mapper is not affected. Is there something different I have to do with the Quarkus CDI?
Updates
Apparently I was a little confused about the implementation. I should be using the Json-B api. I figured out how to change the configuration for Json-B and posted it below.
Instead of providing an ObjectMapper, you can provide a JsonbConfig so that you can customize serialization/deserialization.
Here is what I ended up using:
#Provider
public class JsonConfig implements ContextResolver<Jsonb> {
#Override
public Jsonb getContext(Class type) {
JsonbConfig config = new JsonbConfig();
config.withPropertyVisibilityStrategy(new IgnoreMethods());
return JsonbBuilder.create(config);
}
}
class IgnoreMethods implements PropertyVisibilityStrategy {
#Override
public boolean isVisible(Field field) {
return true;
}
#Override
public boolean isVisible(Method method) {
return false;
}
}
This allows you to customize your JsonbConfig. Here, mine specifically prevents access of methods for serialization/deserialization. On Quarkus with Panache, this prevents isPersistent from appearing in your JSON output.
In addition to the correct answer of #jsolum, here is a working provider which uses the fasterxml-annotations to check visibility of fields and methods:
#Provider
public class JsonConfig implements ContextResolver<Jsonb> {
#Override
public Jsonb getContext(Class aClass) {
JsonbConfig config = new JsonbConfig();
config.withPropertyVisibilityStrategy(new PropertyVisibilityStrategy() {
#Override
public boolean isVisible(Field field) {
JsonIgnore annotation = field.getAnnotation(JsonIgnore.class);
return annotation == null || !annotation.value();
}
#Override
public boolean isVisible(Method method) {
JsonIgnore annotation = method.getAnnotation(JsonIgnore.class);
return annotation == null || !annotation.value();
}
});
return JsonbBuilder.create(config);
}
}
JsonbConfig in Quarkus can be customized providing an ApplicationScoped instance of JsonbConfigCustomizer (taking #jsolum's answer into account):
#ApplicationScoped
public class JsonbFormattingConfig implements JsonbConfigCustomizer {
#Override
public void customize(JsonbConfig jsonbConfig) {
jsonbConfig.withPropertyVisibilityStrategy(new IgnoreMethods());
}
}
class IgnoreMethods implements PropertyVisibilityStrategy {
#Override
public boolean isVisible(Field field) {
return true;
}
#Override
public boolean isVisible(Method method) {
return false;
}
}
Source: https://quarkus.io/guides/rest-json#json-b

No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]

I am trying to use spring-data-solr in order to access to my Solr instance through my Spring boot application. I have the following bean class:
#SolrDocument(solrCoreName = "associations")
public class Association implements PlusimpleEntityI {
#Id
#Indexed
private String id;
#Indexed
private String name;
#Indexed
private Point location;
#Indexed
private String description;
#Indexed
private Set<String> tags;
#Indexed
private Set<String> topics;
#Indexed
private Set<String> professionals;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<String> getTags() {
return tags;
}
public void setTags(Set<String> tags) {
this.tags = tags;
}
public Set<String> getTopics() {
return topics;
}
public void setTopics(Set<String> topics) {
this.topics = topics;
}
public Set<String> getProfessionals() {
return professionals;
}
public void setProfessionals(Set<String> professionals) {
this.professionals = professionals;
}
}
I have implemented the following repository in order to access to the related information:
public interface AssociationsRepository extends SolrCrudRepository<Association, String> {
}
I have created a configuration class which looks like the following one:
#Configuration
#EnableSolrRepositories(basePackages = {"com.package.repositories"}, multicoreSupport = true)
public class SolrRepositoryConfig {
#Value("${solr.url}")
private String solrHost;
#Bean
public SolrConverter solrConverter() {
MappingSolrConverter solrConverter = new MappingSolrConverter(new SimpleSolrMappingContext());
solrConverter.setCustomConversions(new CustomConversions(null));
return solrConverter;
}
#Bean
public SolrClientFactory solrClientFactory () throws Exception {
return new MulticoreSolrClientFactory(solrClient());
}
#Bean
public SolrClient solrClient() throws Exception {
return new HttpSolrClient.Builder(solrHost).build();
}
#Bean
public SolrOperations associationsTemplate() throws Exception {
SolrTemplate solrTemplate = new SolrTemplate(solrClient());
solrTemplate.setSolrConverter(solrConverter());
return solrTemplate;
}
}
Unfortunately, when I try to read an association from my Solr instance I got the following error:
org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [org.springframework.data.solr.core.geo.Point]
I don't understand why it is not able to find a converter if I have explicitly defined it in the solrTemplate() method.
This is my POM definition:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-solr</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
Thank you for your help.
EDIT:
I've also tried with different BUILD-RELEASEs but they are highly unstable and I've found a lot of errors using them.
Alessandro, as you can see directly in the GeoConverters class on GitHub, the implemented converters are only for:
org.springframework.data.geo.Point
and not for:
org.springframework.data.solr.core.geo.Point
Simply use this class and you don't even need a custom converter for this. Spring Data for Solr will perform the conversion for you.
I'm using a slightly patched version of the 3.0.0 M4, but I'm pretty sure this solution should apply seamlessly also to your case.

How to use JMockit MockUp for default interface method

Trying to apply a MockUp on a Java 8 default interface method, and JMockit tells me that method cannot be found. This has been tried with JMockit 1.15, 1.19, and 1.25. Here's a very simple use case:
#RunWith(JMockit.class)
public class TestTest {
public interface MyInterface {
default void foo(int f) {
bar(String.valueOf(f));
}
void bar(String s);
}
public class MyClass implements MyInterface {
public void bar(String s) {
System.out.println(s);
}
}
#Test
public void testtest() throws Exception {
new MockUp<MyClass>() {
#Mock
void foo(int i) {
System.out.println("MOCKMOCK " + (i*2));
}
#Mock
void bar(String s) {
System.out.println("MOCK " + s);
}
};
MyClass baz = new MyClass();
baz.foo(5);
baz.bar("Hello world");
}
}
This gets me the error
java.lang.IllegalArgumentException: Matching real methods not found for the following mocks:
com.example.dcsohl.TestTest$1#foo(int)
at com.example.dcsohl.TestTest$1.<init>(TestTest.java:29)
at com.example.dcsohl.TestTest.testtest(TestTest.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
...
How can we #Mock this method?
Slightly modifying your use case to return strings instead of printing to standard out the following solution will work.
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import mockit.Expectations;
public class TestTest {
public interface MyInterface {
default String foo(int f) {
return bar(String.valueOf(f));
}
String bar(String s);
}
public class MyClass implements MyInterface {
public String bar(String s) {
return s;
}
}
#Test
public void testtest() throws Exception {
MyClass baz = new MyClass();
new Expectations(MyClass.class) {{
baz.foo(anyInt); result = "FOOMOCK";
baz.bar(anyString); result = "BARMOCK";
}};
assertEquals(baz.foo(5), "FOOMOCK");
assertEquals(baz.bar("Hello world"), "BARMOCK");
}
}
There are many useful examples of how to mock out interfaces with method bodies (ie default or static methods) outlined in the examples section on the jmockit github repository.
Use #Mocked instead of a MockUp, it supports default methods.

Passing complex navigation parameters with MvvmCross ShowViewModel

My complex type wouldn't pass from Show to Init method even with configured MvxJsonNavigationSerializer as specified here Custom types in Navigation parameters in v3
public class A
{
public string String1 {get;set;}
public string String2 {get;set;}
public B ComplexObject1 {get;set;}
}
public class B
{
public double Double1 {get;set;}
public double Double2 {get;set;}
}
When I pass instance of object A to ShowViewModel method I receive this object with String1 & String2 deserialized correctly but CopmlexObject1 is null.
How to deal with complex object MvvmCross serialization?
I believe there may be some gremlins in that previous answer - will log as an issue :/
There are other possible routes to achieve this type of complex serializable object navigation still using Json and overriding parts of the framework, but actually I think that it might be better to just use your own BaseViewModel's to do serialization and deserialization - e.g. use serialization code like:
public class BaseViewModel
: MvxViewModel
{
private const string ParameterName = "parameter";
protected void ShowViewModel<TViewModel>(object parameter)
where TViewModel : IMvxViewModel
{
var text = Mvx.Resolve<IMvxJsonConverter>().SerializeObject(parameter);
base.ShowViewModel<TViewModel>(new Dictionary<string, string>()
{
{ParameterName, text}
});
}
}
with deserialization like:
public abstract class BaseViewModel<TInit>
: MvxViewModel
{
public void Init(string parameter)
{
var deserialized = Mvx.Resolve<IMvxJsonConverter>().DeserializeObject<TInit>(parameter);
RealInit(deserialized);
}
protected abstract void RealInit(TInit parameter);
}
then a viewModel like this:
public class FirstViewModel
: BaseViewModel
{
public IMvxCommand Go
{
get
{
return new MvxCommand(() =>
{
var parameter = new A()
{
String1 = "Hello",
String2 = "World",
ComplexObject = new B()
{
Double1 = 42.0,
Double2 = -1
}
};
ShowViewModel<SecondViewModel>(parameter);
});
}
}
}
can navigate to something like:
public class SecondViewModel
: BaseViewModel<A>
{
public A A { get; set; }
protected override void RealInit(A parameter)
{
A = parameter;
}
}
A small addition to Stuart's answer to add type safety:
public class BaseViewModel: MvxViewModel {
protected bool ShowViewModel<TViewModel, TInit>(TInit parameter) where TViewModel: BaseViewModel<TInit> {
var text = Mvx.Resolve<IMvxJsonConverter>().SerializeObject(parameter);
return base.ShowViewModel<TViewModel>(new Dictionary<string, string> { {"parameter", text} });
}
}
public abstract class BaseViewModel<TInit> : BaseViewModel {
public void Init(string parameter)
{
var deserialized = Mvx.Resolve<IMvxJsonConverter>().DeserializeObject<TInit>(parameter);
RealInit(deserialized);
}
protected abstract void RealInit(TInit parameter);
}
ShowViewModel method now takes the same parameter type that the RealInit method instead of an object type. Also, BaseViewModel<TInit> inherits from BaseViewModel so their instances can also call the new ShowViewModel method.
The only drawback is that you have to explicitly specify the parameter type in the call like this:
ShowViewModel<StoreInfoViewModel, Store>(store);

Constructor parameter for injected class

Let's say I would like to inject an implementation of this interface:
interface IService { ... }
implemented as:
class MyService : IService
{
public MyService(string s) { }
}
in an instance of this class:
class Target
{
[Inject]
public IService { private get; set; }
}
I do the injection by calling kernel.Inject(new Target()), but what if I would like to specify the parameter s of the constructor depending on some context when calling Inject?
Is there a way to achieve such context-dependant service initialization at injection?
Thanks!
In most cases you should not use Field Injection, it should be
used only in rare cases of circular dependencies.
You should only use the kernel once at the start of your
application and never again.
Example Code:
interface IService { ... }
class Service : IService
{
public Service(string s) { ... }
}
interface ITarget { ... }
class Target : ITarget
{
private IService _service;
public Target(IServiceFactory serviceFactory, string s)
{
_service = serviceFactory.Create(s);
}
}
interface ITargetFactory
{
ITarget Create(string s);
}
interface IServiceFactory
{
IService Create(string s);
}
class NinjectBindModule : NinjectModule
{
public NinjectBindModule()
{
Bind<ITarget>().To<Target>();
Bind<IService>().To<Service>();
Bind<ITargetFactory>().ToFactory().InSingletonScope();
Bind<IServiceFactory>().ToFactory().InSingletonScope();
}
}
Usage:
public class Program
{
public static void Main(string[] args)
{
IKernel kernel = new StandardKernel(new NinjectBindModule());
var targetFactory = kernel.Get<ITargetFactory>();
var target = targetFactory.Create("myString");
target.DoStuff();
}
}
Simply done using parameters...
kernel.Inject(new Target(), new ConstructorArgument("s", "someString", true));