gwt java: ant code code reuse eclipse example fix gwt library tutorial web application
leave a comment
Multiple Projects and GWT
When working on several large scale projects (in Eclipse), it’s convenient and of course more efficient to share and reuse code via common libraries. While those are in an early stage they need to be changed a lot and therefore it’s handy to link projects in instead of creating new jars each time the library has been updated.
Unfortunately, this standard approach for Java development in Eclipse does not work that straight forward as with plain old Java projects, it requires three steps in total:
- Link the library project to all relevant projects (“Project Preferences” -> “Java Build Path” -> “Projects” -> “Add…”)
- Then, add the client-side code of the library (by adding it as a module.) Therefore, edit the gwt.xml of your application and add for example
<inherits name="net.svenbuschbeck.gwt.lib.SuperLib "/>where SuperLib is the file name of the gwt.xml file in you library project and before that is the package it lies in. - Add the code to the project by linking a source folder. Unfortunately, this is required if you do not want to write an Ant script to compile your application. (If you prefer Ant check this out) I don’t like the idea of using such a script because if you forget to run it each time you make changes, you will end up in confusion—let’s go for the convenient, automatic way then.
- Add a folder to your application project; open the “advanced” section in the folder creation dialog, select “Link to alternate location” and pick the source folder (usually “src”) of your library project. (Hint: if you work within a team using a versioning system, you can create a variable for that folder and use this instead. This way, each of your colleagues can put the library project in a different folder and accommodate for that by adjusting the variable
) - Right click the folder, “Build Path” -> “Use as Source Folder”. Done.
- Add a folder to your application project; open the “advanced” section in the folder creation dialog, select “Link to alternate location” and pick the source folder (usually “src”) of your library project. (Hint: if you work within a team using a versioning system, you can create a variable for that folder and use this instead. This way, each of your colleagues can put the library project in a different folder and accommodate for that by adjusting the variable
Surprisingly, the GWT plugin for Eclipse does not honor the project linking, thus all the references need to be made explicit or you will end up with lots of the following: ClassNotFoundException.
How to Execute Code When the GWT Application Is Going Down
My goal was to store the UI state of my application just before it gets terminated to be able to restore it next time the way the user left it the other day.
I tried to add an addAttachHandler to the RootPanel to get informed about the root panel getting detached from the DOM so that I can finalize my application. Surprisingly, that does not work in Chrome (tested Chrome and Firefox only).
But besides that this sounds like a bug to me, I found the “proper” way of doing things before the application ends:
Window.addWindowClosingHandler(new Window.ClosingHandler() {
@Override public void onWindowClosing(ClosingEvent event) { ... }
});
In the end, I think something like Document.addUnloadHandler would be more suggestive… closing the window or reloading a page is both exiting the application by unloading the DOM — not closing the window.
Java Cookies from the Future Past
While working with cookies in Java/GWT and thus—to set the expire date—with Date, I found a doubtful Java behavior.
My goal was to set a cookie to expire in about one month from today like this:
Date expires = new Date(new Date().getTime() + 1000 * 60 * 60 * 24 * 30);
Cookies.setCookie("myCookie", "myData", expires);
And kept wondering why the cookie never got stored.
And finally created a simple test case like this:
Date today = new Date(); Date tomorrow = new Date(today.getTime() + 1000 * 60 * 60 * 24); Date nextMonth = new Date(today.getTime() + 1000 * 60 * 60 * 24 * 30);
And got following dates:
today=Mon Feb 07 14:27:50 CET 2011 tomorrow=Tue Feb 08 14:27:50 CET 2011 nextMonth=Tue Jan 18 21:25:02 CET 2011
According to Java’s calculation, the cookie was expired already before even being set.
Took me a bit to understand why:
1000 * 60 * 60 * 24 * 30 = 2,592,000,000 = 0x9A7EC800
Thus, the first bit got set to one… a classical overflow causing the integer value to become negative — just try:
System.out.println(1000 * 60 * 60 * 24 * 30);
It will print out -1702967296.
Fix: Add a little L will solve the issue by forcing the compiler to calculate using the scope of long:
Date nextMonthLong = new Date(today.getTime() + 1000L * 60 * 60 * 24 * 30);
I guess I will fall for that one again sometime as the error is not obvious in my opinion — especially because getTime() returns a long and still, the compiler sticks with an int for the multiplication part.
Disable Context Menu in GWT
To make use of the right mouse button, it is necessary to disable the native browser context menu (the popup menu appearing on right click). This can be achieved like this:
RootLayoutPanel.get().addDomHandler(new ContextMenuHandler() {
@Override public void onContextMenu(ContextMenuEvent event) {
event.preventDefault();
event.stopPropagation();
}
}, ContextMenuEvent.getType());
Same should work for RootPanel.
After that, it is possible to make use of the right mouse button for example like this:
someWidget.addDomHandler(new MouseMoveHandler() {
@Override public void onMouseMove(MouseMoveEvent event) {
if (event.getNativeButton() == NativeEvent.BUTTON_RIGHT) {
...
java projects: API code example flickr Java tutorial web application
leave a comment
Authentication with FlickrJ
When you know about username and password logins, the whole Flickr authentication process for web applications seems a little weird on first sight, nevertheless it is logical and necessary after you have done some reading (for example the official Flickr WebApp Auth HowTo).
To get started and into coding quickly (using FlickrJ and Java) I recommend this page. Especially the code example is excellent in my opinion! Thanks Andy Sacher!
gwt jobs: GAE gwt tutorial virtual machine web application website
leave a comment
Testing GWT Application in Virtual Machine
I am developing on a Mac, but to test my GWT applications for cross-browser compatibility in Internet Explorer I need to use Windows, thus I got Windows 7 installed using Parallels. Just by the way, to be able to test in different Internet Explorer version, I am using a pretty handy application called IETester.
But trying to access localhost with IE in the virtual machine did not work. I got a “404 page not found” error instead of seeing my app running on the local App Engine instance. Obviously, Parallels does not automatically forward localhost requests to OSX and maybe that is actually a good idea security-wise.
To fix the issue, you need to run Google App Engine on a public network interface, or in other words, bind the App Engine server to all available IP addresses. The down side: everybody knowing your IP address can see the GWT app now, but otherwise you are not allowed to access it in the virutal machine as from your OSX’s point of view, that Windows machine is “some other guy accessing from the outside”, too. To make GAE accessible from the outside, add the parameter “-bindAddress 0.0.0.0″ when launching you local GAE. Using Eclipse you can achieve that by right clicking your project -> Run As -> Run Configurations -> Choose “(x)= Arguments” tab; add the option to the top most box titled “Program arguments” in the options area (e.g. before “-port 8888″).
The first part of the list of arguments should look something like that:
-remoteUI "${gwt_remote_ui_server_port}:${unique_id}" -startupUrl GlocalUiPg2.html -logLevel INFO -codeServerPort 9997 -bindAddress 0.0.0.0 -port 8888 ...
Now, you can access you app using the OSX’s public IP address. (You can get to know your IP by having a look at the network preferences panel.) Launching GAE from Eclipse, you will see a different link (URL) in the “Development Mode” tab now, containing the public IP already. Using that one in, say, your Firefox on Mac, it will ask you now whether you want to allow the debugger access. That is also due to the fact, that you are now using a public address, so it is not clear to your local debug server, whether that request came from the same computer or someone else in the network.
Casting collections in Java
Assuming two classes A and B as
class A {}
class B extends A {}
It is just logical that casting B to A works fine:
A anObjectOfClassA = new B();
But when it comes to collections of As and Bs, a strange phenomenon appears in Java:
Collection<B> collectionOfBs = new LinkedList<B>(); Collection<A> collectionOfAs = (Collection<A>)collectionOfBs; // this line does not compile!
That is, though the collection wrapper (the java.util.Collection class) is the same and B extends A, casting a collection of objects of class B to a collection of objects of class A throws an compile-time error.
But it works using generics (the whole class for the sake of completeness and reusability):
import java.util.Collection;
import java.util.LinkedList;
public class CollectionCastingExample {
class A {}
class B extends A {}
Collection<B> collectionOfBs = new LinkedList<B>();
// Collection<A> collectionOfAs = (Collection<A>)collectionOfBs;
Collection<A> collectionOfAs = downCastCollection(collectionOfBs, A.class);
/**
* Casts a collection of objects of class B where B extends A to a collection of objects of class A.
*
* @param <T> Base class
* @param collection Collection of objects of a class extending T
* @param aClass Representation of T
* @return Collection of objects of T casted from given collection of objects of a class extending T.
*/
@SuppressWarnings("unchecked")
public static <T> Collection<T> downCastCollection(Collection<? extends T> collection,
Class<T> aClass) {
return (Collection<T>) collection;
}
}
Despite the fact that a @SuppressWarnings("unchecked") is required, it avoids iterating over the whole collection of Bs and casting each of them from B to A plus adding them to a new collection of As.
Adding a New Service (GWT)
Adding a new servlet/service to you GWT application is quite straight forward, e.g. by copying the example “greetingService” or creating a new servlet. But it’s easy to overlook a required change/adjustment of your project’s configuration and you might end up with an error message like “Blocked attempt to access interface ‘some.package.SomeService’, which is not implemented by ‘some.other.package.SomeOtherServiceImpl’; this is either misconfiguration or a hack attempt”.
Check list (some should be replaced with whatever you want to call your new service):
- Copy or create files:
SomeService.java and SomeServiceAsync.java in client package
SomeServiceImpl.java in server package + change implementation statement to SomeService - Adjust web.xml:
<servlet> <servlet-name>someServlet</servlet-name> <servlet-class>some.package.SomeServiceImpl</servlet-class> </servlet> <servlet-mapping> <servlet-name>someServlet</servlet-name> <url-pattern>/[copy base directory name from other service declaration]/some</url-pattern> </servlet-mapping>
- Annotate interface SomeService.java:
@RemoteServiceRelativePath("some") - Connect to your new service in the client:
private final SomeServiceAsync someService = GWT.create(SomeService.class);
Definitely some possibilities to make a mistakes or miss something here.
Resizing System or Home Partion
A very convenient tool for creating, moving, and resizing partitions is GParted. I use it for all my partition-changing-needs — it is really powerful and yet easy to use!
But it is not possible to resize system relevant partitions while the system is running — makes sense, right?
But you can download GParted as LiveCD ISO file and burn it on a CD. After that, restart your computer with the CD in your drive and a small linux will start up directly from CD including GParted, thus allowing you to modify any drive and partition there is.
Do all required changes, click the exit button and you are done. In my case, the computer did not reboot automatically, instead I ended up with a command line interface — use the command “sudo reboot” to restart the system yourself if that happens.
And just by the way, GParted does also handle Windows partitions easily — so there is no need to buy or “get” Partition Magic from somewhere. But never forget to backup your data first.
Yet another hint: GParted works most reliable if you do one step at a time. So for example, there are partitions A and B (A is in front of B) and you wish to give some of the free space in A to B. You need to do following steps: Shrink A, move B left and finally grow B. From my experience, GParted works best if you really do all those steps separately, apply each of then, and go for the next one if the last one finished successfully.
Flickering Screen After Upgrade to Kubuntu 10.04
First of all, I was amazed how smoothly the upgrade went. (K)Ubuntu and I guess other distributions as well have gone quite a far way to become platforms for everybody — with a lot of software but even more tools, helpers and automatic background services — like the nice upgrade service.
There was only one problem I ran into and I want to share the solution.
I am running Kubuntu 10.04 (just upgraded today) on a Lenovo IBM ThinkPad R60 (Yes, one of those with both brands on them
) with an ATI Radeon X1400 graphics device. But since upgraded, my display started flickering — not permanently but unbearable.
The solution that worked for me (at least partially — see below — and this is of cause depending on the graphics device type) was to install the proprietary ATI drivers. I know, it is not a good solution, I do not like to use them neither and if anyone out there is reading this with a better solution in mind, let me know it!! ![]()
Edit 2011-02-14: Added a new post with an additional, alternative solution here.
So what you need to do is to get your favorite package management tool (e.g. Synaptic or KPackageKit) — just hit Alt+F2 and type “package” and pick KPackageKit from the list (it will ask you for the super user password). Then, search for “fglrx”. In KPackageKit, you will find a result titled “Video driver for the ATI graphics accelerator”, and something below the title like “fglrx — 2:8.723.1-0ubuntu3” but the version number should not matter. Click the arrow to the right, hit “Apply” and after rebooting, everything should perfectly without any configuration.
Good luck.
Problems noticed so far: The driver causes “Segmentation Fault” error messages, e.g. when trying to open up the display settings. That’s ugly, I know. But you can read in several forum and blog posts, that the support for the former nicely working driver for the ATI X1400 has been discontinued since 10.04, hence, it’s just good luck that the fglrx works somehow — good to know *after* upgrading, right. But still, the flickering was unbearable for me, thus, I accept the issues for now. I will keep my eyes peeled hoping for a proper solution in the future.
Change hotkey of Kubuntu’s Quick Launch Tool KRunner
First of all: I love those quick launch tools aka keystroke launchers, they are real time savers — everyone should have one!
[For those without a glue what a keystroke launcher is:] It is THE tool for launching any kind of software or even opening documents. Instead of moving your mouse to you applications menu, click it, search the program, move the mouse there, maybe pick a sub-folder, move mouse again and finally click — unless you accidentally moved a little but to far and the menu close again, completely.
But it is easy to put an end to this (as described below). Instead of doing all that clicking, you hit a special key combination, by default [Alt] and [Space], this will make a small input box show up, now, you only enter the first letters of the program — e.g. “f” will do after a few uses to start Firefox (the program learned that you use it a lot). It might save only a few seconds each time, but the sum up and, hey, it is very convenient, too!
So here is what you need to do:
Mac OS: It is already built-in — Just hit Alt+Space and type the name of the program you want to start (or files or whatever).
Windows: Get/install Launchy and use it as explained above.
Kubuntu: built-in as well, BUUUT you have to hit Alt+F2 instead.
And there it is, something that kept annoying me about Kubuntu for quite a bit. I was hoping to get used to it but for what reason? Alt+F2 is really not handy compared to Alt+Space.
Finally, based on this old forum post and a few adjustments to fit nowadays Kubuntu, all you need to do is this:
- Go to “Settings” -> “Keyboard and mouse”
- Select “Global Keyboard Shortcuts”
- Pick from the select box “KDE component” at the top “Run Command Interface”
- Now, you can access “Run Command” — Change it to whatever you like
Moving home to it’s own partion (Ubuntu)
We are going to move all accounts including their personal data on a distinct partition. This recommended in case of system failure to not loose any data.
I have no idea, why the Ubuntu installation wizard does not do this by default — it should!
This post is based on an article in German — I will mainly translate it, strip some plush and add some stuff to make life easier and to reduce the risk of data loss. But be aware: to perform any of those following things, you will need super user rights and you should feel somewhat comfy with using the command line. And of course, it might be possible in circumstances unforeseen, that you lose all your personal data — but there are a lot of backup steps included below.
Here we go: (console input or statements are written in italics)
- Preparation
- Create a backup: rsync –avx –progress /home <your backup destination>
- If you do not have a free partition yet, I recommend GParted to create one (use sudo apt-get install gparted). I recommend ext3 for compatibility issues — but if you use Linux only, you can go for ext4 (please change ext3 to ext4 in step 1.6 in case) — make sure your new partition is big enough for your home folder! Try to remember the size (get size: du –sh /home) of /home, you can use it later on to verify your new home location.
- Get partion name sudo fdisk –l /dev/sda — e.g. /dev/sda7 — I will refer to this name as (name)
- Copy your current file system configuration: sudo cp /etc/fstab /etc/fstab.new
- Get partion UUID of new partition: sudo blkid — you will find a line about (name) stating a UUID (quite a long hex string), I will refer to it as (uuid) — copy it.
- Edit /etc/fstab.new, add a new line at the end as follows (the layout should follow previous lines — simply copy one and adjust it):
UUID=(UUID) /home ext3 defaults 0 2
- Copy
- Sign off / Log out
- Switch to console mode by pressing Ctrl+Alt+F1
- Create a mount point for the new partition: sudo mkdir /mnt/tmp
- Add partion: sudo mount (name) /mnt/tmp
- Copy home from the old location to the new partition: sudo rsync –avx –progress /home/ /mnt/tmp
- Test
- Mount copy of home as new home: sudo mount (name) /home
- Check size of home folder — should be the same as in step 1.: du –sh /home
- Check mounting worked: sudo mount| grep /home should print out something like
(name) on /home
- Switch
- yet another home backup: sudo mv /home /home.bak
- create new home mount point: sudo mkdir /home
- create a backup of fstab: sudo mv /etc/fstab /etc/fstab.bak
- put updated version in place: sudo mv /etc/fstab.new /etc/fstab
- reboot and you should be done: sudo reboot
Ok, that’s that. If everything works fine, you can delete the backup home sudo rm –rf /home.bak and the fstab backup sudo rm /etc/fstab.bak. Hope you found it useful and I did not put in a mistake or typo. Gimme feedback!
Simple redirection using PHP and HTML meta tag
Something everyone needs once in a while… maybe you moved a file on your server or you did not install wordpress in the root folder of your webserver — like I did neither
— a redirection or forwarding can be an easy answer.
The script is rather simple — it redirects in three ways to provide a reasonable fall back if any of the automatic redirecting fails. To use it on your server, just enter the URL/address/file name/folder you would like the user to be redirected to in the second line of the page/script.
<?php
$url = 'put your URL between the parenthesis';
header("Location: $url");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<meta http-equiv="refresh" content="0;url=<?php echo $url; ?>"/>
<title>You will be redirected... </title>
</head>
<body>
If you are not redirected automatically, please click <a href="<?php echo $url; ?>">here</a>.
</body>
</html>
how to install memchached 1.2.2 from source
I have installed an instance of memchached version 1.2.2 on one of our servers (Debian etch) today and to keep you from spending a whole afternoon, see my everything-step-by-step instruction below.
Memchached is a distributed hash map, which can be used for example to speed up any kind of web application, see website for details. In our case, we want to use it as temporary data store. I will report about the experiences in a latter post.
introduction
Always refer to this page for details, but I created a version with less text but including steps to really start from scratch.
All lines starting with # are command lines, i.e. you need to type into a linux shell.
Output of any kind is always surrounded by ” even if it is multiline output.
content
a. get libevent (needed to install memcached)
b. get memcached and verify installation
c. use and test memcached within Java with junit/ant
a. installing libevent 1.3
a.1. check for current version of libevent
a.1a.
Log in as root or get super user rights by calling su
# updatedb
# locate libevent
If there is output including “libevent1” and/or “libevent-1″ (ignore package files like *.deb) -> a.1b, otherwise a.2
a.1b. removing old libevent version
# apt-get remove –purge libevent1
# Y
# updatedb
# locate libevent
Should now return nothing or package files only, i.e. you are ready for installation
a.2. installing libevent 1.3
a.2a downloading and unpacking
# cd /usr/local/src
# wget http://monkey.org/~provos/libevent-1.3b.tar.gz
# tar zxvf libevent-1.3b.tar.gz
# cd libevent-1.3b
a.2b. configuring
# ./configure
check the output, if it contains something like “configure: error: no acceptable C compiler found in $PATH” -> a.2c. otherwise a.2d.
a.2c. compiling
# apt-get install gcc
Redo a.2b.
I got output like “C compiler cannot create executables”, reading file ‘config.log’ did not help me at all. Googling finally did, as I found a forum entry, pointing out a missing lib.
So try this:
# apt-get install libc-dev
Redo a.2b.
If that did not solve it… sorry … google on, there is no sense in going on without solving this issue. :-/
a.2d. make it!
# make && make install
If you get something like “-bash: make: command not found” -> A.2e, otherwise A.3.
a.2e.
# apt-get install make
Redo a.2d.
a.3. configuration
Press the Esc key as you read [esc] in the commands below.
# vim /etc/ld.so.conf.d/libevent-i386.conf
# i/usr/local/lib/[esc]:wq
# ldconfig
b. install memchached and verify installation
b.1. download, unpack and install memchached
# cd /usr/local/src
# wget http://danga.com/memcached/dist/memcached-1.2.2.tar.gz
# tar zxvf memcached-1.2.2.tar.gz
# cd memcached-1.2.2
# ./configure
# make && make install
After installing gcc and libc-dev in section a, this one went easily for me — if you skipped section a and run in problems here, please install gcc and libc-dev (see a.2c).
b.2. verify installation of memchached
b.2a. start memchached server
# memcached –u www-data –vv
Output should end with line “<3 server listening”. Perfect!
b.2b test server
I will refer to this shell in front of you as server shell below. Now, open another shell on the same machine, I will refer to it a client shell.
# telnet localhost 11211
You should see something like “<7 new client connection” on the server shell, switch back to client shell.
# set test1 1 10000 1
# a
You should see “STORED” on client shell and the two following lines on server shell
”<7 set test1 1 10000 1
>7 STORED”
Perfect!
You did it, your memcached is up and running
c. memcached and Java
I wrote a little test package using a Java client library for memcached from here, together with junit and ant. You can download it to have a look how simple using memcache is and to verify your installation with an included junit test, automated with an ant build file.