Monday, 28 November 2011

Calling your own AppEngine Service methods

To test the operation of this I'm going to take a leaf out of the Task example and implement a Create button on the GWT front-end of the server, to make sure everything is wired up and working.

Add a new button to the web-page com.yrdomain.yrproject.client.YrprojectWidget.ui.xml

 <g:Button ui:field="createButton">Create</g:Button>
 
Open file com.yrdomain.yrproject.client.YrprojectWidget.java

Add the UI element:

@UiField
Button createButton;
 
And in the constructor, fire off a createGift() request.

createButton.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
            createButton.setEnabled(false);
            MygiftwishlistRequest mygwlRequest = requestFactory.mygiftwishlistRequest();
            mygwlRequest.createGift().fire(new Receiver<GiftProxy>() {
                @Override
                public void onFailure(ServerFailure error) {
                    createButton.setEnabled(true);
                    setStatus(error.getMessage(), true);
                }
                @Override
                public void onSuccess(GiftProxy response) {
                    createButton.setEnabled(true);
                    setStatus(response.getGiftLocation(), false);
                  }
                
            });
        }
    });
 
The RPC wizard automatically took the Gift.java Entity and created a GiftProxy, which it used in YrprojectRequest.java and added an entry for it in the MyRequestFactory.java (both in the shared folder).
Update the createGift() method to make it return something interesting - ok, just a variation on the HelloWorldService:

@ServiceMethod
    public Gift createGift() {
        
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        String message;
        if (user == null) {
          message = "No one is logged in!\nSent from App Engine at " + new Date();
        } else {
          message = "Howdie, " + user.getEmail() + 
"!\nSent from createGift on the App Engine at " + 
new Date();
        }
       
        Gift porsche = new Gift();
        porsche.setGiftName("sports car");
        porsche.setGiftLocation(message);
        
        return porsche;
    }
 
When we run the project, we see that when we press the Create button on the web-page, it calls the createGift() function on YrprojectService.java as expected.

Now we need to properly create Gifts and store them against the name of the user in the database.

No comments:

Post a Comment