CDI class explosion - cdi

With current spec (2.0) there is no way to prevent class explosion
problem like what we do with decorator pattern:
Cake cakeWithToppings = new ColoredSprinklesDecorator(new ShavedChocolateDecorator(new ToastedCoconutDecorator(new BaseCake())));
cakeWithToppings.delish();
Now to do that with CDI our options are create all possible combinations
of cake toppings(2^3 = 8) as class or with producer method with qualifiers which
will create problem of qualifier and producer method explosion.
When GoF decorator used there is need for only 5 classes Cake, CakeDecorator, ColoredSprinklesDecorator, ShavedChocolateDecorator, ToastedCoconutDecorator, BaseCake.
And #Decorator doesn't solve this issue as i can see.
Is there any way I couldn’t think of or is cake lie?

I am not sure I fully grasp your point, but I'll give it a go...
I think you are mixing two things here - GoF's decorator pattern and CDI's decorator which is not quite an implementation of that pattern.
In CDI, #Decorator can be seen as a "semantics-aware" interceptor rather than implementation of GoF's Decorator pattern.
This means that it can wrap calls to underlying beans of given types while being able to leverage the semantics.
E.g. you can create a decorator which will wrap all calls to any Cake:
#Decorator
#Priority(1)
public class CakeDecorator implements Cake {
#Inject
#Delegate
Cake cake; // this will cause to it decorate all cakes
public void delish() {
// do stuff BEFORE actual cake's delish() invocation
addMoreChocolate(cake);
cake.delish(); // this is the original method invocation
// do stuff AFTER actual cake's delish() invocation
cleanUp(cake);
}
}
But you can also easily modify the decorator to trigger for only certain types of cakes - you can do that by either changing the delegate injection point, or simply by checking cake type withing the method body. You can also chain several decorators if you so wish.
I'd say CDI's decorator is meant to meet slightly different goals. You could in fact design a decorator accordingly to GoF's principles and then apply CDI's decorator on top of that.

Related

How can I programmatically add a producer method to a CDI container during AfterBeanDiscovery?

I know how to add a Bean to a CDI container during AfterBeanDiscovery. My problem is that what I really need to do is the equivalent of adding a new producer method with the equivalent of a particularly qualified parameter.
That is, I'd like to somehow programmatically create several of these:
#Produces
#SomeQualifier("x")
private Foo makeFoo(#SomeQualifier("x") final FooMaker fm) {
return fm.makeFoo();
}
...where the domain over which SomeQualifier's value element ranges is known only at AfterBeanDiscovery time. In other words, some other portable extension has installed two FooMaker instances into the container: FooMaker-qualified-by-#SomeQualifier("x") and FooMaker-qualified-by-#SomeQualifier("y"). Now I need to do the equivalent of making two producer methods to "match" them.
Nonbinding is not an option; I want this resolution to take place at container startup, not at injection time.
I am aware of BeanManager's getProducerFactory method, but the dozens if not hundreds of lines of gymnastics I'd have to go through to add the right qualifier annotation on each AnnotatedParameter "reachable" from the AnnotatedMethod I'd have to create by hand (to avoid generics issues) make me think I'm way off the beaten path here.
Update: So in my extension, I have created a private static method that returns a Foo, and has a FooMaker parameter. I've wrapped this in a hand-tooled AnnotatedMethod that reports SomeQualifier("x") etc. in its getAnnotations() method, and also reports SomeQualifier("x") etc. from its AnnotatedParameter's getAnnotations() method. Then I got a ProducerFactory from the BeanManager and feed that into a new Bean that I create, where I use it to implement the create and destroy methods. Everything compiles and so forth just fine.
(However, Weld (in particular) blows up with this usage, which leads me to think that I'm doing Really Bad Things™.)

what is the purpose of runtime mixins in groovy

What is the purpose of runtime mixins in groovy?
Mixins overall one of the ways to add functionallity to class without multiple inheritance issues. But what is its purpose in Groovy? Traits can do the same.
Annotation #Mixin is considered deprecated at all. Will runtime mixins have the same fate one day?
Runtime mixins give us the ability to add methods to existed classes at runtime. The important part of the answer is "existed" and "runtime".
So, you can easily add new methods to any 3rd party library at runtime.
Actually, recently I found a case where using mixins helped me a lot.
String.metaClass {
invokeMethod {
String name, args ->
System.out.println "[$name] invokation with $args"
}
}
class GroovyInterceptableWrapper
implements GroovyInterceptable {
}
String.mixin(GroovyInterceptableWrapper)
Though again if I used there trait instead of class and then invoked withTraits I would have achieved the same result.

Metaprogramming: adding equals(Object o) and hashCode() to a library class

I have a library of domain objects which need to be used in the project, however we've found a couple of the classes haven't got an equals or hashCode method implemented.
I'm looking for the simplest (and Grooviest) way to add those methods. Obviously I could create a subclass which only adds the methods, but this would be confusing for developers used to the library and would mean we'd have to refactor existing code.
It is not possible to get the source changed (currently).
If I could edit the class I would just use the #EqualsAndHashCode annotation to carry out an AST transformation (at compile time?), but I can't find a way to instruct the compiler to carry out the transformation on a class which I can't directly annotate.
I'm currently trying to work up an example using the ExpandoMetaClass, so I'd do something like:
MySuperClass.metaClass.hashCode = { ->
// Add dynamic hashCode calculation bits here
}
MySuperClass.metaClass.equals = { ->
// Add dynamic hashCode calculation bits here
}
I don't really want to hand-code the hashCode/equals methods for each class, so I'm looking for something dyamic (like #EqualsAndHashCode) which will work with this.
Am I on the right track? Is there a groovier way?
AST Transforms are only applied at compile time, so you'll get no help from the likes of #EqualsAndHashCode. MetaClass hacks are going to be your only option. That said, there are more-elegant ways to impose MetaClass behavior.
Shameless Self Plug I did a talk about this kind of stuff last year at SpringOne 2GX: http://www.infoq.com/presentations/groovy-app-architecture
In short, you might find benefit in creating extensions (unless you're in Grails) - http://mrhaki.blogspot.com/2013/01/groovy-goodness-adding-extra-methods.html, or by explicitly adding mixins - http://groovy.codehaus.org/Runtime+mixins ... But in general, these are just cleaner ways to do the exact same thing you're already doing.

solving multiple inheritance (for precooked classes)

What I need: a class with two parents, which are ContextBoundObject and another class.
Why: I need to access the ContextBoundOject to log the method calls.
Composition works? As of now, no (types are not recognized, among other things).
Are other ways to do this? Yes, but not so automatable and without third-party components (maybe a T4 could do, but I'm no expert).
A more detailed explanation.
I need to extend System classes (some of which have already MarshalByRefObject (which is the parent of ContextBoundObject) for parent, for example ServiceBase and FileSystemWatcher, and some not, for example Exception and Timer) to access some inner workings of the framework, so I can log method calls (for now; in future it may change).
If I use this way I only have to add a class name to the object I want to log, instead of adding the logging calls to every method, but obviously I can't do this:
public class MyService:ServiceBase,ContextBoundObject,IDisposable{
public MyService(){}
public Dispose(){}
}
so one could try the usual solution, interfaces, but then if I call Run as in:
ServiceBase.Run(new MyService());
using a hypotethical interface IServiceBase it wouldn't work, because the type ServiceBase is not castable to IServiceBase -- it doesn't inherit from any interface. The problem is even worse with exceptions: throw only accepts a type descending from Exception.
The reverse, producing a IContextBoundObject interface, doesn't seem to work either: the logging mechanism doesn't work by methods, so I don't need to implement any, just an attribute and some small internal classes (and inheriting from ContextBoundObject, not even from MarshalByRefObject, which the metadata present as practically the same).
From what I see, extending from ContextBoundObject puts the extended class in a Proxy (probably because in this way the method calls use SyncProcessMessage(IMessage) and so can be intercepted and logged), maybe there's a way to do it without inheritance, or maybe there could be pre or post compiling techniques available for surrounding methods with logging calls (like T4 Text Templates), I don't know.
If someone wants to give this a look, I used a customized version of MSTestExtentions in my program to do the logging (of the method calls).
Any ideas are appreciated. There could be the need for more explanations, just ask.
Logging method calls is usually done using attributes to annotate classes or methods for which you want to have logging enabled. This is called Aspect Oriented Programming.
For this to work, you need a software that understands those attributes and post-processes your assembly by adding the necessary code to the methods / classes that have been annotated.
For C# there exists PostSharp. See here for an introduction.
Experimenting with proxies I found a way that apparently logs explicit calls.
Essentially I create a RealProxy like in example in the msdn, then obtain the TransparentProxy and use that as the normal object.
The logging is done in the Invoke method overridden in the customized RealProxy class.
static void Main(){
...
var ServiceClassProxy=new ServiceRealProxy(typeof(AServiceBaseClass),new object[]{/*args*/});
aServiceInstance=(AServiceBaseClass)ServiceClassProxy.GetTransparentProxy();
ServiceBase.Run(aServiceInstance);
...
}
In the proxy class the Invoke will be done like this:
class ServiceRealProxy:RealProxy{
...
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure)]
public override IMessage Invoke(IMessage myIMessage){
// remember to set the "__Uri" property you get in the constructor
...
/* logging before */
myReturnMessage = ChannelServices.SyncDispatchMessage(myIMessage);
/* logging after */
...
return myReturnMessage;
// it could be useful making a switch for all the derived types from IMessage; I see 18 of them, from
// System.Runtime.Remoting.Messaging.ConstructionCall
// ... to
// System.Runtime.Remoting.Messaging.TransitionCall
}
...
}
I have still to investigate extensively, but the logging happened. This isn't an answer to my original problem because I have still to test this on classes that don't inherit from MarshalByRefObject.

Trying to understand IOC and binding

I am very new to concept of IOC and I understand the fact that they help us resolve different classes in different contexts. Your calling class will just interact with Interface and Interface with decide which implementation to give you and it takes care of newing up the object.
Please do correct me if I am understanding is wrong because my question is based on that:
Now, I see this pattern very often in these projects:
private readonly IEmailService emailService;
private readonly ITemplateRenderer templateRenderer;
private readonly IHtmlToTextTransformer htmlToTextTransformer;
public TemplateEmailService(IEmailService emailService,
ITemplateRenderer templateRenderer,
IHtmlToTextTransformer htmlToTextTransformer)
{
this.emailService = emailService;
this.htmlToTextTransformer = htmlToTextTransformer;
this.templateRenderer = templateRenderer;
}
I understand that this helps using all the implementations of these classes without newing them up and also you don't have to decide WHICH implementaion to get, your IOC decides it for you, right?
but when I code like this, I do not even touch any IOC congiguration files. And again I am usin git for 2 days only but from all the tutorials that I have read, I was expecting my self to configure something which says "Resolve IParent to Child" class. But it works without me doing anything like it. Is it because there is only one implementaion of these interfaces? and If I do have more than one implementations then and then only I will have to configure resolved explicitly?
The code sample you have is a case of Constructor Injection.
In a traditional code, you would have a parameterless constructor, and in it you would "new-up" your objects like this:
IEmailService emailService = new EmailService();
So your code is explictly controlling which implementation gets assigned to the interface variable.
In IoC using constructor injection, control is inverted, meaning the container is "driving the bus" and is creating your TemplateEmailService object. When it is about to create it, the container looks at your constructor parameters (IEmailService , ITemplateRenderer , etc.) and feeds those objects to your class for use.
The IoC container can be configured so that interface A gets fulfilled by implementation B (or C) explicitly. Each one has a way to do it. Or it could do it by convention (IFoo fulfilled by Foo), or even attributes in classes, whatever.
So to answer your question-- you can explicitly define which implementations get used to fulfill certain interfaces. Got to read the IoC container docs for how to.
One more thing - "when you code like this", you technically don't have to be using an IoC container. In fact, your class should not have a direct reference to the container - it will maximize the reusability, and also allow easy testing. So you would wire-up interfaces to implementation classes elsewhere.

Resources