What does it mean to observe an event with no qualifiers if all events have #Any as a qualifier? - cdi

The CDI specification says, in section 10.1:
Every event [object] has the qualifier #jakarta.enterprise.inject.Any, even if it does not explicitly declare this qualifier.
(Terminology is important; this is in a part of the spec talking about event objects, i.e. the things you fire, i.e. payloads, that can be observed by observer methods, not the poorly-named Event object, which you use to fire event objects.)
Then in section 10.4.1, talking about observer methods and their parameters, it says:
If the event parameter [of an observer method] does not explicitly declare any qualifier, the observer method observes events with no qualifier.
(This is probably distinguishing this from "ordinary" injection where if you don't put a qualifier on your injection point you get #Default by default; in this case the spec is saying no analogous default applies.)
Leaving aside how observer resolution works (covered in section 10.3), is there any state of affairs where an event object could have no qualifiers, given section 10.1? Or is section 10.4.1 just a statement about what qualifiers are automatically applied to the method parameter (namely none)?

As far as I can interpret the specification, the part from section 10.4.1
If the event parameter [of an observer method] does not explicitly
declare any qualifier, the observer method observes events with no
qualifier.
Makes the third bullet point from section 10.3 come into effect:
if [...] The observer method has no event qualifiers [...]
Therefore, the observer method received the event with the #Any qualifier.

Every event [object] has the qualifier #jakarta.enterprise.inject.Any, even if it does not explicitly declare this qualifier.
This statement is basically a prepping ground for observer resolution (10.3) and is needed in order for the 10.4.1 statement you quoted to work.
Under the hood, there are always qualifiers - at least #Any and this is also an explanation as to why your observer for, say, String type and with "no qualifier" (from user code view) gets notified for every single event of type String regardless the event payload qualifiers.
The spec wordings you quoted are basically a scaffolding allowing CDI to express what happens when user doesn't specify qualifiers all the while actually adding them in the background when appropriate and then performing resolution.
To see what I mean, try experimenting with these observers:
public void observe(#Observes String payload) {
observerTriggered++; // assuming you are counting the triggers...
}
public void observe2(#Observes #Any String payload) {
observerTriggered2++;
}
public void observe3(#Observes #Default String payload) {
observerTriggered3++;
}
public void observe4(#Observes #DummyQualifier("foo") String payload) {
observerTriggered4++;
}
And fire the following events and watch which observers get triggered:
Event<Object> event = // retrieve the event object somehow
event.select(String.class).fire("irrelevantPayload");
event.select(String.class, Any.Literal.INSTANCE).fire("irrelevantPayload");
event.select(String.class, Default.Literal.INSTANCE).fire("irrelevantPayload");
event.select(String.class, new DummyQualifier.Literal("foo")).fire("irrelevantPayload");

Related

GatewayProxyFactoryBean doesn't consider Future<Void> as a no-reply method

Looking at the message gateway methods return type semantics, the void return type indicates no reply is produced (no reply channel will be created), and the Future return type indicates asynchronous invocation mode (utilizing AsyncTaskExecutor).
Now, if one wishes to combine those two and make the no-reply method asynchronous, one could argue that the mere possibility of declaring a return type of Future<Void> would mean just that: the method is invoked asynchronously (by declaring a Future), and the method doesn't expect any reply (by declaring a type parameter Void).
Looking at the source code of GatewayProxyFactoryBean, it is clear this is not the case:
private Object invokeGatewayMethod(MethodInvocation invocation, boolean runningOnCallerThread) throws Exception {
...
boolean shouldReply = returnType != void.class;
...
Only the simple void return type is checked. So I'm wondering if this is a feature or a bug. If this is a feature, the Future<Void> return type is not behaving as one could be led to expect, and (in my opinion) should be handled differently (causing a validation error or something similar).
It's not clear what is the point of returning a Future<Void> in this case.
The reason we can't treat Future<Void> as "special" is that the downstream flow might return such an object; the framework can't imply intent.
If you want to run a flow that doesn't return a reply asynchronously, simply make the request channel an ExecutorChannel; if you are using XML configuration, documentation is here.
If you are using java configuration define the channel #Bean with type ExecutorChannel.

Multiple #ServiceActivator methods with the same inputChannel and different signature

I'm trying to implement an annotation driven event bus (e.g. Guava Event Bus) using spring integration.
I have a PublishSubscribeChannel where I publish my events and the idea is to use methods annotated with #ServiceActivator as event handlers.
Each method can have a different signature based on the event (payload) they need to handle.
What I noticed is that when an event is published, all instances of ServiceActivatingHandler created by the ServiceActivatorAnnotationPostProcessor are called and an exception for each method that has a signature that does not match the payload. E.g.
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1004E:(pos 8): Method call: Method handle(model.api.ServiceAvailableEvent) cannot be found on service.eai.TestServiceActivatorImpl2 type
Is there a way to define a #ServiceActivator method only for specific payload types?
That's correct, all the subscribers for the PublishSubscribeChannel accept the same message. And if there is no any chance to convert incoming payload into expected method argument type, we get that exception.
If you would like to filter unexpected types, you definitely have to use #Filter before your #ServiceActivator. In other words you do the same as now, but make your flow(s) a bit complex with front filters as subscribers to that PublishSubscribeChannel.
You even can rely on the existing PayloadTypeSelector:
#Bean
#Filter(inputChannel = "publishSubscribeChannel", outputChannel="service1")
public MessageSelector payloadTypeSelector() {
return new PayloadTypeSelector(...);
}
Or, yes, just simple POJO method which checks the payload type and marked with the same #Filter.
I guess your next question will be like: why doesn't #ServiceActivator ignore those types which aren't unsuitable for the target method?
Just don't mix concerns. Service Activator is for Message handling in the target business logic. For filtering and skipping we have a difefrent EI pattern - filter.

CDI extension, altering processed type

Using Weld 1.1.13.Final in test with Arquillian....
Let's say I inject into a field something volatile. Something like a property subject to change that I want the bean owning the injection point to receive change events. Thought about creating a CDI extension.
Caught ProcessAnnotatedType event and looking for all fields that have an custom annotation on field injection points:
<T> void pat(#Observes ProcessAnnotatedType<T> event, BeanManager bm) {
final AnnotatedType<T> target = event.getAnnotatedType();
for (AnnotatedField<? super T> field : target.getFields())
if (field.isAnnotationPresent(Value.class)) { // ignore that I don't check #Inject here for the moment
CtClass wrapper = pool.get(target.getJavaClass().getName());
ConstPool cp = wrapper.getClassFile().getConstPool();
CtMethod m = CtNewMethod.make(....)
....
wrapper.addMethod(m);
event.setAnnotatedType(bm.createAnnotatedType(wrapper.toClass()));
}
}
Had even grabbed thereafter all the injection points for fields and replaced the underlying WeldField with a new Field corresponding the "wrapper" type. Otherwise bean validation fails.
But this only works for stuff setup during startup not when for example Arquillian uses the Bean Manager to initialize a class that injects one of my "wraps". Things fail since the Bean Resolver uses the Type as a hash key to find beans.
Basically I don't think I can "mask" a class that is annotated (made into a bean) by the CDI with an extra method to receive custom events. Would have been cool but a Type is a Type (i.e. no idea how to proxy or fake the equals/hashCode).
Got it. Turns out the compute value function (google extension) inside the TypeSafeBeanResolver resolver (at least the CDI Weld implementation) is smart. If I just extend the class:
CtClass wrapper = pool.makeClass(target.getJavaClass().getName()+"Proxy");
wrapper.setSuperclass(pool.get(target.getJavaClass().getName()));
.....
final AnnotatedType<T> other = bm.createAnnotatedType(wrapper
.toClass());
then everything works fine. Tested capturing an event in a bean. Will post the code on a Gist with a comment.

What is the difference between static and dynamic binding?

Binding times can be classified between two types: static and dynamic. What is the difference between static and dynamic binding?
Could you give a quick example of each to further illustrate it?
In the most general terms, static binding means that references are resolved at compile time.
Animal a = new Animal();
a.Roar(); // The compiler can resolve this method call statically.
Dynamic binding means that references are resolved at run time.
public void MakeSomeNoise(object a) {
// Things happen...
((Animal) a).Roar(); // You won't know if this works until runtime!
}
It depends when the binding happens: at compile time (static) or at runtime (dynamic). Static binding is used when you call a simple class method. When you start dealing with class hierarchies and virtual methods, compiler will start using so called VTABLEs. At that time the compiler doesn't know exactly what method to call and it has to wait until runtime to figure out the right method to be invoked (this is done through VTABLE). This is called dynamic binding.
See Wikipedia article on Virtual tables for more details and references.
I came accross this perfect answer of a quora user "Monis Yousuf". He explain this perfectly. I am putting it here for others.
Binding is mostly a concept in object oriented programming related to Polymorphism.
Firstly, understand what Polymorphism is. Books say that it means "one name and multiple forms". True, but too abstract. Let us take a real-life example. You go to a "Doctor", a doctor may be an eye-specialist, ENT specialist, Neuro-Surgeon, Homeopath etc.
Here, a "doctor" is a name and may have multiple types; each performing their own function. This is polymorphism in real life.
Function Overloading: This concept depicts Static Binding. Function overloading may be roughly defined as, two or more methods (functions) which have the same name but different signatures (including number of parameters, types of parameters, differt return types) are called overloaded methods (or functions).
Suppose you have to calculate area of a rectangle and circle. See below code:-
class CalculateArea {
private static final double PI = 3.14;
/*
Method to return area of a rectangle
Area of rectangle = length X width
*/
double Area(double length, double width) {
return (length * width);
}
/*
Method to return area of circle
Area of circle = π * r * r
*/
double Area(double radius) {
return PI * radius * radius;
}
}
In above code, there are two methods "Area" with different parameters. This scenario qualifies as function overloading.
Now, coming to the real question: How is this static binding?
When you call any of the above functions in your code, you have to specify the parameters you are passing. In this scenario, you will pass either:
Two parameters of type double [Which will call the first method, to
calculate are of a rectangle]
Single parameter of type double [Which will call the second method, to calculate area of a circle]
Since, at compile time the java compiler can figure out, WHICH function to call, it is compile-time (or STATIC) binding.
Function Overriding: Function overriding is a concept which is shown in inheritance. It may roughly be defined as: when there is a method present in a parent class and its subclass also has the same method with SAME signature, it is called function overriding. [There is more to it, but for the sake of simplicity, i have written this definition] It will be easier to understand with below piece of code.
class ParentClass {
int show() {
System.out.println("I am from parent class");
}
}
class ChildClass extends ParentClass{
int show() {
System.out.println("I am from child class");
}
}
class SomeOtherClass {
public static void main (String[] s) {
ParentClass obj = new ChildClass();
obj.show();
}
}
In above code, the method show() is being overridden as the same signature (and name) is present in both parent and child classes.
In the third class, SomeOtherClass, A reference variable (obj) of type ParentClass holds the object of ChildClass. Next, the method show() is called from the same reference variable (obj).
Again, the same question: How is this Dynamic Binding?
At compile time, the compiler checks that the Reference variable is of type ParentClass and checks if the method show() is present in this class. Once it checks this, the compilation is successful.
Now, when the programs RUNS, it sees that the object is of ChildClass and hence, it runs the show() method of the ChildClass. Since this decision is taken place at RUNTIME, it is called Dynamic Binding (or Run-time Polymorphism).
Link for original answer
Static Binding: is the process of resolving types, members and operations at compile-time.
For example:
Car car = new Car();
car.Drive();
In this example compiler does the binding by looking for a parameterless Drive method on car object. If did not find that method! search for methods taking optional parameters, and if did not found that method again search base class of Car for that method, and if did not found that method again searches for extension methods for Car type. If no match found you'll get the compilation error!
I this case the binding is done by the compiler, and the binding depends on statically knowing the type of object. This makes it static binding.
Dynamic Binding: dynamic binding defers binding (The process of resolving types, members and operations) from compile-time to runtime.
For example:
dynamic d = new Car();
d.Drive();
A dynamic type tells the compiler we expect the runtime type of d to have Drive method, but we can't prove it statically. Since the d is dynamic, compiler defers binding Drive to d until runtime.
Dynamic binding is useful for cases that at compile-time we know that a certain function, member of operation exists but the compiler didn't know! This commonly occurs when we are interoperating with dynamic programming languages, COM and reflection.
Binding done at compile time is static binding and binding done at run time is dynamic binding.In static binding data type of the pointer resolves which method is invoked.But in dynamic binding data type of the object resolves which method is invoked.
* Execution time:-* bindings of variables to its values,as well as the binding of variable to particular storage location at the time of execution is called execution time binding.
IT MAY BE OF TWO TYPES
on entry to a subprogram.
At arbitrary points during execution time.
COMPILE TIME BINDING :- (TRANSLATION TIME)
It consist of the following.
Binding chosen by programmer.
Binding chosen by the translator.
Binding chosen by the loader.

Using getters within class methods

If you have a class with some plain get/set properties, is there any reason to use the getters within the class methods, or should you just use the private member variables? I think there could be more of an argument over setters (validation logic?), but I'm wondering just about getters.
For example (in Java) - is there any reason to use option 2?:
public class Something
{
private int messageId;
public int getMessageId() { return this.messageId; }
public void setMessage(int messageId) { this.messageId = messageId; }
public void doSomething()
{
// Option 1:
doSomethingWithMessageId(messageId);
// Option 2:
doSomethingWithMessageId(getMessageId());
}
}
Java programmers in general tend to be very consistent about using getter methods. I program multiple languages and I'm not that consistent about it ;)
I'd say as long as you don't make a getter it's ok to use the raw variable - for private variables. When you make a getter, you should be using only that. When I make a getter for a private field, my IDE suggests that it replace raw field accesses for me automatically when I introduce a getter. Switching to using a getter is only a few keystrokes away (and without any chance of introducing errors), so I tend to delay it until I need it.
Of course, if you want to stuff like getter-injection, some types of proxying and subclassing framworks like hibernate, you have to user getters!
With getters you wont accidentally modify the variables :) Also, if you use both getters and the "raw" variable, your code can get confused.
Also, if you use inheritance and redefined the getter methods in child classes, getter-using methods will work properly, whereas those using the raw variables would not.
If you use the getter method everywhere - and in the future perform a code-search on all calls of getMessageId() you will find all of them, whereas if you had used the private ones, you may miss some.
Also if there's ever logic to be introduced in the setter method, you wont have to worry about changing more than 1 location for it.
If the value that you are assigning to the property is a known or verified value, you could safely use the private variable directly. (Except perhaps in some special situations, where it would be obvious why that would be bad.) Whether you do or not is more a matter of taste or style. It's not a performance issue either, as the getter or setter will be inlined by the compiler if it's simple enough.
If the value is unknown to the class, you should use the property to set it, so that you can protect the property from illegal values.
Here's an example (in C#):
public class Something {
private string _value;
public string Value {
get {
return _value;
}
set {
if (value == null) throw new ArgumentNullException();
_value = value;
}
}
public Something() {
// using a known value
_value = "undefined";
}
public Something(string initValue) {
// using an unknown value
Value = initValue;
}
}
If you use the getter you're ensuring you'll get the value after any logic/decisions have been applied to it. This probably isn't your typical situation but when it is, you'll thank yourself for this.
Unless I have a specific use case to use the internal field directly in the enclosing class, I've always felt that it's important to use access the field the same way it is accessed publicly. This ensures consistency in the return values across the board should there ever be any need to add some post-processing to the field via the getter method, or property. I feel like it's perfectly fine to access the raw field if you want its raw value for one reason or another.
More often than not, the getter encapsulation is plain and simple boilerplate code -- you're most likely not returning anything other than the field's value itself. However, in the case where you may want to change the way the data is presented at some point in the future, it's one less refactoring you have to make internally.

Resources