Guice injection for dynamically creating objects - java

I have a "Handler" interface for a message queue, something that has methods:
boolean canHandle(message);
void handle(message);
I then have multiple implementations for this interface, each of them canHandle() certain types of messages
When a message arrive, I do something like:
for (Handler handler : handlers) {
if handler.canHandle(message)
handle(message)
So, I need to build a list of "enabled handlers" that must be specified in a config file.
I could either specify the enabled handlers by class name (FQCN) or annotating the class by some name and referencing this name on the config.
For instance:
enabledHandlers = ("com.domain.handlers.HandlerA", "com.domain.handlers.HandlerB", )
#or
enabledHandlers = ("HandlerAAnnotation", "HandlerBAnnotation", )
in any case, somehow I will need to build those handlers inside my service, and they require injected parameters.
I believe something injector.getInstance(clazz) would work to build those objects, but it doesn't make much sense to have the "injector" going around my service when I need to create those classes.
I could also create them by reflection "manually" by clazz.getConstructor(...).newInstance(...), but it seems pretty dirty.
Any other ideas?
Thanks!

Related

Guice Multi-binding Injection in javax.validation.ConstraintValidator

I want to use Guice Multibinding injection in javax.validation.ConstraintValidator.
Not getting any clue to inject map binder in my ConstraintValidator class.
I use the MapBinder in the following way, it does it's job, but I need to refactor to make it better. To give you some background, I had to match a legacy program for copying data from a primary database to any number of subsequent databases using a combination of files (don't ask, but it works). Anyhow, I use a super simple mapping scheme of TableName -> TableTransferHandler, here is how I define the bindings:
MapBinder<String, TableTransferHandler<?>> binder
= MapBinder.newMapBinder(
binder(),
new TypeLiteral<String>() {},
new TypeLiteral<TableTransferHandler<?>>(){});
// Add my Table handlers based on table name.
binder.addBinding("table_one").to(TableOneTransferHandlerImpl.class);
binder.addBinding("table_two").to(TableTwoTransferHandlerImpl.class);
which gets used as such:
#Inject
Map<String,TableTransferHandler<?>> handlers;
TableTransferHandler<?> handler = handlers.get(tableName);
handler.process();
It's very trivial, and needs to be rewritten, but for the most part it gets the job done. From what you've explained though, I'm not sure if you want MapBinder, you probably want to return the regular binding for a ConstraintValidator. If I had chosen to implement a TableTransferHandler by remote system, instead of by name, I would have done this:
Multibinder<TableTransferHandler<UserAccess>> binder
= Multibinder.newSetBinder(
binder(),
new TypeLiteral<TableTransferHandler<UserAccess>>() {});
// Add all my remote handlers relating to UserAccess
binder.addBinding().to(RemoteOneUserAccessTableHandler.class);
binder.addBinding().to(RemoteTwoUserAccessTableHandler.class);
Which would then be used:
#Inject
Set<TableTransferHandler<UserAccess>> handlers;
for (TableTransferHandler<UserAccess> handler : handlers) {
handler.process();
}

Modifying annotation value in superclass and dynamically instantiating child classes with new value

We are using Spring Cloud Stream as the underlying implementation for event messaging in our microservice-based architecture. We wanted to go a step further and provide an abstraction layer between our services and the Spring Cloud Stream library to allow for dynamic channel subscriptions without too much boilerplate configuration code in the services themselves.
The original idea was as follows:
The messaging-library provides a BaseHandler abstract class which all individual services must implement. All handlers of a specific service would like to the same input channel, though only the one corresponding to the type of the event to handle would be called. This looks as follows:
public abstract class BaseEventHandler<T extends Event> {
#StreamListener
public abstract void handle(T event);
}
Each service offers its own events package, which contains N EventHandlers. There are plain POJOs which must be instantiated programmatically. This would look as follows:
public class ServiceEventHandler extends BaseEventHandler<ImportantServiceEvent> {
#Override
public void handle(ImportantServiceEvent event) {
// todo stuff
}
}
Note that these are simple classes and not Spring beans at this point, with ImportantServiceEvent implementing Event.
Our messaging-library is scanned on start-up as early as possible, and performs handler initialization. To do this, the following steps are done:
We scan all available packages in the classpath which provide some sort of event handling and retrieve all subclasses of BaseEventHandler.
We retrieve the #StreamListener annotation in the hierarchy of the subclass, and change its value to the corresponding input channel for this service.
Since our handlers might need to speak to some other application components (repositories etc.), we use DefaultListableBeanFactory to instantiate our handlers as singleton, as follows:
val bean = beanFactory.createBean(eventHandlerClass, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, true);
beanFactory.registerSingleton(eventHandlerClass.getSimpleName(), bean);
After this, we ran into several issues.
The Spring Cloud Stream #StreamListener annotation cannot be inherited as it is a method annotation. Despite this, some mechanism seems to be able to find it on the parent (as the StreamListenerAnnotationBeanPostProcessor is registered) and attempts to perform post-processing upon the ServiceEventHandler being initialized. Our assumption is that the Spring Cloud Stream uses something like AnnotationElementUtils.findAllMergedAnnotations().
As a result of this, we thought that we might be able to alter the annotation value of the base class prior to each instantiation of a child class. Due to this, we thought that although our BaseEventHandler would simply get a new value which would then stay constant at the end of this initialization phase, the child classes would be instantiated with the correct channel name at the time of instantiation, since we do not expect to rebind. However, this is not the case and the value of the #StreamListener annotation that is used is always the one on the base.
The question is then: is what we want possible with Spring Cloud Stream? Or is it rather a plain Java problem that we have here (does not seem to be the case)? Did the Spring Cloud Stream team foresee a use case like this, and are we simply doing it completely wrong?
This question was also posted on on the Spring Cloud Stream tracker in case it might help garner a bit more attention.
Since the same people monitor SO and GitHub issues, it's rather pointless to post in both places. Stack Overflow is preferred for questions.
You should be able to subclass the BPP; it specifically has this extension point:
/**
* Extension point, allowing subclasses to customize the {#link StreamListener}
* annotation detected by the postprocessor.
*
* #param originalAnnotation the original annotation
* #param annotatedMethod the method on which the annotation has been found
* #return the postprocessed {#link StreamListener} annotation
*/
protected StreamListener postProcessAnnotation(StreamListener originalAnnotation, Method annotatedMethod) {
return originalAnnotation;
}
Then override the bean definition with yours
#Bean(name = STREAM_LISTENER_ANNOTATION_BEAN_POST_PROCESSOR_NAME)
public static StreamListenerAnnotationBeanPostProcessor streamListenerAnnotationBeanPostProcessor() {
return new StreamListenerAnnotationBeanPostProcessor();
}

Best factory pattern for delivering app data object based on application type in http header

I have a business with multiple applications using my webservice resource. I have a web service resource that looks in a http header for the application ID. This tell the server which application is requesting data. My goal is to deliver to my web application developers a method they can call to retrieve all the application specific settings via the application ID.
Given an applicationID i can specify device type, properties file for that app, and whether GCM,APNS or Microsoft Push Notification, etc. So each applicationID has distinct properties basically.
I want the developer to be able to call for this object like this (or similar):
ApplicationData appData = ApplicationDataFactory.getCurrentApplicationData();
and the factory would look something like this:
class ApplicationDataFactory
{
public static ApplicationData getCurrentApplicationData()
{
//notice how im not passing in criteria here, im getting it from the request so call doens't have to know
String criteria = Request.getHTTPHeaderInfo("applicationID");
if ( criteria.equals("Android") )
return new Android();
else if ( criteria.equals("Android-germany") )
return new Android_germany();
else if ( criteria.equals("ios_germany") )
return new ios_germany();
else if ( criteria.equals("ios"))
return new ios();
else if ( criteria.equals("windows") )
return new windows();
return null;//or throw exception
}
}
so Android, ios, and windows objects all extend off ApplicationData class clearly.
So for example the Android.java object would look like this:
class Android extends ApplicationData{
#override
public String getType(){
return "Android"
}
#override
public Properties getProperties{
return system.getProperties("android.properties");
}
}
and the Android-germany and ios-germany will have common data since there both from germany.
First, i dont like that im specifying the criteria inside the factory and also can anyone help me
with a good design pattern i can use to achieve this ? Remember, in the end i want to be able to have the developer call only ApplicationDataFactory.getCurrentApplicationData(); (or something similar) and the correct application info will be sent referenced. I dont have to use a factory here either its just the first thing i thought of.
So your problem is with the fact that the logic for the criteria is within the factory method. Meanwhile, you don't want the user to provide the criteria as an parameter to the factor method.
First of all, I don't like the idea of having a static Request class. A request should be an object that contains information about the current request. I have a suspicion that your code may be prone to race conditions, once you have many concurrent requests (how do you know which request is which?). So as a starting point, I would refactor the Request class so that you work with instances of Request.
I think, the clearest approach would be that you pass in applicationID as a parameter. This makes testability trivial and the code becomes very obvious, too. You take an input and produce the output based on the input. You could pass the Request instead of the applicationID and let the factory handle the retrieval of the applicationID from the request (as you are doing now).
If you think the Request -> applicationID logic should not be part of the factory, you can create another class, such as ApplicationIDResolver which translates a Request to an applicationID. From then on ApplicationDataFactory would be used through an instance and the ApplicationIDResolver would be a constructor parameter. (I think, this is an overkill.). Another option is to add a getApplicationID() method to the Request class.
If you use a dependency injection framework, it may take care of object life cycles/scopes automatically for you, so the ApplicationData could be a request-scoped object and you could tell your dependency injection framework to instantiate ApplicationData objects based on requests and inject them into the classes where they get used.
Better to use for this purposes enum which implements ApplicationData interface and define each entry. You can resolve proper by valueOf() from enum.

Overriding/Wrapping spring beans in java based config multiple times

I have a (web-)application that needs special configurations and/or extensions based on the customer using the application. I call these additions "plugins" and they are auto discovered by classpath scanning when the application starts. For extensions that is incredibly easy. Let's say I want to have a plugin which adds an API that prints "hello world" when the URL /myplugin/greet is called: I just create a #Controller annotated class with the according #RequestMapping, put this in a myplugin.jar, copy that on the classpath and that's it.
Problems come up when I want to change some defaults and especially if I want to do this multiple times. Let's say my core application has a config like this:
#Configuration
public class CoreConfiguration {
#Bean
public Set<String> availableModules() {
return Collections.singleton("core");
}
}
Now I have two plugins that don't know about each other (but they do know the CoreConfig), but they both want to add themselves to the list of available modules. How would I do that? If I only had a single plugin that wants to override the module list I could override the existing bean from CoreConfiguration, but with two plugins that becomes a problem. What I imagine is something like this:
#Configuration
public class FirstPluginConfiguration {
#Bean
public Set<String> availableModules(Set<String> availableModules) {
Set<String> extendedSet = new HashSet<>(availableModules);
extendedSet.add("FirstPlugin");
return extendedSet;
}
}
Of course a SecondPluginConfiguration would look nearly exactly like this, except that the Set is not extended by "FirstPlugin", but by "SecondPlugin". I tested it to check what would happen and spring will just never call the First/SecondPluginConfiguration "availableModules" methods but it does not show an error either.
Now of course in this case this could easily be solved by using a mutable Set in the CoreConfiguration and then autowiring and extending the set in the other configurations, but for example I also want to be able to add method interceptors to some beans. So for example I might have an interface CrashLogger which has a logCrash(Throwable t) method and in CoreConfiguration a ToFileCrashLogger is created that writes stack traces to files as the name suggests. Now a plugin could say that he also wants to get notified about crashes, for example the plugin wants to ADDITIONALLY send the stacktrace to someone by email. For that matter that plugin could wrap the CrashLogger configured by the CoreConfiguration and fire BOTH. A second plugin could wrap the wrapper again and do something totally different with the stacktrace and still call both of the other CrashLoggers.
The later does sound somewhat like AOP and if I'd just let ALL my beans be proxied (I did not test that) I could autowire them into my plugin configurations, cast them to org.springframework.aop.framework.Advised and then add advices that manipulate behaviour. However it does seem like a huge overkill to generate proxies for each and everyone of my beans just so that that plugin can potentially add one or two advices one one or two beans.

Guice IOC: Manual (and Optional) Creation of a Singleton

Trying to get started with Guice, and struggling to see how my use-case fits in.
I have a command-line application, which takes several optional parameters.
Let's say I've got the tool shows a customer's orders, for example
order-tool display --customerId 123
This shows all the orders owned by customer with ID 123. Now, the user can also specify a user's name:
order-tool display --customerName "Bob Smith"
BUT the interface to query for orders relies on customer IDs. Thus, we need to map from a customer name to a customer ID. To do this, we need a connection to the customer API. Thus, the user has to specify:
order-tool display --customerName "Bob Smith" --customerApi "http://localhost:8080/customer"
When starting the application, I want to parse all the arguments. In the case where --customerApi is specified, I want to place a CustomerApi singleton in my IoC context - which is parameterized by the CLI arg with the API URL.
Then, when the code runs to display a customer by name - it asks the context if it has a CustomerApi singleton. If it doesn't it throws an exception, telling the CLI user that they need to specify --customerApi if they want to use --customerName. However, if one has been created - then it simply retrieves it from the IoC context.
It sounds like "optionally creating a singleton" isn't exactly what you're trying to do here. I mean, it is, but that's as simple as:
if (args.hasCustomerApi()) {
bind(CustomerApi.class).toInstance(new CustomerApi(args.getCustomerApi()));
}
To allow for optional bindings, you will probably need to annotate their use with #Nullable.
I think your real question is how to structure an application so that you can partially configure it, use the configuration to read and validate some command-line flags, then use the flags to finish configuring your application. I think the best way to do that is with a child injector.
public static void main(String[] args) {
Injector injector = Guice.createInjector(new AModule(), new BModule(), ...);
Arguments arguments = injector.getInstance(ArgParser.class).parse(args);
validateArguments(arguments); // throw if required arguments are missing
Injector childInjector =
injector.createChildInjector(new ArgsModule(arguments));
childInjector.getInstance(Application.class).run();
}
Child injectors are just like normal injectors that defer to a parent if they don't contain the given bindings themselves. You can also read documents on how Guice resolves bindings.

Categories

Resources