JUnit Tests with GWT Editor - gwt

In my current project we have a gwt clientapplication based on mvp pattern. Now I have a View that implements Editor and a Presenter who gets the EditorDriver per getter access. The Presenter call edit() and flush() on the EditorDriver.
What I have found is a MockSimpleBeanEditorDriver but nothing like a editormock. A ready to use "MockSimpleBeanEditor" would be nice.
Is there any way to get that working in an JUnit test?

A possible route for you to take is to 'fabricate' a mock editor.
The simplest and elegant way I can think of is Mockito.
Check this out::
Comparable c = mock(Comparable.class);
when(c.compareTo("Test")).thenReturn(1);
assertEquals(1, c.compareTo("Test"));
This code snippet fabricates an instance of Comparable that will return '1' when passed the string 'Test'.
More info here

Related

What is the difference between testng annotation #Beforemethod and beforeinvocation() listener?

Does #Beforemethod() and beforeInvocation() listener do the same? Please help with the difference!
#Beforemethod: The annotated method will be run before each test method meaning Methods annotated with #Test annotation
If you have implemented the IInvokedMethodListener listener
void beforeInvocation(IInvokedMethod method, ITestResult testResult)
void afterInvocation(IInvokedMethod method,ITestResult testResult)
then IInvokedMethodListener will be invoked for configuration(#BeforeSuite...) and test methods (#Test ...).
From an execution stage perspective, both get executed before a method annotated with #Test is called. It allows you to do any kind of setup you need for a test.
But when do you use what will be based on what is it you want to do.
If you have a specific setup for only a few tests, I will use #BeforeMethod in a class which would apply only to a few tests.
But if it is an suite wide setup, say initializing a driver object or creating an API token which needs to be done for every single test in your suite, then I would prefer listeners.

How to exclude classes from triggering Aspect method call

I have a method in an #Aspect service method called logChangesAndAnnounceNewContributions that fires whenever somewhere in the webapp the save method of Spring-data's JpaRepository is called. I don't want the logChanges method to be called when the save method is used within the Aspect class itself, so i used this in the pointcut definition !within(Services.SystemListenerService). But its not having any effect! The save method is still being called despite using this condition in the definition. The full definition looks like this:
#AfterReturning("execution(* org.springframework.data.jpa.repository.JpaRepository.save(..))" +
"&& !within(Services.SystemListenerService) && args(entity)")
private void logChangesAndAnnounceNewContributions(Object entity){
What am i missing here?
EDIT: I tried changing !within content to !within(#org.aspectj.lang.annotation.Aspect *) but that doesn't work either..
Assuming that Services.SystemListenerService is the fully qualified name of your aspect (class name SystemListenerService, package name Services with strange upper-case first letter), within() does not work because at the time of execution(* org.springframework.data.jpa.repository.JpaRepository.save(..)) we are not within(Services.SystemListenerService) anyway but rather within(org.springframework.data.jpa.repository.JpaRepository). So there is the logical error in your pointcut.
There are ways to solve this in AspectJ, such as
call(A) && !adviceexecution(),
execution(A) && !cflow(execution(B)),
but both pointcut types are unsupported in Spring AOP. So you
either need to activate full AspectJ via LTW in Spring
or abuse some Spring methods in order to get the real object underneath the proxy via ((Advised) myProxy).getTargetSource().getTarget() and call the method directly on that object from your aspect
or obtain a stack trace from a newly created exception or from the current thread and inspect it manually - very ugly.
Sorry, but Spring AOP is just "AOP lite", I think you should go for AspectJ. The second option is also a bit hacky but will probably work.

GWT Deferred binding failed for custom class: No class matching "..." in urn:import:

I am developing a couple of custom widgets that I would like to be able to use with UiBinder. Unfortunately I keep wasting my life away with chasing down the following error:
No class matching "..." in urn:import:...
This seems to be the catch-all exception that is thrown any time there is any error in the class that prevents the GWT compiler from processing it. This includes anything in the class's entire dependency tree.
To save myself and anyone of you who is running into the same issue some time and pain, let's compile a list here of the most unexpected and hard to find causes for this. I'll start with my latest one, which has made me decide to post this here.
I was using a CellList thusly:
private static RelationshipViewerUiBinder uiBinder = GWT.create(RelationshipViewerUiBinder.class);
#UiField(provided=true)
CellList<String> prioritisedDisplay;
public RelationshipViewer() {
prioritisedDisplay = new CellList<>(new TextCell());
initWidget(uiBinder.createAndBindUi(this));
}
note the Java 7 style <> on the CellList. Despite my IDE's protestations to the contrary, it turns out you DO need to explicitly say CellList< String> in that new call, or it wont compile and all you get is the above mentioned error. Thanks by the way, the existance of this question prompted me to scrutinise my code and probably saved me a couple of hours! This fixed it:
private static RelationshipViewerUiBinder uiBinder = GWT.create(RelationshipViewerUiBinder.class);
#UiField(provided=true)
CellList<String> prioritisedDisplay;
public RelationshipViewer() {
prioritisedDisplay = new CellList<String>(new TextCell());
initWidget(uiBinder.createAndBindUi(this));
}
I had written a component that used the GWT JSON functionality, but hadn't imported com.google.gwt.json.JSON into the module.
Thanks to your message here, this was only 2 hours down the drain...
I wrote a helper-class that this widget uses somewhere deep inside its dependency tree.
For this helper-class, I told Eclipse to auto-generate the hashCode() and equals(...) functions. The class contained a field of type double, for which Eclipse generates code that uses Double.doubleToLongBits().
Turns out GWT does not implement this method on its version of Double. But of course, neither does Eclipse detect this as a possible compile-error, nor does it cause any issues in Dev Mode if I use the widget inside the GWT-App's Java code rather than inside UiBinder.
3 hours down the drain... Great... Yay for helpful error messages.
UPDATE:
As of GWT 2.5.0 (RC1) GWT now supports Double.doubleToLongBits() rendering this particular error obsolete, but the general error mechanism of a missing JRE emulation remains and will probably manifest itself in a similarly unhelpful way.
I was trying to use a GwtQuery DragAndDropCellTree in a UiBinder .ui.xml, which was impossible as DragAndDropCellTree has no zero-arg constructor.
See more details

Dont understand the concept of extends in URL.openConnection() in JAVA

Hi I am trying to learn JAVA deeply and so I am digging into the JDK source code in the following lines:
URL url = new URL("http://www.google.com");
URLConnection tmpConn = url.openConnection();
I attached the source code and set the breakpoint at the second line and stepped into the code. I can see the code flow is: URL.openConnection() -> sun.net.www.protocol.http.Handler.openConnection()
I have two questions about this
First In URL.openConnection() the code is:
public URLConnection openConnection() throws java.io.IOException {
return handler.openConnection(this);
}
handler is an object of URLStreamHandler, define as blow
transient URLStreamHandler handler;
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right? But there are a lot classes who implement this methods in sun.net.www.protocol (like http.Hanlder, ftp.Handler ) How should the code know which "openConnection" method it should call? In this example, this handler.openConnection() will go into http.Handler and it is correct. (if I set the url as ftp://www.google.com, it will go into ftp.Handler) I cannot understand the mechanism.
second. I have attached the source code so I can step into the JDK and see the variables but for many classes like sun.net.www.protocol.http.Handler, there are not source code in src.zip. I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip? Where can I find a comprehensive version of source code?
Thanks!
First the easy part:
... I googled this class and there is source code online I can get but why they did not put it (and many other classes) in the src.zip?
Two reasons:
In the old days when the Java code base was proprietary, this was treated as secret-ish ... and not included in the src.zip. When they relicensed Java 6 under the GPL, they didn't bother to change this. (Don't know why. Ask Oracle.)
Because any code in the sun.* tree is officially "an implementation detail subject to change without notice". If they provided the code directly, it helps customers to ignore that advice. That could lead to more friction / bad press when customer code breaks as a result on an unannounced change to sun.* code.
Where can I find a comprehensive version of source code?
You can find it in the OpenJDK 6 / 7 / 8 repositories and associated download bundles:
http://hg.openjdk.java.net/jdk6/jdk6 - http://download.java.net/openjdk/jdk6/
http://hg.openjdk.java.net/jdk7/jdk7 - http://download.java.net/openjdk/jdk7/
http://hg.openjdk.java.net/jdk8/jdk8
Now for the part about "learning Java deeply".
First, I think you are probably going about this learning in a "suboptimal" fashion. Rather than reading the Java class library, I think you should be reading books on java and design patterns and writing code for yourself.
To the specifics:
But URLStreamHandler is a abstract class and method openConnection() is not implement in it so when handler calls this method, it should go to find a subclass who implement this method, right?
At the point that the handler calls than method, it is calling it on an instance of the subclass. So finding the right method is handled by the JVM ... just like any other polymorphic dispatch.
The tricky part is how you got the instance of the sun.net.www.protocol.* handler class. And that happens something like this:
When a URL object is created, it calls getURLStreamHandler(protocol) to obtain a handler instance.
The code for this method looks to see if the handler instance for the protocol already exists and returns that if it does.
Otherwise, it sees if a protocol handler factory exists, and if it does it uses that to create the handler instance. (The protocol handler factory object can be set by an application.)
Otherwise, searches a configurable list of Java packages to find a class whose FQN is package + "." + protocol + "." + "Handler", loads it, and uses reflection to create an instance. (Configuration is via a System property.)
The reference to handler is stored in the URL's handler field, and the URL construction continues.
So, later on, when you call openConnection() on the URL object, the method uses the Handler instance that is specific to the protocol of the URL to create the connection object.
The purpose of this complicated process is to support URL connections for an open-ended set of protocols, to allow applications to provide handlers for new protocols, and to substitute their own handlers for existing protocols, both statically and dynamically. (And the code is more complicated than I've described above because it has to cope with multiple threads.)
This is making use of a number of design patterns (Caches, Adapters, Factory Objects, and so on) together with Java specific stuff such as the system properties and reflection. But if you haven't read about and understood those design patterns, etcetera, you are unlikely to recognize them, and as a result you are likely to find the code totally bamboozling. Hence my advice above: learn the basics first!!
Take a look at URL.java. openConnection uses the URLStreamHandler that was previously set in the URL object itself.
The constructor calls getURLStreamHandler, which generates a class name dynamically and loads, and the instantiates, the appropriate class with the class loader.
But URLStreamHandler is a abstract class and method openConnection()
is not implement in it so when handler calls this method, it should go
to find a subclass who implement this method, right?
It has to be declared or abstract or implemented in URLStreamHandler. If you then give an instance of a class that extends URLStreamHandler with type URLStreamHandler and call the openConnection() method, it will call the one you have overriden in the instance of the class that extends URLStreamHandler if any, if none it will try to call the one in URLStreamHandler if implemented and else it will probably throw an exception or something.

How do you handle instantiation of Messages classes in GWT?

I have a question on how you usually instantiate GWT Messages. I usually do this:
private static final GenericMessages GENERIC_MESSAGES = GWT.create(GenericMessages.class);
I usually do this in every class that uses the GenericMessages Interface, is this a nice thing to do, or should I create a MessagesSingleton that instantiates all my Messages interface and I just access it from there?
Thanks in advance.
You don't have to worry about it. The GWT compiler will replace all your GENERIC_MASSAGES inside the code.
Example:
If you have in your propert file:
applicationName=My Application
and in your java class like this:
label.setText(GENERIC_MESSAGES.applicationName());
in compilation time the gwt compiler will replace to
label.setText("My Application");
and will remove your variable.