GWT_speakernoted_2 by azden70

VIEWS: 1 PAGES: 74

More Info
									10/07/2006




                  Google Web Toolkit
                  (GWT) Basics

                    Sang Shin
                    Java Technology Architect & Evangelist
                    Sun Microsystems, Inc.
                    sang.shin@sun.com
                    www.javapassion.com




             Welcome to Google Web Toolkit presentation.
10/07/2006




             Disclaimer & Acknowledgments
             • Even though Sang Shin is a full-time employee of
               Sun Microsystems, the contents here are created as
               his own personal endeavor and thus does not
               necessarily reflect any official stance of Sun
               Microsystems on any particular technology
             • Most of the slides in this presentations are created
               from the contents from Google Web Toolkit (GWT)
               website
               > http://code.google.com/webtoolkit/


                                                      Source: http://code.google.com/webtoolkit/   2
10/07/2006




              Agenda
               • What is & Why GWT?
               • Building User interface
                  > GWT Widgets
                  > Event Handling
                  > Styling
               • Remote Procedural Call (RPC)
                  > Steps for building GWT RPC application
                  > Serializable types
                  > Handling exceptions


                                                             Source: http://code.google.com/webtoolkit/   3

         This is what we are going to learn in this presentation. First, we
           will learn what GWT is and why and when you want to use GWT
           for building AJAX applications.

         We will then learn how to use built-in widgets that come with the
          GWT package. We will learn how to create and register event
          handlers to widgets. We will also learn how CSS styles can be
          attached to widgets.

         The next topic is how to perform Remore procedure call between
           the client and server. We will start with step by step guideline
           on how to do it. We will briefly touches upon how parameter
           and return data types are serialized. We will also learn how to
           do handle exceptions that might occur when RPC operation is
           being performed.
10/07/2006




                Agenda
                 • JavaScript Native Interface (JSNI)
                    > Motivation for JSNI
                    > Accessing native JavaScript code from Java code
                    > Accessing Java methods and fields from native JavaScript
                       code
                 • GWT Project
                    > GWT Module configuration
                    > Deployment




                                                                      Source: http://code.google.com/webtoolkit/   4
         We will talk about JavaScript Native Interface which is called JSNI. First, we will
         learn when you want to use JSNI. Then we will learn how you can access native
         JavaScript code from Java code and vice versa.
         Lastly we will learn the GWT project related information including module
         configuration and deployment.
10/07/2006




             What is and
             Why GWT?
10/07/2006




                What is GWT?
                • Java software development framework that makes
                  writing AJAX applications easy
                • Let you develop and debug AJAX applications in the
                  Java language using the Java development tools of
                  your choice
                   > NetBeans or Eclipse
                • Provides Java-to-JavaScript compiler and a special
                  web browser that helps you debug your GWT
                  applications
                   > When you deploy your application to production, the compiler
                      translates your Java application to browser-compliant
                      JavaScript and HTML                           Source: http://code.google.com/webtoolkit/   6
         You can think of GWT as Java software development framework for building AJAX
         application. In other words, it lets you develop and debug AJAX applications in the
         Java development environment. You can use your favorite development tool such
         as NetBeans or Eclipse to develop the application. When you are done with the
         testing and debugging, you can deploy the application. During the deployment
         phase, the GWT compiler compiles the Java code into JavaScript and HTML.
10/07/2006




                Two Modes of Running GWT App
                • Hosted mode
                   > Your application is run as Java bytecode within the Java
                     Virtual Machine (JVM)
                   > You will typically spend most of your development time in
                     hosted mode because running in the JVM means you can
                     take advantage of Java's debugging facilities
                • Web mode
                   > Your application is run as pure JavaScript and HTML,
                     compiled from your original Java source code with the GWT
                     Java-to-JavaScript compiler
                   > When you deploy your GWT applications to production, you
                     deploy this JavaScript and HTML to your web servers, so end
                     users will only see the web mode version of your application
                                                                   Source: http://code.google.com/webtoolkit/   7
         GWT applications can be run in two modes:
            * Hosted mode - In hosted mode, your application is run as Java bytecode within
         the Java Virtual Machine (JVM). You will typically spend most of your development
         time in hosted mode because running in the JVM means you can take advantage of
         Java's debugging facilities and remain within an IDE like Eclipse.
            * Web mode - In web mode, your application is run as pure JavaScript and HTML,
         compiled from your original Java source code with the GWT Java-to-JavaScript
         compiler. When you deploy your GWT applications to production, you deploy this
         JavaScript and HTML to your web servers, so end users will only see the web mode
         version of your application.
         To support hosted mode, GWT ships with a special web browser with hooks into
         the JVM. See the GWT architecture diagram below for more information.
10/07/2006




                Why Use Java Programming
                Language for AJAX Development?
               • Static type checking in the Java language boosts
                 productivity while reducing errors.
               • Common JavaScript errors (typos, type mismatches)
                 are easily caught at compile time rather than by users at
                 runtime.
               • Code prompting/completion is widely available
               • Automated Java refactoring is pretty snazzy these days.
               • Java-based OO designs are easier to communicate and
                 understand, thus making your AJAX code base more
                 comprehensible with less documentation.
                                                                   Source: http://code.google.com/webtoolkit/   8
         Java technologies offer a productive development plaform, and with GWT, they can
         instantly become the basis of your AJAX development platform as well. Here are
         some of the benefits of developing with GWT:
           * You can use all of your favorite Java development tools (Eclipse, IntelliJ,
         JProfiler, JUnit) for AJAX development.
           * Static type checking in the Java language boosts productivity while reducing
         errors.
           * Common JavaScript errors (typos, type mismatches) are easily caught at
         compile time rather than by users at runtime.
           * Code prompting/completion is widely available.
           * Automated Java refactoring is pretty snazzy these days.
           * Java-based OO designs are easier to communicate and understand, thus
         making your AJAX code base more comprehensible with less documentation.
10/07/2006




             Why GWT?
             • No need to learn/use JavaScript language
               > Leverage Java programming knowledge you already have
             • No need to handle browser incompatibilities and quirks
               > GWT handles them for you
             • No need to learn/use DOM APIs
               > Use Java APIs
             • No need to handle forward/backward buttons
               browser-history
               > GWT handles it for you
             • No need to build commonly used Widgets
               > Most of them come with GWT
                                                       Source: http://code.google.com/webtoolkit/   9
         .
10/07/2006




             Why GWT?
             • Leverage various tools of Java programming language
               for writing/debugging/testing
               > For example, NetBeans or Eclipse
             • JUnit integration
               > GWT's direct integration with JUnit lets you unit test both in a
                  debugger and in a browser and you can even unit test
                  asynchronous RPCs
             • Internationalization
                > GWT includes a flexible set of tools to help you
                  internationalize your applications and libraries
                > GWT internationalization support provides a variety of
                  techniques to internationalize strings, typed values, and
                  classes
                                                              Source: http://code.google.com/webtoolkit/   10
         .
10/07/2006




             GWT Architecture
10/07/2006




              GWT Architecture




                                                                 Source: http://code.google.com/webtoolkit/   12
         GWT has four major components: a Java-to-JavaScript compiler, a "hosted" web
         browser, and two Java class libraries:
10/07/2006




                 GWT Architectural Components
                 • GWT Java-to-JavaScript Compiler
                   > translates the Java programming language to the
                     JavaScript programming language
                 • GWT Hosted Web Browser
                   > lets you run and execute your GWT applications in
                     hosted mode, where your code runs as Java in the
                     Java Virtual Machine without compiling to JavaScript
                 • JRE emulation library
                   > GWT contains JavaScript implementations of the
                     most widely used classes in the Java standard class
                     library
                 • GWT Web UI class library                               13
                                                                     Source: http://code.google.com/webtoolkit/



         The components, from bottom to top, are:
             *
              GWT Java-to-JavaScript Compiler
              The GWT Java-to-JavaScript compiler translates the Java programming
         language to the JavaScript programming language. You use the GWT compiler to
         run your GWT applications in web mode.
            *
              GWT Hosted Web Browser
              The GWT Hosted Web Browser lets you run and execute your GWT applications
         in hosted mode, where your code runs as Java in the Java Virtual Machine without
         compiling to JavaScript. To accomplish this, the GWT browser embeds a special
         browser control (an Internet Explorer control on Windows or a Gecko/Mozilla
         control on Linux) with hooks into the JVM.
            *
              JRE emulation library
              GWT contains JavaScript implementations of the most widely used classes in
         the Java standard class library, including most of the java.lang package classes
         and a subset of the java.util package classes. The rest of the Java standard library
         isn't supported natively within GWT. For example, packages like java.io don't apply
         to web applications since they access the network and local file system.
            *
              GWT Web UI class library
              The GWT web UI class library is a set of custom interfaces and classes that let
         your create web browser "widgets," like buttons, text boxes, images, and text. This
         is the core user interface library used to create GWT applications. GWT ships with
         the complete source code for the library under an open source license.
10/07/2006




             Building User Interface:
             Built-in GWT Widgets
10/07/2006




                GWT User Interface Classes
                • Similar to those in existing UI frameworks such as
                  Swing except that the widgets are rendered using
                  dynamically-created HTML rather than pixel-oriented
                  graphics
                • While it is possible to manipulate the browser's DOM
                  directly using the DOM interface, it is far easier to
                  use Java classes from the Widget hierarchy
                • Using widgets makes it much easier to quickly build
                  interfaces that will work correctly on all browsers

                                                                    Source: http://code.google.com/webtoolkit/   15
         GWT user interface classes are similar to those in existing UI frameworks such as
         Swing and SWT except that the widgets are rendered using dynamically-created
         HTML rather than pixel-oriented graphics.
         While it is possible to manipulate the browser's DOM directly using the DOM
         interface, it is far easier to use classes from the Widget hierarchy. You should
         rarely, if ever, need to access the DOM directly. Using widgets makes it much easier
         to quickly build interfaces that will work correctly on all browsers.
10/07/2006




              GWT Widget Gallery




                                           Source: http://code.google.com/webtoolkit/   16
         GWT comes with lots of widgets.
10/07/2006




             Building User Interface:
             Custom Composite
             Widget
10/07/2006




                Custom Composite Widget
                • Composite widget is a specialized widget that can
                  contain another component (typically, a panel)
                   > You can easily combine groups of existing widgets into a
                      composite widget that is itself a reusable widget
                • The most effective way to create new widgets




                                                                    Source: http://code.google.com/webtoolkit/   18
          Composites are by far the most effective way to create new widgets. You can easily
         combine groups of existing widgets into a composite that is itself a reusable
         widget. Composite is a specialized widget that can contain another component
         (typically, a panel) but behaves as if it were its contained widget. Using Composite
         is preferable to attempting to create complex widgets by subclassing Panel
         because a composite usually wants to control which methods are publicly
         accessible without exposing those methods that it would inherit from its panel
         superclass
10/07/2006




             Example: Composite Widget
              public static class OptionalTextBox extends Composite implements
                  ClickListener {
               private TextBox textBox = new TextBox();
               private CheckBox checkBox = new CheckBox();
               /**
                * Constructs an OptionalTextBox with the given caption on the check.
                *
                * @param caption the caption to be displayed with the check box
                */
               public OptionalTextBox(String caption) {
                   // Place the check above the text box using a vertical panel.
                   VerticalPanel panel = new VerticalPanel();
                   panel.add(checkBox);
                   panel.add(textBox);
                  // Set the check box's caption, and check it by default.
                  checkBox.setText(caption);
                  checkBox.setChecked(true);
                  checkBox.addClickListener(this);
                                                                             Source: http://code.google.com/webtoolkit/   19
                  // All composites must call initWidget() in their constructors.
         .
10/07/2006




             Building User Interface:
             Event Handling
10/07/2006




                Events and Listeners
                • Events in GWT use the "listener interface" model
                  similar to other user interface frameworks (like
                  Swing)
                   > A listener interface defines one or more methods that the
                     widget calls to announce an event
                   > A class wishing to receive events of a particular type
                     implements the associated listener interface - called Event
                     Listener - and then passes a reference to itself to the widget
                     to "subscribe" to a set of events




                                                                     Source: http://code.google.com/webtoolkit/   21
         Events in GWT use the "listener interface" model similar to other user interface
         frameworks. A listener interface defines one or more methods that the widget calls
         to announce an event. A class wishing to receive events of a particular type
         implements the associated listener interface and then passes a reference to itself to
         the widget to "subscribe" to a set of events.
10/07/2006




             Example: Event Listener
             public class ListenerExample extends Composite implements ClickListener {
              private FlowPanel fp = new FlowPanel();
              private Button b1 = new Button("Button 1");
              private Button b2 = new Button("Button 2");
                 public ListenerExample() {
                   setWidget(fp);
                   fp.add(b1);
                   fp.add(b2);
                   b1.addClickListener(this);
                   b2.addClickListener(this);
                 }
                 // Event listener method from the ClickListener interface
                 public void onClick(Widget sender) {
                   if (sender == b1) {
                     // handle b1 being clicked
                   } else if (sender == b2) {
                     // handle b2 being clicked
                   }
                 }
             }                                                               Source: http://code.google.com/webtoolkit/   22
         .
10/07/2006




             Building User Interface:
             Styling through CSS
10/07/2006




             Steps To Follow
             1.Create CSS file (which contains styles)
               > KitchenSink.css
             2.Specify the CSS file in the module configuration file
             3.Use the styles in the Java code




                                                     Source: http://code.google.com/webtoolkit/   24
         .
10/07/2006




             Step 1: Create a CSS file
             Example: KitchenSink.css
             .ks-List .ks-SinkItem {
               width: 100%;
               padding: 0.3em;
               padding-right: 16px;
               cursor: pointer;
               cursor: hand;
             }
             .ks-List .ks-SinkItem-selected {
               background-color: #C3D9FF;
             }
             .ks-images-Image {
               margin: 8px;
             }
             .ks-images-Button {
               margin: 8px;
               cursor: pointer;
               cursor: hand;                    Source: http://code.google.com/webtoolkit/   25
             }
         .
10/07/2006




             Step 2: Specify the CSS file in the Module
             Configuration File: KitchenSink.gwt.xml
             <module>
             <inherits name='com.google.gwt.user.User'/>
             <entry-point
                class='com.google.gwt.sample.kitchensink.client.KitchenSink'/>
             <stylesheet src='KitchenSink.css'/>
             </module>




                                                                   Source: http://code.google.com/webtoolkit/   26
         .
10/07/2006




             Step 3: Add/Remove Styles to Widgets in the
             Java Code: SinkList.java
             public void setSinkSelection(String name) {
              if (selectedSink != -1)
                list.getWidget(selectedSink).removeStyleName("ks-SinkItem-selected");
                 for (int i = 0; i < sinks.size(); ++i) {
                   SinkInfo info = (SinkInfo) sinks.get(i);
                   if (info.getName().equals(name)) {
                     selectedSink = i;
                     list.getWidget(selectedSink).addStyleName("ks-SinkItem-selected");
                     return;
                   }
                 }
             }




                                                                               Source: http://code.google.com/webtoolkit/   27
         .
10/07/2006




             Adding/Removing Styles
             • Style can be added to or removed from widgets via
               > <Widget>.addStyleName(“<name-of-style>”);
               > <Widget>.removeStyleName(“<name-of-style>”);
             • Multiple styles can be added to a widget




                                                       Source: http://code.google.com/webtoolkit/   28
         .
10/07/2006




             Remore Procedure Call
             (RPC)
10/07/2006




             What is and Why GWT RPC?
             • Mechanism for interacting with the server by
               invoking a method
               > Example: Use for fetching data from the server
             • Makes it easy for the client and server to pass Java
               objects back and forth over HTTP
               > Marshaling and unmarshaling of Java objects are handled by
                 the GWT
             • When used properly, RPCs give you the opportunity
               to move all of your UI logic to the client (leaving
               business logic on the server)
               > Could result in greatly improved performance, reduced
                 bandwidth, reduced web server load, and a pleasantly fluid
                 user experience                                            30
                                                           Source: http://code.google.com/webtoolkit/



         .
10/07/2006




                GWT RPC Plumbing Architecture




                                                                    Source: http://code.google.com/webtoolkit/   31
         This section outlines the moving parts required to invoke a service. Each service
         has a small family of helper interfaces and classes. Some of these classes, such as
         the service proxy, are automatically generated behind the scenes and you generally
         will never realize they exist. The pattern for helper classes is identical for every
         service that you implement, so it is a good idea to spend a few moments to
         familiarize yourself with the terminology and purpose of each layer in server call
         processing. If you are familiar with traditional remote procedure call (RPC)
         mechanisms, you will recognize most of this terminology already
10/07/2006




             Remore Procedure Call
             (RPC)
             Sub-topic: Steps for
             Implementing GWT RPC
10/07/2006




             Steps for Implementing GWT RPC
             1.Write two service interface's (client & server)
               > Synchronous interface
               > Asynchronous interface - has to pass async. callback object
             2.Implement the service at the server side
               > Service class implements Service interface and extends
                 RemoteServiceServlet class
             3.Configure the service in the module configuration file
               > Needed for running the app in hosted mode
             4.Make a call from the client

                                                           Source: http://code.google.com/webtoolkit/   33
         .
10/07/2006




                1. Write Two Service Interface Files
                • Synchronous interface
                   public interface MyHelloService extends RemoteService {
                     public String sayHello(String s);
                   }

                • Asynchronous interface
                   // Has to be named as <Synchronous-interface>Async.
                   // Has to pass AsyncCallback object as the last parameter.
                   // The return type is always void.
                   interface MyHelloServiceAsync {
                     public void sayHello(String s, AsyncCallback callback);
                   }


                                                                                Source: http://code.google.com/webtoolkit/   34
         To develop a new service interface, begin by creating a client-side Java interface
         that extends the RemoteService tag interface.
          Before you can actually attempt to make a remote call from the client, you must
         create another interface, an asynchronous one, based on your original service
         interface.
          The nature of asynchronous method calls requires the caller to pass in a callback
         object that can be notified when an asynchronous call completes, since by
         definition the caller cannot be blocked until the call completes. For the same
         reason, asynchronous methods do not have return types; they must always return
         void. After an asynchronous call is made, all communication back to the caller is via
         the passed-in callback object.
         The relationship between a service interface and its asynchronous counterpart is
         straightforward:
            * If a service interface is called com.example.cal.client.SpellingService, then the
         asynchronous interface must be called
         com.example.cal.client.SpellingServiceAsync. The asynchronous interface must be
         in the same package and have the same name, but with the suffix Async.
10/07/2006




                2. Implement the Service
                • Extends RemoteServiceServlet and implements the
                  service interface
                   public class MyHelloServiceImpl extends RemoteServiceServlet
                                                  implements MyHelloService {

                       // Provide implementation logic.
                       public String sayHello(String s) {
                          return "Hello, " + s + "!";
                       }
                   }




                                                                     Source: http://code.google.com/webtoolkit/   35
         Every service ultimately needs to perform some processing to order to respond to
         client requests. Such server-side processing occurs in the service implementation,
         which is based on the well-known servlet architecture.
         A service implementation must extend RemoteServiceServlet and must implement
         the associated service interface. Note that the service implementation does not
         implement the asynchronous version of the service interface.
         Every service implementation is ultimately a servlet, but rather than extending
         HttpServlet, it extends RemoteServiceServlet instead. RemoteServiceServlet
         automatically handles serialization and invoking the intended method in your
         service implementation.
10/07/2006




                3. Configure the Service in the
                Module Configuration File
                <module>
                 <inherits name="com.google.gwt.user.User"/>
                 <entry-point class="com.google.gwt.sample.hello.client.Hello"/>
                 <servlet path='/hellorpc'
                  class='com.google.gwt.sample.hello.server.MyHelloServiceImpl'/>
                </module>




                                                                        Source: http://code.google.com/webtoolkit/   36
         To automatically load your service implementation, use the <servlet> tag within
         your module XML. The GWT development shell includes an embedded version of
         Tomcat which acts as a development-time servlet container for testing
10/07/2006




                4. Make a call from Client
                a)Instantiate an client proxy (an object of the type of
                  asynch. service interface) using GWT.create()
                b)Specify a service entry point URL for the service
                  proxy using ServiceDefTarget
                c)Create an asynchronous callback object to be
                  notified when the RPC has completed
                d)Make the call from the client



                                                                    Source: http://code.google.com/webtoolkit/   37
         The process of making an RPC from the client always involves the exact same
         steps.
          1. Instantiate the service interface using GWT.create().
          2. Specify a service entry point URL for the service proxy using ServiceDefTarget.
          3. Create an asynchronous callback object to be notified when the RPC has
         completed.
          4. Make the call.
10/07/2006




             a. Instantiate Service Interface
             using GWT.create()
             public void menuCommandEmptyInbox() {
              // (a) Create the client proxy. Note that although you are creating the
              // object instance of the service interface type, you cast the result to the asynchronous
              // version of the interface. The cast is always safe because the generated proxy
              // implements the asynchronous interface automatically.
              //
              MyEmailServiceAsync emailService =
                                  (MyEmailServiceAsync) GWT.create(MyEmailService.class);




                                                                             Source: http://code.google.com/webtoolkit/   38
         .
10/07/2006




             b. Specify a service entry point URL for the
             service proxy using ServiceDefTarget
             public void menuCommandEmptyInbox() {
              // (a) Create the client proxy. Note that although you are creating the
              // service interface proper, you cast the result to the asynchronous
              // version of the interface. The cast is always safe because the generated proxy
              // implements the asynchronous interface automatically.
              //
              MyEmailServiceAsync emailService =
                                  (MyEmailServiceAsync) GWT.create(MyEmailService.class);
              // (b) Specify the URL at which our service implementation is running.
              // Note that the target URL must reside on the same domain and port from
              // which the host page was served.
              //
              ServiceDefTarget endpoint = (ServiceDefTarget) emailService;
              String moduleRelativeURL = GWT.getModuleBaseURL() + "email";
              endpoint.setServiceEntryPoint(moduleRelativeURL);


                                                                            Source: http://code.google.com/webtoolkit/   39
         .
10/07/2006




             c. Create an asynchronous callback object to
             be notified when the RPC has completed
             public void menuCommandEmptyInbox() {
              ...
              // (c) Create an asynchronous callback to handle the result.
              //
              AsyncCallback callback = new AsyncCallback() {
                public void onSuccess(Object result) {
                  // do some UI stuff to show success
                }
                public void onFailure(Throwable caught) {
                  // do some UI stuff to show failure
                }
              };




                                                                             Source: http://code.google.com/webtoolkit/   40
         .
10/07/2006




             d. Make the Call
             public void menuCommandEmptyInbox() {
                 ...
                 // (d) Make the call. Control flow will continue immediately and later
                 // 'callback' will be invoked when the RPC completes.
                 //
                 emailService.emptyMyInbox(fUsername, fPassword, callback);
             }




                                                                                 Source: http://code.google.com/webtoolkit/   41
         .
10/07/2006




             Remore Procedure Call
             (RPC)
             Sub-topic:
             Serializable Types
10/07/2006




                Serializable Types
                 • Method parameters and return types must be
                   serializable
                 • Java data types that are already serializable
                    > primitives, such as char, byte, short, int, long, boolean, float,
                        or double
                    >   String, Date, or wrapper types such as Character, Byte, Short,
                        Integer, Long, Boolean, Float, or Double
                    >   An array of serializable types (including other serializable
                        arrays)
                    >   A serializable user-defined class
                    >   A class has at least one serializable subclass

                                                                        Source: http://code.google.com/webtoolkit/   43
         Method parameters and return types must be serializable, which means they must
         conform to certain restrictions. GWT tries really hard to make serialization as
         painless as possible, so while the rules regarding serialization are subtle, in
         practice the behavior becomes intuitive very quickly.

         A type is serializable and can be used in a service interface if it
           * is primitive, such as char, byte, short, int, long, boolean, float, or double;
           * is String, Date, or a primitive wrapper such as Character, Byte, Short, Integer,
         Long, Boolean, Float, or Double;
           * is an array of serializable types (including other serializable arrays);
           * is a serializable user-defined class; or
           * has at least one serializable subclass
10/07/2006




                    Serializable User-defined Classes
                    • A user-defined class is serializable if
                       > it is assignable to IsSerializable, either because it directly
                         implements the interface or because it derives from a
                         superclass that does, and
                       > all non-transient fields are themselves serializable.




                                                                        Source: http://code.google.com/webtoolkit/   44
             A user-defined class is serializable if
           1. it is assignable to IsSerializable, either because it directly implements the
         interface or because it derives from a superclass that does, and
           2. all non-transient fields are themselves serializable.

         The transient keyword is honored, so values in transient fields are not exchanged
         during RPCs. Fields that are declared final are also not exchanged during RPCs, so
         they should generally be marked transient as well.
10/07/2006




             Remore Procedure Call
             (RPC)
             Sub-topic:
             Handling Exceptions
10/07/2006




                Handling Exceptions
                • Making RPCs opens up the possibility of a variety of
                  errors
                   > Networks fail, servers crash, and problems occur while
                      processing a server call
                • GWT lets you handle these conditions in terms of
                  Java exceptions
                • RPC-related exceptions
                   > Checked exceptions
                   > Unexpected exceptions



                                                                     Source: http://code.google.com/webtoolkit/   46
         Making RPCs opens up the possibility of a variety of errors. Networks fail, servers
         crash, and problems occur while processing a server call. GWT lets you handle
         these conditions in terms of Java exceptions. RPC-related exceptions fall into two
         categories.
10/07/2006




                Checked Exceptions
                • Service interface methods support throws
                  declarations to indicate which exceptions may be
                  thrown back to the client from a service
                  implementation
                • Callers should implement AsyncCallback.onFailure
                  (Throwable) to check for any exceptions specified in
                  the service interface




                                                                   Source: http://code.google.com/webtoolkit/   47
         Service interface methods support throws declarations to indicate which
         exceptions may be thrown back to the client from a service implementation. Callers
         should implement AsyncCallback.onFailure(Throwable) to check for any exceptions
         specified in the service interface.
10/07/2006




                Unchecked Exceptions
                • An RPC may not reach the service implementation
                  at all. This can happen for many reasons:
                   > the network may be disconnected
                   > a DNS server might not be available
                   > the HTTP server might not be listening
                • In this case, an InvocationException is passed to
                  your implementation of AsyncCallback.onFailure
                  (Throwable)



                                                                    Source: http://code.google.com/webtoolkit/   48
          An RPC may not reach the service implementation at all. This can happen for many
         reasons: the network may be disconnected, a DNS server might not be available,
         the HTTP server might not be listening, and so on. In this case, an
         InvocationException is passed to your implementation of AsyncCallback.onFailure
         (Throwable). The class is called InvocationException because the problem was with
         the invocation attempt itself rather than with the service implementation itself.
         An RPC can also fail with an invocation exception if the call does reach the server,
         but an undeclared exception occurs during normal processing of the call. There are
         many reasons such a situation could arise: a necessary server resource, such as a
         database, might be unavailable, a NullPointerException could be thrown due to a
         bug in the service implementation, and so on. In these cases, a
         InvocationException is thrown in application code.
10/07/2006




             JavaScript Native
             Interface (JSNI)
10/07/2006




                Why JSNI?
                • Sometimes it's very useful to mix handwritten
                  JavaScript into your Java source code
                   > For example, the lowest-level functionality of certain core
                     GWT
                • Leverage various existing JavaScript toolkits
                   > Dojo toolkits, Prototype, Rico, etc.
                • Should be used sparingly
                   > JSNI code is less portable across browsers, more likely to
                     leak memory, less amenable to Java tools, and hard for the
                     compiler to optimize
                • Web equivalent of inline assembly code
                                                                   Source: http://code.google.com/webtoolkit/   50

         The GWT compiler translates Java source into JavaScript. Sometimes it's very
         useful to mix handwritten JavaScript into your Java source code. For example, the
         lowest-level functionality of certain core GWT classes are handwritten in
         JavaScript. GWT borrows from the Java Native Interface (JNI) concept to implement
         JavaScript Native Interface (JSNI).
         Writing JSNI methods is a powerful technique, but should be used sparingly. JSNI
         code is less portable across browsers, more likely to leak memory, less amenable
         to Java tools, and hard for the compiler to optimize.
10/07/2006




                   What Can You Do with JSNI?
                   • Implement a Java method directly in JavaScript
                   • Wrap type-safe Java method signatures around
                     existing JavaScript
                   • Call from JavaScript into Java code and vice-versa
                   • Throw exceptions across Java/JavaScript
                     boundaries
                   • Read and write Java fields from JavaScript
                   • Use hosted mode to debug both Java source (with a
                     Java debugger) and JavaScript (with a script
                     debugger, only in Windows right now)
                                                                      Source: http://code.google.com/webtoolkit/   51
             We think of JSNI as the web equivalent of inline assembly code. You can:
           * Implement a Java method directly in JavaScript
           * Wrap type-safe Java method signatures around existing JavaScript
           * Call from JavaScript into Java code and vice-versa
           * Throw exceptions across Java/JavaScript boundaries
           * Read and write Java fields from JavaScript
           * Use hosted mode to debug both Java source (with a Java debugger) and
         JavaScript (with a script debugger, only in Windows right now)
10/07/2006




             JavaScript Native
             Interface (JSNI):
             Accessing Native
             JavaScript Methods
             from Java Code
10/07/2006




                How to add JavaScript Code via
                JSNI?
                • When accessing the browser's window and
                  document objects from JSNI, you must reference
                  them as $wnd and $doc, respectively
                   > Your compiled script runs in a nested frame, and $wnd and
                     $doc are automatically initialized to correctly refer to the host
                     page's window and document




                                                                    Source: http://code.google.com/webtoolkit/   53
         When accessing the browser's window and document objects from JSNI, you must
         reference them as $wnd and $doc, respectively. Your compiled script runs in a
         nested frame, and $wnd and $doc are automatically initialized to correctly refer to
         the host page's window and document.
10/07/2006




                Writing Native JavaScript Methods
                • JSNI methods are declared native and contain
                  JavaScript code in a specially formatted comment
                  block between the end of the parameter list and the
                  trailing semicolon
                   > /*-{ <JavaScript code }-*/
                • JSNI methods are be called just like any normal
                  Java method
                • They can be static or instance methods



                                                                    Source: http://code.google.com/webtoolkit/   54
         JSNI methods are declared native and contain JavaScript code in a specially
         formatted comment block between the end of the parameter list and the trailing
         semicolon. A JSNI comment block begins with the exact token /*-{ and ends with
         the exact token }-*/. JSNI methods are be called just like any normal Java method.
         They can be static or instance methods.
10/07/2006




             Example: Native JavaScript Methods


              public static native void alert(String msg) /*-{
                $wnd.alert(msg);
              }-*/;




                                                                 Source: http://code.google.com/webtoolkit/   55
         .
10/07/2006




             JavaScript Native
             Interface (JSNI):
             Accessing Java Methods
             & Fields from JavaScript
10/07/2006




                Invoking Java methods from JavaScript
               • Calling Java methods from JavaScript is somewhat
                 similar to calling Java methods from C code in JNI.
                 In particular, JSNI borrows the JNI mangled method
                 signature approach to distinguish among overloaded
                 methods.
               • [instance-expr.]@class-name::method-name(param-
                 signature)(arguments)




                                                                  Source: http://code.google.com/webtoolkit/   57
          Calling Java methods from JavaScript is somewhat similar to calling Java methods
         from C code in JNI. In particular, JSNI borrows the JNI mangled method signature
         approach to distinguish among overloaded methods.
10/07/2006




                Accessing Java Fields from JavaScript
               • Static and instance fields can be accessed from
                 handwritten JavaScript
               • [instance-expr.]@class-name::field-name




                                                                    Source: http://code.google.com/webtoolkit/   58
          Static and instance fields can be accessed from handwritten JavaScript. Field
         references are of the form
         [instance-expr.]@class-name::field-name
10/07/2006




             Example: Native JavaScript Methods


              public static native void alert(String msg) /*-{
                $wnd.alert(msg);
              }-*/;




                                                                 Source: http://code.google.com/webtoolkit/   59
         .
10/07/2006




             GWT Module
             Configuration
10/07/2006




             Configuration Settings of a GWT
             Project (defined in *.gwt.xml file)
             • Inherited modules
             • An entry point class name; these are optional,
               although any module referred to in HTML must have
               at least one entry-point class specified
             • Source path entries
             • Public path entries
             • Deferred binding rules, including property providers
               and class generators

                                                    Source: http://code.google.com/webtoolkit/   61
         .
10/07/2006




             Module XML ( *.gwt.xml) File Format
             • Modules are defined in XML files whose file
               extension is .gwt.xml
             • Module XML files should reside in the project's root
               package




                                                    Source: http://code.google.com/webtoolkit/   62
         .
10/07/2006




             Entry-Point Classes
             • A module entry-point is any class that is assignable
               to EntryPoint and that can be constructed without
               parameters
             • When a module is loaded, every entry point class is
               instantiated and its EntryPoint.onModuleLoad()
               method gets called




                                                    Source: http://code.google.com/webtoolkit/   63
         .
10/07/2006




             Example: Entry-Point class of GWTHello




                                          Source: http://code.google.com/webtoolkit/   64
         .
10/07/2006




             Source Path
             • Modules can specify which subpackages contain
               translatable source, causing the named package and its
               subpackages to be added to the source path
                > Only files found on the source path are candidates to be
                   translated into JavaScript, making it possible to mix client-side
                   and server-side code together in the same classpath without
                   conflict
             • When module inherit other modules, their source paths are
               combined so that each module will have access to the
               translatable source it requires
             • If no <source> element is defined in a module XML file, the
               client subpackage is implicitly added to the source path as if
               <source path="client"> had been found in the XML
                                                               Source: http://code.google.com/webtoolkit/   65
         .
10/07/2006




             Public Path
             • Modules can specify which subpackages are public, causing
               the named package and its subpackages to be added to the
               public path
             • When you compile your application into JavaScript, all the
               files that can be found on your public path are copied to the
               module's output directory
                > The net effect is that user-visible URLs need not include a full
                   package name.
             • When module inherit other modules, their public paths are
               combined so that each module will have access to the static
               resources it expects.

                                                              Source: http://code.google.com/webtoolkit/   66
         .
10/07/2006




             Servlet Path
             • For convenient RPC testing, this element loads a servlet
               class mounted at the specified URL path
             • The URL path should be absolute and have the form of a
               directory (for example, /spellcheck)
                > Your client code then specifies this URL mapping in a call
                  to ServiceDefTarget.setServiceEntryPoint(String)
             • Any number of servlets may be loaded in this manner,
               including those from inherited modules.




                                                          Source: http://code.google.com/webtoolkit/   67
         .
10/07/2006




             Example: Servlet Path




                                     Source: http://code.google.com/webtoolkit/   68
         .
10/07/2006




             GWT Project Structure
10/07/2006




             Standard GWT Project Layout
             • GWT projects are overlaid onto Java packages such
               that most of the configuration can be inferred from the
               classpath and your module definitions (*.gwt.xml files)
             • Standard GWT Project layout
               > com/example/cal/ - The project root package contains module
                 XML files
               > com/example/cal/client/ - Client-side source files and
                 subpackages
               > com/example/cal/server/ - Server-side code and subpackages
               > com/example/cal/public/ - Static resources that can be served
                 publicly

                                                          Source: http://code.google.com/webtoolkit/   70
         .
10/07/2006




             Example: Calendar GWT Application
             (Root directory)
             • com/example/cal/Calendar.gwt.xml
               > A common base module for your project that inherits
                 com.google.gwt.user.User module
             • com/example/cal/CalendarApp.gwt.xml
               > Inherits the com.example.cal.Calendar module (above) and
                 adds an entry point class
             • com/example/cal/CalendarTest.gwt.xml
               > A module defined by your project



                                                           Source: http://code.google.com/webtoolkit/   71
         .
10/07/2006




             Example: Calendar GWT Application
             (client and server directories)

             • com/example/cal/client/CalendarApp.java
               > Client-side Java source for the entry-point class
             • com/example/cal/client/spelling/SpellingService.java
               > An RPC service interface defined in a subpackage
             • com/example/cal/server/spelling/SpellingServiceImpl.j
               ava
               > Server-side Java source that implements the logic of the
                 spelling service


                                                             Source: http://code.google.com/webtoolkit/   72
         .
10/07/2006




             Example: Calendar GWT Application
             (public directory)
             • com/example/cal/public/Calendar.html
               > An HTML page that loads the calendar app
             • com/example/cal/public/Calendar.css
               > A stylesheet that styles the calendar app
             • com/example/cal/public/images/logo.gif
               > A logo




                                                             Source: http://code.google.com/webtoolkit/   73
         .
10/07/2006




             Google Web Toolkit
             (GWT) Basics

             Sang Shin
             Java Technology Architect
             Sun Microsystems, Inc.
             sang.shin@sun.com
             www.javapassion.com

								
To top