How to write tests for tracking event flows in eventbus? - gwt

Long description:
In our gwt with mvp4g app we have pretty complicated flow of events in eventbus. One event like LOGIN produces multiple others as a reaction from presenters/handlers. Currently we have great difficulties with understanding how events interrelated i.e. which events must follow this particular one.
We have tests for presenters and views, but we are lacking tests which would clearly show/model event flows, preferably without usage of real views and services.
Short description:
New tests on eventBus(?) should be developed which should clearly describe and test event flows.
I have few rud ideas but they all sounds not satisfactory:
Write custom implementation(could be ugly) of mvp4g eventbus and:
use real presenters
use mock(?) views
mock services
verify all produced service calls
Why not cool: (a) In this case test would not verify produced events directly but only that ones which have services. (b)
EventBus implementation would look rather scarry - it must create each presenter with mocked services and views
Find a way to use some magical mvp4g mechanism to create eventBus in test and mock vies, services.
Why not cool : same as prev - only indirect verification through services is possible, and I cannot find how to create eventBus manually and solve all problems with GIN, inter GWT module dependencies and so. I guess there is no simple way to do it.
Is there any general solution for problem of tracking event tree in tests? Guess I'm not the first person to stare at complicated eventbus event flows.

Do you want to test the eventBus? Or do you want to track all event which are fired?
If you want to track your events, maybe some kind of EventMonitor could help you? A class that implements all necessary EventHandler and log every event that occurs.
Something like that? Just instance that class before your tests starts.
import java.util.logging.Logger;
import com.google.gwt.event.shared.GwtEvent;
import com.google.web.bindery.event.shared.EventBus;
public class EventMonitor implements AEventHandler, BEventHandler /* , ... */{
private static int event_count = 1;
private final Logger logger = Logger.getLogger(this.getClass().getName());
public EventMonitor(EventBus eventBus) {
eventBus.addHandler(AEvent.getType(), this);
eventBus.addHandler(BEvent.getType(), this);
// [...]
}
private void logEvent(GwtEvent<?> event) {
logger.info(event_count + " useful information");
event_count++;
}
#Override
public void onAEvent(AEvent event) {
logEvent(event);
}
#Override
public void onBEvent(BEvent event) {
logEvent(event);
}
}

Related

Vert.x run blocking handler before and after other handlers

I'm trying to write a Vert.x Web handler that could be used to hide any processing latencies from an API to prevent figuring out existence of accounts as well as other information from an API. I would like to be able to just write something like:
router
.post("/uri")
.handler(new LatencyNormalizer())
.handler(new UriHandler());
In other words, make it as easy to use as possible and as easy to integrate into existing code bases as possible. Looking at the docs for Router and RoutingContext, I see only the following method as a possible candidate for implementing this:
https://vertx.io/docs/apidocs/io/vertx/ext/web/RoutingContext.html#addHeadersEndHandler-io.vertx.core.Handler-
I could then write code like:
public void handle(RoutingContext ctx) {
long start = System.nanoTime();
ctx.addHeadersEndHandler(v -> {
public void handle(RoutingContext ctx) {
long end = System.nanoTime();
Thread.sleep(...);
});
ctx.next();
}
Of course, this doesn't work, since sleep here blocks the thread. It looks like the handlers in the addHeaderEndHandlers list maintained internally by the RoutingContext are called synchronously, so there is no way to use e.g. vertx.SetTimer() inside the addHeaderEndHandler.
In other words, does Vert.x offer any interface that allows creating a handler which is called asynchronously before writing out to the wire (and with nothing written until the async call finishes)? This is for example how Netty works under the hood, which Vert.x leverages. I know I could implement this LatencyNormalizer as a base class for my other handlers, but it would not be as easy to integrate in existing code in that case.

GWTP REST-Dispatch - What is the new usage for rest dispach, since the removal of the RestService interface in 1.5 release

Hi everybody,
I encounter implementation issues with the rest-dispatch module of the gwtp framework.
If i follow the current documentation, the resource interface defining what a service provide should be as follow:
#Path(FOO)
#Produces(MediaType.APPLICATION_JSON)
public interface FooResource {
#GET
RestAction<FooDTO> getFoo();
}
On the client side (without delegate extension):
#Inject RestDispatch dispatcher;
#Inject FooResource fooResource;
...
dispatcher.execute(fooResource.getFoo(), new AsyncCallback<FooDTO>() {
#Override
public void onFailure(Throwable throwable) {
}
#Override
public void onSuccess(FooDTO fooDto) {
}
});
...
Question
The RestDispatch is waiting for method that return RestAction, but since the RestService interface has been remove from 1.5 release:
How can i implements the FooResource ?
Moreover
In the carstore sample project, the only resource that uses RestAction is:
https://github.com/ArcBees/GWTP-Samples/blob/master/carstore/src/main/java/com/gwtplatform/carstore/shared/api/StatisticsResource.java
But it's implementation, is in fact not an implementation in that case:
https://github.com/ArcBees/GWTP-Samples/blob/master/carstore/src/main/java/com/gwtplatform/carstore/server/api/StatisticsResourceImpl.java
Should i follow this example, and what is the purpose of an non-implemented Interface ?
I assume that my question is very specific and it is maybe principally directed to the authors of gwtp.
And i thank in advance those who will respond.
The rest-dispatch is a client-library, and the interface that describes the services are not to use on the server side.
I was attempting to do something not intended by the authors of GWTP.
Yet, the DelegateResource extension is a solution, if you want to use the interface on the server side too. It comes with a drawback: the anability to have type safe callback on the client side.
To go further, here the exchange i had with the team on github:
https://github.com/ArcBees/GWTP-Samples/issues/92

OSGi Declarative services filter references at runtime

I've been trying some examples with OSGi Declarative Services (among other things, such as Blueprint) on Karaf. The problem I am trying to solve now, is how to get references to certain services at runtime (so annotations and/or XML are not really an option here)
I will explain my use case:
I am trying to design (so far only in my head, that's why I am still only experimenting with OSGi :) ) a system to control certain automation processes in industry. To communicate with devices, a special set of protocols is being used. To make the components as reusable as possible, I designed a communication model based on layers (such as ISO/OSI model for networking, but much more simple)
To transform this into OSGi, each layer of my system would be composed of a set of bundles. One for interfaces of that layer, and then one plugin for each implementation of that layer (imagine this as TCP vs. UDP on the Transport layer of OSI).
To reference any device in such network, a custom address format will be used (two examples of such addresses can be xpa://12.5/03FE or xpb://12.5/03FE). Such address contains all information about layers and their values needed in order to access the requested device. As you can guess, each part of this address represents one layer of my networking model.
These addresses will be stored in some configuration database (so, again, simple .cfg or .properties files are not an option) so that they can be changed at runtime remotely.
I am thinking about creating a Factory, that will parse this address and, according to all its components, will create a chain of objects (get appropriate services from OSGi) that implement all layers and configure them accordingly.
As there can be more implementations of a single layer (therefore, more services implementing a single interface), this factory will need to decide, at runtime (when it gets the device address passed as string), which particular implementation to choose (according to additional properties the services will declare).
How could this be implemented in OSGi? What approach is better for this, DS, Blueprint or something else?
I realise that this is now a very late answer to this question, but both answers miss the obvious built-in support for filtering in Declarative Services.
A target filter can be defined for a DS reference using the #Reference annotation:
#Component
public class ExampleComponent {
#Reference(target="(foo=bar)")
MyService myService;
}
This target filter can also be added (or overriden) using configuration. For the component:
#Component(configurationPid="fizz.buzz")
public class ExampleComponent {
#Reference
MyService myService;
}
A configuration dictionary for the pid fizz.buzz can then set a new filter using the key myService.target.
This is a much better option than jumping down to the raw OSGi API, and has been available for several specification releases.
I revoke my answer, because the acceppted answer is correct. When I answered that question I missed this little, but very important detail in the spec.
There is a nice way given by OSGi called service tracker. You can use inside a declarative service. In this example there is a config which holds the filter for the service you want to use. If the filter configuration changes, the whole component reactivating, so the tracking mechanism is restarting.
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
#Component(immediate = true, metatype = true)
#Properties(value = {
#Property(name = "filterCriteria", value = "(objectClass=*)")
})
public class CustomTracker {
private CustomServiceTracker customServiceTracker;
#Activate
protected void activate(ComponentContext componentContext) throws InvalidSyntaxException {
String filterCriteria = (String) componentContext.getProperties().get("filterCriteria");
customServiceTracker = new CustomServiceTracker(componentContext.getBundleContext(), filterCriteria);
customServiceTracker.open(true);
}
#Deactivate
protected void deactivate() {
customServiceTracker.close();
}
/**
* OSGi framework service tracker implementation. It is able to listen all serivces available in the system.
*/
class CustomServiceTracker extends ServiceTracker {
CustomServiceTracker(BundleContext bundleContext, String filterCriteria) throws InvalidSyntaxException {
super(bundleContext, bundleContext.createFilter(filterCriteria), (ServiceTrackerCustomizer) null);
}
#SuppressWarnings("checkstyle:illegalcatch")
#Override
public Object addingService(ServiceReference serviceReference) {
try {
Object instance = super.addingService(serviceReference);
// TODO: Whatever you need
return instance;
} catch (Exception e) {
LOGGER.error("Error adding service", e);
}
return null;
}
#Override
public void removedService(ServiceReference serviceReference, Object service) {
// TODO: Whatever you need
super.removedService(serviceReference, service);
}
#Override
public void modifiedService(ServiceReference serviceReference,
Object service) {
super.modifiedService(serviceReference, service);
}
}
}
The only option I see for this use case is to use the OSGi API directly. It sounds like you have to do the service lookups each time you get an address to process. Thus you will have to get the appropriate service implementation (based on a filter) each time you are going to process an address.
Declarative approaches like DS and Blueprint will not enable you to do this, as the filters cannot be altered at runtime.

OSGi services - best practice

I start loving OSGi services more and more and want to realize a lot more of my components as services. Now I'm looking for best-practice, especially for UI components.
For Listener-relations I use the whiteboard-pattern, which IMHO opinion is the best approach. However if I want more than just notifications, I can think of three possible solutions.
Imagine the following scenario:
interface IDatabaseService {
EntityManager getEntityManager();
}
[1] Whiteboard Pattern - with self setting service
I would create a new service interface:
interface IDatabaseServiceConsumer {
setDatabaseService(IDatabaseService service);
}
and create a declarative IDatabaseService component with a bindConsumer method like this
protected void bindConsumer(IDatabaseServiceConsumer consumer) {
consumer.setDatabaseService(this);
}
protected void unbindConsumer(IDatabaseServiceConsumer consumer) {
consumer.setDatabaseService(null);
}
This approach assumes that there's only one IDatabaseService.
[Update] Usage would look like this:
class MyUIClass ... {
private IDatabaseService dbService;
Consumer c = new IDatabaseServiceConsumer() {
setDatabaseService(IDatabaseService service) {
dbService = service;
}
}
Activator.registerService(IDatabaseServiceConsumer.class,c,null);
...
}
[2] Make my class a service
Image a class like
public class DatabaseEntryViewer extends TableViewer
Now, I just add bind/unbind methods for my IDatabaseService and add a component.xml and add my DatabaseEntryViewer. This approach assumes, that there is a non-argument constructor and I create the UI components via a OSGi-Service-Factory.
[3] Classic way: ServiceTracker
The classic way to register a static ServiceTracker in my Activator and access it. The class which uses the tracker must handle the dynamic.
Currently I'm favoring the first one, as this approach doesn't complicated object creation and saves the Activator from endless, static ServiceTrackers.
I have to agree with #Neil Bartlett, your option 1 is backward. You are in effect using an Observer/Observable pattern.
Number 2 is not going to work, since the way UI objects lifecycles are managed in RCP won't allow you to do what you want. The widget will have to be created as part of the initialization of some sort of view container (ViewPart, Dialog, ...). This view part is typically configured and managed via the Workbench/plugin mechanism. You should work with this, not against it.
Number 3 would be a simple option, not necessarily the best, but simple.
If you use Spring DM, then you can easily accomplish number 2. It provides a means to inject your service beans into your UI Views, Pages, etc. You use a spring factory to create your views (as defined in your plugin.xml), which is configured via a Spring configuration, which is capable of injecting your services into the bean.
You may also be able to combine the technique used by the SpringExtensionFactory class along with DI to accomplish the same thing, without introducing another piece of technology. I haven't tried it myself so I cannot comment on the difficulty, although it is what I would try to do to bridge the gap between RCP and OSGi if I wasn't already using Spring DM.

GWT RequestFactory and multiple types

My GWT app has ten different kinds of entities. Right now I use plain old DTOs and transport them over GWT-RPC. This works well for cases like startup - I can pack them all into a single request.
I'm looking at switching to RequestFactory because there are many times throughout the lifetime of the app (30 minutes, on average) when I just have to update one type of entity, and the unifying/bandwidth-saving features of RequestFactory are appealing. BUT: I don't see a way to download all of my initialization data in a single request when the app loads. I don't want to have to make ten requests to fetch all of the init data for my ten entity types.
Is there a way to make a GeneralRequestContext, or something? I'd even be happy with a solution like:
public interface InitDataProxy extends EntityProxy
{
public UserProxy getInitUsers();
public OrganizationProxy getInitOrganizations();
...
}
public interface GeneralRequestContext extends RequestContext
{
Request<InitDataProxy> getInitData();
}
But this won't work because I don't want to have to actually back InitDataProxy with anything, I just want to use it to combine a bunch of different types of Proxies in a single request.
So: Is there a way to receive multiple, unrelated types of EntityProxy in a single request?
I would also be happy enough making a normal gwt-rpc request to go outside of RequestFactory for this data, but I don't want to have to implement duplicate DTOs to run next to RequestFactory's proxies, and write custom code to copy the DTOs into them!
The InitDataProxy could extend ValueProxy instead, which doesn't require that the object on the server have any kind of id or version semantics. The domain-side InitData type could be an interface, possibly implemented with an anonymous type.
interface InitData {
User getUser();
Organization getOrgatization();
}
class InitService {
static InitData makeInitData() {
return new InitData() { ..... };
}
}
#ProxyFor(InitData.class)
interface InitDataProxy extends ValueProxy {
UserProxy getUser();
OrganizationProxy getOrganization();
}
#Service(InitService.class)
interface Init extends RequestContext {
Request<InitDataProxy> makeInitData();
}