Class without Verticle implement and event loop - asynchronous

I'm not sure to understand correctly the verticles principle. If my main class extends AbstractVerticle (implements the Verticle interface) and this class create instances of other class (by example, Controllers for MVC use case), the execution process of the functions in theses class is also asynchronous ? Even if theses class (controllers in my example) doesn't implements Verticle interface ?
I just want to have a full asynchonous execution in the same thread, i dont't want to use a worker verticle.
Thx for reading.

If you create an object as class variable in your class the extends AbstractVerticle then every method you would call with your object would be executed on your Verticle thread.
If your object is a synchronous class obviously this might block your thread execution.

Related

Java FXML Application: unsuccessful calling method in controller class from external class

Working on a Java FXML application called EVIF VideoRouter. Main class is then VideoRouter.java and the controller class is called VideoRouterFXMLController.java.
I have a method in the VideoRouterFXMLController.java class that I need to be able to call from other external classes within the application. Based on extensive searching and reading, I altered the FXML loader code in the main VideoRouter.java class to be thus:
FXMLLoader EVIFloader = new FXMLLoader(this.getClass().getResource("VideoRouterFXML.fxml"));
Parent EVIFroot = (Parent) EVIFloader.load();
VideoRouterFXMLController EVIFcontroller = EVIFloader.getController();
Now, as I understand this process, I'm somehow supposed to create a getter in the main VideoRouter.java class that returns the EVIFcontroller instance I've created above? And then I can use that getter in other classes and call the method inside the returned instance?
If so, I'm having difficulty figuring out where exactly to place the getter. Does it go in the controller class, or the main class? In either case it doesn't seem to be able to see the controller instance in order to return it.
Again, I've searched extensively and the related posts I've found to not appear to address this specific problem I'm having. Any help?
Many thanks in advance!
You have already partly answered your problem: create VideoRouterFXMLController member variable in your VideoRouter class and a getter to expose it, then set it to the controller instance after you load the FXML like in the code snippet your provided.
Having said that, I would propose a different approach to your problem because this approach is generally not a good design due to high coupling between your classes. I would recommend Observer pattern as an alternative approach and EventBus as a library to do this.

SignalR: sub-classing my hub breaks outside calls

I'm starting from a functioning SignalR web application with an ActivityHub class derived from a SignalR Hub to manage client connections and activities. Similar to the stock ticker tutorial, there is also a singleton ActivityTimer class that uses a System.Threading.Timer to periodically broadcast to all clients via the hub context it gets in its constructor, like this:
activityHubContext = GlobalHost.ConnectionManager.GetHubContext<ActivityHub>();
Now I want to turn my ActivityHub into a base class with sub-classes for different kinds of activities, overriding a few methods in ActivityHub for activity-specific behaviors, and using activity-specific clients which each reference the appropriate activity sub-class (e.g., var activityHub = $.connection.coreActivityHub).
The sub-classing works for the hub server code and clients, and the ActivityTimer fires timer events as intended, but the ActivityTimer calls no longer reach the clients. If I get the hub context for a specific activity sub-class, it works again, but only for that sub-class:
activityHubContext = GlobalHost.ConnectionManager.GetHubContext<CoreActivityHub>();
Is there a way to have a single, generic ActivityTimer that will work with all sub-classes of ActivityHub? Can the ActivityTimer call some method in the base ActivityHub class rather than trying to reach all the clients directly (the base class seems to have no problems calling Clients.All.doSomething())?
In case it simplifies things (or makes possible an otherwise challenging solution), the application will only be running one type of activity at a time -- all clients will be on the same activity at one time.
In working on a different issue in the same project, I came across this, which points to this, where I also found this (all worth a quick read if the topic interests you). They provide one way to do what I was trying to do: have a method in the base class that can be called from "outside" to reach clients of any/all sub-classes. (They also helped me to think more clearly about the hub context, and why I believe my original ActivityTimer cannot work with sub-classes -- see note at the end of this answer for further explanation).
The solution to my problem is to create a method in the base class that does the call to the clients, and then call this new method from the ActivityTimer to reach the clients indirectly. This approach does not rely on having a hub context within ActivityTimer, and it frees us from worry about sub-classes because it calls into the base class explicitly:
Create a static field in the base class to hold the base class's hub context:
private static IHubContext thisHubContext;
Set this hub context in each sub-class's constructor with that class as the type passed to GetHubContext():
thisHubContext =
GlobalHost.ConnectionManager.GetHubContext<CoreActivityHub>();
Create a static method in the base class that calls the desired client-side method(s); note that you could use other options than Clients.All to reach a subset of clients (for example, the arg might designate a SignalR group to reach):
public static void DoSomething(string someArg)
{
thisHubContext.Clients.All.doSomething(someArg);
}
Call this base-class method from any server code that is "outside" the hub. In my case, I call it from the timer event handler in ActivityTimer:
ActivityHub.DoSomething("foo");
The messages will get through to the clients specified in the static method.
NB: this solution only works for the particular case mentioned at the end of the original post, in which only one sub-class is ever in use at a time, because each sub-class sets the base class static hub context to its own context. I have not yet tried to find a way around this limitation.
Note: I don't think it's possible to have "outside-the-hub" server code work with sub-classes by way of a stored hub context. In my original, functioning app (before I tried to create sub-classes of the ActivityHub), the ActivityTimer talks to the clients by means of a hub context that it gets on instantiation:
public ActivityTimer()
{
activityHubContext = GlobalHost.ConnectionManager.GetHubContext<ActivityHub>();
activityTimer = new Timer(DoSomething, null, TimerInterval, TimerInterval);
}
public void DoSomething(object state)
{
activityHubContext.Clients.All.doSomething("foo");
}
Because the hub context is obtained by explicit reference to a particular class (in this case, ActivityHub), it will not work with a sub-class. If instead (as I mentioned trying in my original post) I get the hub context for a particular sub-class, the timer will now work for instances of that sub-class, but not other sub-classes; again, the problem is that the hub context is obtained for a particular sub-class.
I don't think there's any way around this, so I think the only solution is the one outlined above in which the base class method uses the hub context set by the sub-class constructor, and the outside code calls the base class method to get to the clients by way of that sub-class context.
However, I'm still on the SignalR learning curve (among others) so will appreciate any corrections or clarifications!

PHPUnit - How do I stub the entire parent class?

I have a bad situation where a class i want to test is extending another class that has a pretty complex public static method. This wouldn't be such an issue if the parent class wasn't extending other classes that are required. In specific, I need \Illuminate\Database\Eloquent\Model to still be extended. My hands are tied regarding possible refactor to make this easier to test.
Is there any way to stub or change the parents of the class in question, while still allowing the Model class to perform?
Maybe you could create a YourClassTestCase that extends the class you are testing. Then, in YourClassTestCase override static method with a simplified return and launch the test over YourClassTestCase.
So you will have YourTest -> yourClassTestCase -> YourClass -> ParentWithStaticMethod.
You should use Mock Objects.
See here:https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects

OCMock 3 Partial Mock: Class methods and the objc runtime

I'm running into an interesting issue when using OCMock 3 when partially mocking an object that defines class methods. I'm not sure if this is an issue with the dynamic subclassing that takes part as partial mocking or my misunderstanding of the objc runtime. Any help would be greatly appreciated.
As part of running tests and other debug builds we do some runtime verification of method declarations using OmniFoundations' OBRuntimeCheck. One of these checks, in short, attempts to use the runtime to verify that type signatures match for class methods across inheritance and protocol conformance. This happens by listing the classes registered in the runtime and for each class the instance methods of the metaClass are copied. For each Method from the metaClass if it exists on the metaClass's superclass the type signatures are compared.
The problem comes when calling class_getInstanceMethod on the metaClass's superclass for one of the ocmock replacement selectors, ocmock_replaced_*. The test crashes EXC_BAD_INSTRUCTION code=EXC_i386_INVOP subcode=0x0 and no class for metaclass is logged in the console. Example given:
class_getInstanceMethod(metaSuperClass, NSSelectorFromString(#"ocmock_replaced_classMessage"))
When partial mocking an object that defines a class method, it appears that the OCMock 3 framework generates a dynamic subclass, does some isa swizzling of the mocked object and also some isa swizzling of the dynamically generated class' metaClass.
This behavior and crash is new in OCMock 3 and I'm really at a loss of where to look next. Any runtime gurus have any idea what may be going on here? When looking through the code it did surprise me that the dynamically generated class used for the mock was having it's meta class swizzled out, but I don't necessarily think that is wrong. For ease in debugging I have created a simplified test case in a fresh fork of OCMock. The crashing test can be found here. Any help for guidance would be greatly appreciated.
I may be way off here, but I thought the superclass of a metaClass is NSObject (which is why you can normally call NSObject instance methods on class objects). I'm not sure you should be doing anything, normally, with the superclass of a metaClass.
In general, the metaClass stores all of the information about class methods. Therefore, getting an "instance" method on a metaClass is the same as getting a class method on the associated regular Class. The runtime can simply dereference the "isa" pointer of an instance to find a method list to find instance methods; doing the same on a Class object gets the meta class (of the same structure) and therefore the same process results in finding the class methods.
OCMock will create a magic subclass for any partial mock, and change the class on that instance to the new subclass, so all the instance method swizzling will be specific to that instance. For class methods though, I thought it had to modify the original class itself -- otherwise, calls to the regular class method in regular code would not be intercepted. It keeps a copy of the original implementation so that when you call -stopMocking on the mock it can restore the original implementation (the added ocmock_replaced* impl will still be there but should no longer be called).
You could simply ignore any selector which starts with "ocmock_replaced" since that really is not related to your actual code you are presumably checking. You might also have better luck changing "class_getInstanceMethod(metaSuperClass, ..." to "class_getClassMethod(regularSuperClass, ..."). I'm not sure why you would be getting a crash though -- I would expect class_getInstanceMethod(metaSuperClass, ...) to just return NULL in most situations.

How to implement callbacks in Java

I have a class called CommunicationManager which is responsible for communication with server.
It includes methods login() and onLoginResponse(). In case of user login the method login() has to be called and when the server responds the method onLoginResponse() is executed.
What I want to do is to bind actions with user interface. In the GUI class I created an instance of CommunicationManager called mCommunicationManager. From GUI class the login() method is simply called by the line
mCommunicationManager.login();
What I don't know how to do is binding the method from GUI class to onLoginResponse(). For example if the GUI class includes the method notifyUser() which displays the message received from theserver.
I would really appreciate if anyone could show how to bind methods in order to execute the method from GUI class (ex. GUI.notifyUser()) when the instance of the class mCommunicationManager receives the message from the server and the method CommunicationManager.onLoginResponse() is executed.
Thanks!
There's two patterns here I can see you using. One is the publish/subscribe or observer pattern mentioned by Pete. I think this is probably what you want, but seeing as the question mentions binding a method for later execution, I thought I should mention the Command pattern.
The Command pattern is basically a work-around for the fact that java does not treat methods (functions) as first class objects and it's thus impossible to pass them around. Instead, you create an interface that can be passed around and that encapsulates the necessary information about how to call the original method.
So for your example:
interface Command {
public void execute();
}
and you then pass in an instance of this command when you execute the login() function (untested, I always forget how to get anonymous classes right):
final GUI target = this;
command = new Command() {
#Override
public void execute() {
target.notifyUser();
}
};
mCommunicationManager.login(command);
And in the login() function (manager saves reference to command):
public void login() {
command.execute();
}
edit:
I should probably mention that, while this is the general explanation of how it works, in Java there is already some plumbing for this purpose, namely the ActionListener and related classes (actionPerformed() is basically the execute() in Command). These are mostly intended to be used with the AWT and/or Swing classes though, and thus have features specific to that use case.
The idiom used in Java to achieve callback behaviour is Listeners. Construct an interface with methods for the events you want, have a mechanism for registering listener object with the source of the events. When an event occurs, call the corresponding method on each registered listener. This is a common pattern for AWT and Swing events; for a randomly chosen example see FocusListener and the corresponding FocusEvent object.
Note that all the events in Java AWT and Swing inherit ultimately from EventObject, and the convention is to call the listener SomethingListener and the event SomethingEvent. Although you can get away with naming your code whatever you like, it's easier to maintain code which sticks with the conventions of the platform.
As far as I know Java does not support method binding or delegates like C# does.
You may have to implement this via Interfaces (e.g. like Command listener.).
Maybe this website will be helpful:
http://www.javaworld.com/javaworld/javatips/jw-javatip10.html
You can look at the swt-snippets (look at the listeners)
http://www.eclipse.org/swt/snippets/
or you use the runnable class , by overwritting the run method with your 'callback'-code when you create an instance

Resources