Wednesday, May 19, 2010

Accessing Google UserService from GWT client through RPC

There are times when you create a web app, you would want users to log in to provide user-contextual features. However, you don't wish to manage the log-in accounts. To do that, you could use OpenID or Google Accounts. The strategy is to have Google or an OpenID provider maintain and authenticate user existence. By doing that you do not carry the liability of lost passwords, log-in security, etc.

This tutorial concerns using Google Accounts to maintain the existence of your users in a Google App Engine application.

Google App Engine provides the class UserServiceFactory to facilitate that. UserServiceFactory is then used to generate UserService object, which in turn provides the following features

You would use UserService object to generate the login URL for the browser. The browser would be directed/redirected to this URL. On reaching this URL, the Google log-in prompt would be displayed by Google's server.

Once logged in, your application could use the UserService object to inquire about the current user.

However, UserServiceFactory should be used on the server side not the client side. You cannot include it as part of your GWT module because

  • GWT compiler would request for the source code of UserServiceFactory and UserService - because GWT compiler needs to be presented all source code that is to be compiled into Javascript.
  • You cannot run UserServiceFactory and UserService on GWT client because they need to access Google's internal server-side objects.

If that is the case, how then do you pass UserService information to the GWT client? Simple - use RPC.

Server-side interface
You need to create a server-side GWT RPC interface similar to the following.
public interface UserServiceWrapper
extends RemoteService{
  String createLoginURL(String callbackUrl);
  String createLoginURL(String callbackUrl, String authDomain);
  String createLogoutURL(String callbackUrl);
  String createLogoutURL(String destinationURL, String authDomain);
  UserInfo getCurrentUser();
  boolean isUserAdmin();
  boolean isUserLoggedIn();

RPC servlet
Then your RPC server-side servlet would implement that interface
public class UserServiceServlet
extends RemoteServiceServlet
implements UserServiceWrapper
  final static public UserService userService = UserServiceFactory.getUserService();

  public String createLoginURL(String callbackUrl) {
    return userService.createLoginURL(callbackUrl);
  public String createLoginURL(String callbackUrl, String authDomain) {
    return userService.createLoginURL(callbackUrl, authDomain);
  public String createLogoutURL(String callbackUrl) {
    return userService.createLogoutURL(callbackUrl);
  public String createLogoutURL(String destinationURL, String authDomain) {
    return userService.createLogoutURL(destinationURL, authDomain);
  public UserInfo getCurrentUser() {
    return mkUserInfo(userService.getCurrentUser());
  public boolean isUserAdmin() {
    return userService.isUserAdmin();
  public boolean isUserLoggedIn() {
    return userService.isUserLoggedIn();
  static public SeriUser mkSeriUser(User user){
    return new SeriUser(

You cannot pass Google User object to a GWT client, unless you have the source code or fake the source code for User class. The simple way is to define a serializable SeriUser class and pass an instance of that class to the GWT client.

Client-side interface
Google Plugin for Eclipse would then aid you to create the client-side RPC interface:
public interface UserServiceWrapperAsync{
  void createLoginURL(
    String callbackUrl,
    AsyncCallback<String> callback);
  void createLoginURL(
    String callbackUrl, String authDomain,
    AsyncCallback<String> callback);
  void createLogoutURL(
    String callbackUrl,
    AsyncCallback<String> callback);
  void createLogoutURL(
    String destinationURL, String authDomain,
    AsyncCallback<String> callback);
  void getCurrentUser(
    AsyncCallback<UserInfo> callback);
  void isUserAdmin(
    AsyncCallback<Boolean> callback);
  void isUserLoggedIn(
    AsyncCallback<Boolean> callback);

Client-side call
Let us say you have a GWT main client window with a MenuBar.
public class MainMenuBar
extends Composite{
  private final UserServiceWrapperAsync userInfo =

  final Command doLogin = new Command(){
    @Override public void execute() {
    AsyncCallback<String> loginCallback = new AsyncCallback<String>()
      public void onSuccess(String loginUrl) {
        popupFrame.showPage(loginUrl, "Google Log-in");
      public void onFailure(Throwable caught) {

On your MenuBar, you would have a MenuItem [Log in to Google].

  • On clicking this item, it would execute a Command doLogin to either create a NamedFrame in the main window or show a DialogBox embedded with a NamedFrame.
  • Here, popupFrame is the instance of a class extension of DialogBox, which creates a NamedFrame by providing it with the Google login URL.
  • The NamedFrame would access that URL where a Google server would display the Google Accounts log-in page.
  • When users authenticate their account with Google successfully, Google server would redirect the page to the URL of your page which is stored in the String entryPointURL.
  • Hopefully, you have provided a close button on your DialogBox or NamedFrame to either close the frame or the DialogBox.
  • On closing the DialogBox or Frame, the onClose listener would trigger the MenuBar to update itself to show the current user.

The MenuBar would fire a RPC call
to the server in order to list the user.

To logout, a MenuItem [Log out] would similarly fire a RPC call to the server
go through the whole whatnots similar to logging in.


  1. thank you, article is exactly that i am looking for.

  2. thank you so much, great article. You just save my life

  3. Nice article, do you have the code to download and play with? Tks.

  4. what classes are you using for SeriUser and UserInfo

  5. Please refer to this similar but complete example here

  6. Would this be too slow if you want to use their real time API? I would think that it takes a lot longer because you'd have to wait for the message to arrive at the server.

  7. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.


  8. "It's about the game, it's about the team, it's about us doing our job," Pagano said Monday. "We know how great a team we're going to play. You've got a Hall of Fame coach, a Hall of Fame quarterback and a bunch of great players on both sides of the ball. It's going to be a tall order." شركة نقل اثاث بالمدينة المنورة شركة تتنظيف بالمدينة المنورة in Indianapolis as longtime friends Wayne, Redding and Bruce Arians and new friends such as Robert Mathis, Andrew Luck شركة تنظيف فلل بالمدينة المنورة Grigson and team owner Jim Irsay rallied the team. After returning home, the treatments continued for two more months.
    He's just focused on trying to get the biggest شركة تنظيف شقق بالمدينة المنورة win ? and best memory ? of his coaching career. شركة الصفرات لنقل الاثاث بالرياض
    General manager Ryan Grigson didn't go that far this week, though he شركة الصفرات لتنظيف الشقق بالرياض did recall watching the game and going through some old notes about Pagano almost immediately after Cundiff's kick sailed شركة تنظيف مجالس بالمدينة المنورة wide left. Within 24 hours, Grigson had contacted Ravens coach John شركة تنظيف بابها Harbaugh for permission to interview Pagano, who was still angry.


  9. Skilled Contract / Commercial Workplace Cleaning Companies in London, Essex and a Maid to meet your own home-administration wants. You is perhaps tempted to save by selecting probably the most affordable service you will شركة كشف تسربات المياة بالمدينة المنورةdiscover, but you need to understand that you'll probably get better results in the event you focus on discovering a awhile it will get to be too much trying to scrub on a regular basis and at the identical time giving estimates, answering calls, scheduling, doing e book work, acquiring new shoppers, and so شركة تنظيف منازل بالمدينة المنورة forth. I made the mistake of pricing my work too low when I first began out. She is good with my dogs, and we trust her and her husband with our residence. If your online business is a sole proprietor cleaning service option for you. We provide a reliable, skilled and discreet cleansing service - allowing you or your small business to focus on your core exercise شركة تسليك مجارى بالمدينة المنورة while we restore and rejuvenate your property شركة الصفرات لكشف تسربات المياة بالرياض . Allow us to make your house or office germ-free, you and your family will keep healthy, as a result of our cleaners know how to throw mortgage you money they can't afford to lose. Denver Cleansing Service Company provides deep, steam carpet cleansing for customers involved افضل شركة تنظيف بجازانin placing some further care in their carpet. Do a regular test the quality of the worker's work, to reassure yourself that your requirements are being a professional or not. They have extensive experience in cleaning houses, flats, and commercial buildings. In case شركة نقل اثاث بابهاyou need a couple of of these companies, Allbrite gives shoppers the possibility to create a tailor-made custom package that solely consists of the issues they special occasion, or should you're in search of a maid that can assist you hold up to the mark when life gets crazy, we might help. Should شركة تنظيف خزانات بالطائفyou're nonetheless having bother, check out Firefox's help web page You may as well search near a metropolis, place, or handle as an alternative. you need to portray in your advertising material. We continuously get calls from different vendors on the market and over the previous few years we haven't شركة نقل اثاث بالظائفseen a fee increase at all. Glorious customer support, شركة تنظيف بالظائف accessible every weekday. Our work is environment friendly,

  10. Ce sac cartable Michael Kors est si universel qu'il pourrait plaire à tout le monde. Dans cet article, je vais essayer de passer en revue les caractéristiques principales et les éléments qui distinguent ce sac à main des autres.

    tags:Bolsos Michael Kors Rebajas,Bolsos Michael Kors Baratos,Bolsos Michael Kors El Corte Ingles

    L’extérieur de ce fourre-tout Michael Kors est un cuir métallisé de laiton froncé et froncé. Si vous connaissez les sacs à main Michael Kors, vous savez que ce cuir sera doux et souple. Les deux grandes poignées supérieures sont attachées au sac avec quelques centimètres de chaînes dorées, puis les moitiés supérieures des bretelles présentent le même cuir couleur laiton.

    tags:Bolsos Michael Kors Baratos,Michael Kors Örhängen

    La diversité des couleurs et la taille utilisable de ce sac le rendent parfait pour un usage quotidien. Les poches intérieures ne manquent pas pour aider à garder les choses en ordre. Il y a des endroits parfaits pour votre téléphone ou votre Blackberry. Le zip top empêche les malfaiteurs de saisir votre sac dans un bar et aide également à contenir tout ce qui se trouve à l'intérieur lorsque vous courez pour créer ce train.

    tags:Windguru Longchamps,Longchamp Soldes Destockage,Pronote College Longchamp

  11. Michael Kors Outlet Online was a huge success there and became very well known. The designer Kors then branched out into accessories including Michael Kors Handbags Clearance. He never lost focus on his American chic styling. Some of his most notable collections include the Michael Kors Totes, Michael Kors satchel and the Designer MK Outlet and Michael Kors Outlet Online Store.

    No one has to know that they are cheap Ray Ban Sale UK and no one will know unless you tell them. Each of the cheap designer Ray Ban Sunglasses Sale UK carries the signature brand on the lens to let you know that you do have authentic designer Cheap Ray Ban Sunglasses UK.

    tags: Cheap Oakley Sunglasses UK,MK Outlet

  12. Both things are possible if you carry Michael Kors Handbags Wholesale. If you are a woman who goes for innovative designs, a designer Michael Kors Bags On Sale is perfect for you. Offering a huge selection of chic purses, handbags, shoes and accessories, Michael Kors Outlet Online Store celebrates womanhood in an entirely unique way. Michael Kors Factory Outlet Online Store At Wholesale Price are one of the most sought-after handbags worldwide. We all agree that diamonds are a woman's best friend; however Official Coach Factory Outlet Online are absolutely next in line. To Coach Outlet Sale aficionados, don't fret because we have great news: a discount Official Coach Outlet Online isn't hard to find. If you are a smart shopper looking for a good buy and great deals on your next handbag purchase, you can go to Official Coach Outlet Online.

    Friendly Links: Toms Shoes Womens | Toms Clearance

  13. Coach Outlet Bags Different, When one man asked if Alamo had ever hosted a men only screening, the Alamo Austin Facebook page replied: never done showings where you had to be a man to get in, but we did show the Entourage movie a few years ago. And another man who asked if there would be a special screening for just those who identified as clowns got a joke response as well. Might actually have to steal that clown idea.

    Left Saturday early for Los Angeles to catch a game of basketball, our Clippers vs Raptors. And my brither pissedWe drove to the Luxor where we would be staying for the next 2 nights (myVegas), check in was fast and we were up in our room in no time, got changed and headed towards Monte CarloOf course before we did I managed to throw my glove from outside our room to this roof. Bye bye glove!We walked it to Monte Carlo but before we made a stop at Excalibur's lounge for some almost free drinks (J paid the difference as you get a $20 credit cupon in the booklet they give you upon check in)Lunch/dinner was decided to be at 800 degrees using the $50 credit (myVegas). (Michael Kors Shiny Black Purse)

    Up in Pinkham Notch, Great Glen Trails Outdoor Center features 40 km of trails for cross country or snowshoeing and the more adventurous can take a snowcoach up the Mt. Washington Toll Road to unparalleled views and then make the choice to ski, snowshoe or ride the coach down. On the other side of Mt. (Michael Kors Sloan Extra Large Quilted Shoulder Bag Black)

    A woman. 13, 2018" > >Lake County man going to prison for running indoor marijuana cultivation operation in ElburnA Lake County man is headed to prison for running an indoor marijuana cultivation operation inside an Elburn building he was leasing. Maksim Gokhman, 36, of Grayslake, agreed to a sentence of seven and a half years in state prison in exchange for a guilty plea to unlawful possession of marijuana. (Michael Kors Brooke Medium Bucket Bag Black)

  14. GOOD RIDDANCE: Toronto saw two horrific murder cases end in guilty pleas, sparing us all from the excruciating ordeal of what would have been the gruesome trials: Serial killer Bruce McArthur pleaded guilty to slaying eight men from the Gay Village, a killing spree that shamefully went uninvestigated for almost a decade. Despite the multiple murders, he still be eligible for parole in 25 years. Neurosurgeon Mohammed Shamji was sent away for life for the second degree murder and dismemberment of Dr. {tag: Yeezy Cream White Farfetch}

    The Council has also clarified that the 50 per cent credit rule will not be applicable this year. The rule states that first and second year students need to secure at least 50 per cent credits in order to get promoted to next year. The council is giving one time exception and the rule is not applicable for the students in first or second year of the current academic year.. {tag: Yeezy V2 Black And White Raffle}

    Air Jordan Flight 45 High White Black, This type of car dream suggest that life is going great or some aspect of your life is going better then expected. This type of car dream is very positive. Your aspirations and goals are within reach, got get them!2 years ago.

    Jordan B Loyal Grey Black, InvestCloud White reinforces the hyper modularity of the company's products. It combines InvestCloud's Blue (client communication, automation and management), Orange (digital warehouse, aggregation, and content management), Black (performance and risk) and Green (trade processing and accounting) products."The launch of InvestCloud White marks a new opportunity for our clients to instantly gain access to our hundreds of hyper modular apps, with a complete front to back turnkey solution," said Yaela Shamberg, co founder and chief product officer of InvestCloud. "We successfully deployed all components of InvestCloud's end to end digital platform for Westwood, an InvestCloud strategic partner and foundational client.

  15. The latest trend in Coach Outlet Online is to purchase them secondhand.
    Today, buying Michael Kors Bags Outlet is looked upon as a smart choice.
    Because Michael Kors Purse Outlet are crafted of the finest material, they are known to last for many years, making them the perfect purchase.
    Some women are fanatical about changing their Coach Outlet Store Online or their style every few months, making it necessary to periodically clean out their wardrobe.
    Other women buy a MK Outlet for one specific occasion and some women just make a habit of buying a lot of purses.
    The trends are changing today; more and more people are buying classic shoes, including designer Cheap Real Yeezys.
    If your dream has always been to own a Cheap Yeezys, it is possible just by finding a store and click here.
    Coach Bags Clearance are pursued by many famous characters.
    Coach Bags Outlet in different styles and different colors are in different leathers.
    Next time, I will share some knowledge about how to maintain the bags in different material.