CDI on Socket Wildfly or SE - java

I need to make a Server socket in a web application that listen for Asterisk AGI requests but i need to enable CDI injection in the socket, don't know how to do that.
Today i already have this socket working very well, the problem is i can't inject a CDI bean with the socket.
Ex:
class RequestProcessor implements Runnable
{
private Socket socket;
#Inject
private PhoneService phoneService;
#Override
public void run()
{
// Do the logic here
}
}
Method that receives the request and send to a pool.
ExecutorService pool = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(25000);
Socket client = server.accept();
pool.execute(new RequestProcessor(client));
It's not the production code, it's just a illustrated example!
I can't make the #Inject PhoneService phoneService works.

As we've already established, newing the RequestProcessor won't populate the #Inject-annotated field since new completely cuts out the DI system. So you need a way to bring it in.
Your goal looks particularly non-trivial because RequestProcessor wants a DI-provided dependency (phoneService) and one that you provide programmatically (socket). As a general rule I would advise against mixing the two where possible – once you're using DI, it wants to spread like a virus. Let that happen. If you can design your system so that (almost) everything is injected for you, that's fanstastic!
That said, your situation is completely workable.
It looks like you have some method in some class which is a potential injection site. Assuming that this unknown class is in fact created by CDI you could #Inject the PhoneService into that class, and then pass it to the RequestProcessor constructor:
public class SomeClass {
#Inject
private PhoneService phoneService;
private void someMethod() {
ExecutorService pool = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(25000);
Socket client = server.accept();
pool.execute(new RequestProcessor(client, phoneService));
}
}
Or you could use a factory to create RequestProcessor instances, which will basically have the same effect in the end. You can write this factory by hand, which will look pretty familiar:
public class RequestProcessorFactory {
#Inject
private PhoneService phoneService;
public RequestProcessor createNewProcessor(Socket socket) {
return new RequestProcessor(socket, phoneService);
}
}
then inject an instance of that factory into your class:
public class SomeClass {
#Inject
private RequestProcessorFactory requestProcessorFactory;
private void someMethod() {
ExecutorService pool = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(25000);
Socket client = server.accept();
pool.execute(requestProcessorFactory.createNewProcessor(client));
}
}
There's a third way that you can do it, which is similar to Guice's assisted injection. Effectively it just generates that factory implementation for you, if you provide the interface. To my knowledge, CDI does not support this, but there is at least one CDI extension which does.
Happy DI-ing!

Related

what is the use of ZMQueue class in JeroMQ

I checked source code of ZMQueue class from JeroMQ which implements Runnable interface looks like:
private final Socket inSocket;
private final Socket outSocket;
public ZMQQueue( Context context, Socket inSocket, Socket outSocket ){
this.inSocket = inSocket;
this.outSocket = outSocket;
}
#Override
public void run(){
zmq.ZMQ.proxy( inSocket.base(), outSocket.base(), null );
}
As you can see inside the run() only one statement is there, i.e. calling a
ZMQ.proxy() - what happens here?
And in constructor,it's taking a Context instance as a parameter and doing nothing with it.
can any one explains, for what purpose this class has implemented?
It's simple proxy that works in separate thread, it takes a msg from one socket and puts it to another, ZMQueue class is just a some kind of high-level api in jeromq/jzmq library.
Also you can use proxy without ZMQueue class (doc).
Or you can implement something more complicated by yourself with any processing you need.

How to test method that internally creates and uses a ServerSocket

My server code looks something like this:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server implements Runnable {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
#Override
public void run() {
try {
Socket client = serverSocket.accept();
// do stuff
} catch (IOException e) {
e.printStackTrace();
}
}
}
My plan was to write a mock client that connects to the server socket, and verifies the result, but in order to do that I need to know which port to connect to. However, this information is private.
None of the options I was thinking about are good practice I think:
If I use a predefined port number for the tests, I have no guarantee that it will be available. Even if it's available just before the test, it might be, theoretically snatched by the time I try to use it.
If I pass 0 as port number (so that ServerSocket will atomically provide a free port), I still have no access to it.
I could add a getServerPort() method to the interface or create a constructor that accepts a ServerSocket object, but changing the interface only for the sake of testing is considered bad practice.
As written, your class is not really suited for unit test.
The problem is that your direct call to new ServerSocket() basically deprives your ability to control what the socket object will be doing.
So, what you can do:
interface SocketFactory {
public ServerSocket createSocketFor(int port);
}
class SocketFactoryImpl implements SocketFactory {
...
public class Server implements Runnable {
public Server(int port) {
this(port, new SocketFactoryImpl());
}
Server(int port, SocketFactory socketFactory) {
...
In other words: you use dependency injection in order to provide a mean to your "class under test" to create those objects that it needs to do its work.
From there: you can use a mocking framework such as EasyMock in order to control what a mocked SocketFactory object will return (probably a mocked ServerSocket object). And now that you have full control over the ServerSocket used by your production code ... you can test whatever situation you want.
Long story short: don't call new; instead use dependency injection to gain full control over your class under test.
(and maybe watch these videos to really understand what writing testable code is about).

JavaFX8 - Thread task with Guice

I'm new (very new) to Guice and JavaFX. I'm building an application that have a thread listening for socket connection and, after an event is received, the thread store value on ObservableArrayList() and the application will notify them to the user.
My problem is how to structure all this behaviour, and how to "share" the ObservableList from the thread and the JavaFX Controller.
I'm reading about Guice that could help to decouple the new creation of an object.
I've tried to setup something, but the #Inject property is null on my runnable task:
Guice Module:
public class AppGuiceModule extends AbstractModule{
#Override
protected void configure() {
bind(EventsDAO.class).toInstance(new EventsDAO());
}
}
EventsDAO (that have the ObservableArrayList )
#Singleton
public class EventsDAO {
private ObservableList<ScheduledEvent> localCache = FXCollections.observableArrayList();
public void addEvent(ScheduledEvent event) {
localCache.add(event);
}
public void removeEvent(ScheduledEvent event) {
this.localCache.remove(event);
}
}
With two this, i in my main i go to create the injector:
#Override
public void start(Stage stage) throws Exception {
Injector injector = Guice.createInjector(new AppGuiceModule());
Platform.setImplicitExit(false);
Thread t = new Thread(new EventsReceiverTask());
t.start();
.....
Now, in the Runnable object, i would to #Inject EventsDAO (to save new events) and #Inject this too in my Controller, adding to localCache a listener (yes localCache is private, i will provide a getter).
The runnable object:
public class EventsReceiverTask implements Runnable {
private static final int port = 4020;
#Inject
EventsDAO eventsDao; // This is null, why not injected ?
private ServerSocket serverSocket;
private Stage notificationStage;
public EventsReceiverTask() {
try {
this.serverSocket = new ServerSocket(port);
this.notificationStage = new Stage();
eventsDao.addEvent(new ScheduledEvent());
} catch (IOException ex) {
Logger.getLogger(EventsReceiverTask.class.getName()).log(Level.SEVERE, null, ex);
}
}
I dont know if this is the correct way to implement a "producer-consumer" in JavaFX, but i have no idea how to share that components, witthout creating tedious getter and setter, with all statics methods.
Your problem shows exactly why it is preferred not to use new in a dependency injected system, when possible.
Injections can only occur when the injection framework is the one creating the objects. When you call new, you are creating them, not the framework.
There are two ways to have Guice create an object for you:
Use injector.getInstance(Foo.class);
You want to use this as little as possible; generally speaking the only place you would use this method is inside your main method. Using this line elsewhere, makes it difficult to track down injections and understand the object graph. From Wikipedia:
With inversion of control, the flow depends on the object graph that is built up during program execution. Such a dynamic flow is made possible by object interactions being defined through abstractions.
Have Guice create your objects for you as injections.
This is exactly what the #Inject annotation does; instruct Guice to create the object for you in your bound classes.
Generally speaking, a class with a name like EventsReceiverTask is not the sort of top level class that you want to be creating in your main method. They have names more like EventService, to which you would inject a Provider<EventsReceiverTask> that is capable of creating new tasks for you, all of which will be injected with your EventsDAO properly.
Side note: you didn't ask about this, but when you do this, in your module:
bind(EventsDAO.class).toInstance(new EventsDAO());
You are overriding the scope of the binding that you attempted to specify with the #Singleton annotation in your class definition. If you want this object to actually be a singleton, you **must also specify the #Singleton binding in your module, e.g.
bind(EventsDAO.class).toInstance(new EventsDAO()).in(Singleton.class);
From the documentation:
If there's conflicting scopes on a type and in a bind() statement, the bind() statement's scope will be used. If a type is annotated with a scope that you don't want, bind it to Scopes.NO_SCOPE.
You never inject the member fields to the task object, so the value is null.
You need something like the inject part below so that Guice actually injects the field value. You might want further refactoring to make this better, but at the most basic level, Guice won't inject the field until you tell it to.
public void start(Stage stage) throws Exception {
Injector injector = Guice.createInjector(new AppGuiceModule());
Platform.setImplicitExit(false);
EventsReceiverTask task = new EventsReceiverTask();
// You need something like this so that Guice injects the members into the object.
injector.injectMembers(task);
Thread t = new Thread(task);
t.start();
....

Aperiodically trigger a thread to run in Java

My server aperiodically receives join requests from new clients. Upon receiving a new join request, the server runs a service that can be finished real quick. I implement the service as a Java class (called JC) implementing the Runnable interface. I have parameters within the JC class.
At the caller side, I like to have only one instance (or static) of the JC. My question is how to trigger the run() method in the JC every time. Please show me some code. Thanks.
Hope following edits make sense, which is my current implementation.
In the Server that wants to trigger thread executing:
public class Server {
private static RealService mm = new RealService();
private static void update(){
new Thread(mm).start();
}
}
In the Service class:
public class RealService implements Runnable{
#Override
public void run() {
// TODO Auto-generated method stub
// Do something
}
}
You're question is not really clear here, but I would suggest reading about TimerTask in Java
You could use a socket to listen for incoming requests, the server can spawn a new thread each time there is a request. Once the thread completes, you should intimate the client.
You could read about how a concurrent server works.

Accessing scoped proxy beans within Threads of

I have a web application running in tomcat where I'm using a ThreadPool (Java 5 ExecutorService) to run IO intensive operations in parallel to improve performance. I would like to have some of the beans used within each pooled thread be in the request scope, but the Threads in the ThreadPool do not have access to the spring context and get a proxy failure. Any ideas on how to make the spring context available to the threads in the ThreadPool to resolve the proxy failures?
I'm guessing there must be a way to register/unregister each thread in the ThreadPool with spring for each task, but haven't had any luck finding how to do this.
Thanks!
I am using the following super class for my tasks that need to have access to request scope. Basically you can just extend it and implement your logic in onRun() method.
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
/**
* #author Eugene Kuleshov
*/
public abstract class RequestAwareRunnable implements Runnable {
private final RequestAttributes requestAttributes;
private Thread thread;
public RequestAwareRunnable() {
this.requestAttributes = RequestContextHolder.getRequestAttributes();
this.thread = Thread.currentThread();
}
public void run() {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
onRun();
} finally {
if (Thread.currentThread() != thread) {
RequestContextHolder.resetRequestAttributes();
}
thread = null;
}
}
protected abstract void onRun();
}
I also wish I had 1000 votes to give to the currently accepted answer. I had been stumped on how to do this for some time. Based on it, here is my solution using the Callable interface in case you want to use some of the new #Async stuff in Spring 3.0.
public abstract class RequestContextAwareCallable<V> implements Callable<V> {
private final RequestAttributes requestAttributes;
private Thread thread;
public RequestContextAwareCallable() {
this.requestAttributes = RequestContextHolder.getRequestAttributes();
this.thread = Thread.currentThread();
}
public V call() throws Exception {
try {
RequestContextHolder.setRequestAttributes(requestAttributes);
return onCall();
} finally {
if (Thread.currentThread() != thread) {
RequestContextHolder.resetRequestAttributes();
}
thread = null;
}
}
public abstract V onCall() throws Exception;
}
Could you try it the other way round? Use a data container that's stored in request scope and give it to the thread pool (perhaps put it into a queue, so that the thread pool can take one data container at a time, work on it, mark it as "done" and continue with the next one).
Spring has a ThreadPoolTaskExecutor class that you can use to manage your thread pool from Spring. However, it looks like you'd have to do some work to make the Spring context available to each thread.
I'm not sure if it will work even if you do wire it up this way though. Spring uses a token in thread local to locate objects in request (or session) scope, so if you're trying to access a request scope bean from a different thread, it's likely that token won't be there.

Categories