RSS

Category Archives: GWT/ JSNI / COMPILER

GWT Compiler – Compiling for one browser and also supporting hosted mode

When you want to compile your GWT module for only specific browser, you can change  UserAgent.gwt.xml inside gwt-user.jar in package com.google.gwt.user.

Find this text and change it as you wish:
<define-property name=”user.agent” values=”ie6,gecko,gecko1_8,safari,opera”>

gecko – Mozilla ,gecko1_8  –  FireFox


I want to compile for only IE , then I change it into

<define-property name=”user.agent” values=”ie6″>

I want to do this because we limit specification of browser for our application, and by doing this we can get more space up to 40%

GWT spends time to compute permutations : create javascript file per browser/locale. With this kind of application, GWT produces 50 permutations :

  • 5 browsers : ie6, opera, gecko1_8, safari, gecko
  • 10 locales : default, de_DE, en_UK, fr_FR, hr_HR, hu_HU, it_IT, nl_NL, pl_PL, pt_PT

OR

1) Force a single browser

You can add the following set-property in ModuleName.gwt.xml

<!– User Agent –>

<set-property name=”user.agent” value=”xxxx” />
where value = “ie6/opera/gecko1_8/safari/gecko”

Note: Add only one User Agent set-property in your ModuleName.gwt.xml

For example in MODULE com\mymodule\Container.gwt.xml:
<module >
<!– Inherit the core Web Toolkit stuff. –>
<inherits name=”com.google.gwt.user.User”/>
<!– Inherit the GWT-EXT stuff. –>
<inherits name=”com.gwtext.GwtExt” />
<!– Inherit the GWT-EXT User Extension stuff. –>
<inherits name=”com.gwtextux.GwtExtUx” />
<inherits name=”com.gwtextux.GridSearchPlugin”/>
<!– User Agent –>
<set-property name=”user.agent” value=”ie6″ />
<!– Include the core ExtJs files. –>
<stylesheet src=”js/ext/resources/css/ext-all.css” />
<script src=”js/ext/adapter/ext/ext-base.js” />
<script src=”js/ext/ext-all.js” />
<script src=”js/pagebus/pagebus.js”/>
</module>

2) Use only one locale

By default, GWT uses “default” locale. So no need to worry about the locale settings.

By doing this you can see the files difference in MODULENAME/html/*.* (If you are using Cypal Studio)  MODULENAME/www/*.* (If you are using GWT Designer) before and after added the set-property in ModuleName.gwt.xml

With this two points, GWT really speeds up we can get more space up to 30% to 40% and compilation timewill be almost 40% less.

Compile GWT files more than one browser

If  you add user.agent=ie6 the compiled code will work only in IE6.

If  you add the following user.agent then your code will work both the browsers (IE6 & Firefox 2/3)

<!– User Agent –>

<set-property name=”user.agent” value=”ie6″/>

<set-property name=”user.agent” value=”gecko1_8″/ >

If you add  <set-property name=”user.agent” value=”ie6,gecko1_8″/>

you will get an error message like below

[ERROR] Invalid property value ‘ie6,gecko1_8′
[ERROR] Failure while parsing XML

More info

Javascript Debug Toolkit – Debug javascript in ie,firefox,chrome,safari,opera and all browsers support ajaxToo

 
14 Comments

Posted by on November 10, 2008 in GWT/ JSNI / COMPILER

 

Tags: , ,

GWT 1.6 – Tomcat or Jetty ?

Bruce Johnson (tech lead of the Google Web Toolkit ) is asking the community if it would rather have Jetty or Tomcat as the hosted mode embedded HTTP. Unfortunately, I do not know Jetty enough to have an opinion. But if you know both Jetty and Tomcat, you should not hesitate to participate in this debate.

The GWT team has started putting together a 1.6 roadmap, which we’ll publish as soon as we have it nailed down. Two of the areas we want to work on for 1.6 are some improvements to hosted mode startup time and a friendlier output directory structure (something that looks more .war-like).

As part of this effort, we’ve all but decided to switch the hosted mode embedded HTTP server from Tomcat to Jetty. Would this break you? (And if so, how mad would you be if we did it anyway?)

http://groups.google.com/group/Google-Web-Toolkit/browse_thread/thread/604aec6b7460c133?hl=en&pli=1

 
 

Tags: , ,

GUID – Globally Unique Identifiers

What is an GUID / UUID ?

A UUID (or GUID) is a unique identifier that can be created whithout a central authority. UUIDs can be used if a sequence number is not good enough. This implementation is thread safe and very fast.

UUID generates version 1 UUIDs that contain the the MAC address of a network card. To obtain it, the following commands are invoked and their respective output parsed:

What is it used for?

UUIDs are applied for identification purposes in a number of fields in the computer industry.

Possible uses are (but are not limited to):

  • The identifiers in the windows registry.
  • Identifiers used in databases.
  • Identifiers used in RPC (COM, CORBA) (remote procedure calls)

To ensure nobody else would – by accident – provide something conflicting.

What does it look like?

The formal definition of the UUID string representation is  provided by the following :

UUIDs are basically 128 bit numbers, normally presented in the following hexadecimal – grouped form:

58e0a7d7-eebc-11d8-9669-0800200c9a66

UUID = time-low “-” time-mid “-” time-high-and-version “-” clock-seq-and-reserved clock-seq-low “-” node

time-low = 4hexOctet

time-mid = 2hexOctet

time-high-and-version = 2hexOctet

clock-seq-and-reserved = hexOctet

clock-seq-low = hexOctet

node = 6hexOctet

hexOctet = hexDigit hexDigit

hexDigit = “0” / “1” / “2” / “3” / “4” / “5” / “6” / “7” / “8” / “9” / “a” / “b” / “c” / “d” / “e” / “f” / “A” / “B” / “C” / “D” / “E” / “F”

In Microsoft Windows, run–> CMD–> ipconfig /all

Resources

 
1 Comment

Posted by on October 12, 2008 in GWT/ JSNI / COMPILER

 

Tags: , , ,

More on GWT Web Mode files

Before reading this article please have a look Google Web ToolKit – Hosted Mode Vs. Web Mode

Create a SampleGWT application and run in web mode, we need to do the following:

  • Compile the SampleGWT application first, by running the SampleGWT-compile script.
    SampleGWT-compile.cmd
  • The above step will create a www folder in the SampleGWTdirectory. Navigate to the www/com.sample.gwtworks.SampleGWT.SampleGWT directory.
  • Open the SampleGWT.html file in your web browser.

Everything needed to run the SampleGWT client application is contained in the www folder. You can deploy the contents of the folder to any servlet container and serve up the SampleGWT application. Here are the contents of the folder after completing the above steps:

SampleGWT.html: The host page that functions as the main HTML page for the SampleGWT application.

gwt.js: A generated JavaScript file that contains bootstrap code for loading and initializing the GWT framework.

History.html: An HTML file that provides history management support.

xxx-cache.html and xxx-cache.xml: One HTML and XML file per supported browser are generated. These contain the JavaScript code generated by the compilation of the source Java files in the com.sample.gwtworks.SampleGWT.client and com.sample.gwtworks.SampleGWT.server packages. For instance, in this case, on Windows, the compilation produced these files shown in below image . Each set of HTML and XML files represents one supported browser:

The file names are created by generating Globally Unique Identifiers (GUIDs) and using the GUID as part of the name. These file names will be different on different computers, and will also be different every time you do a clean recompile of the application on your computer. There is also a master HTML file generated (com.sample.gwtworks.SampleGWT.SampleGWT.nocache.html) that selects the right HTML file from the above files and loads it, depending on the browser that is running the application.

The www folder does not contain the code from the com.sample.gwtworks.SampleGWT.server package. This server code needs to be compiled and deployed in a servlet container so that the client application can communicate with the random quote service. In normal development mode, we will use the hosted mode for testing, which runs the server code inside the embedded Tomcat servlet container in the GWT development shell. This makes it very easy to run and debug the server code from inside the same Eclipse environment as the client application code. This is another feature of GWT, which makes it an extremely productive environment for developing AJAX applications.

In the web mode, our client Java code has been compiled into JavaScript unlike in the hosted mode. Also, you will notice that the SampleGWT.gwt.xml is not in this directory. The configuration details from this module are included in the generated HTML and XML files above.

Thankfully, all this work is automatically done for us by the GWT framework when we run the SampleGWT-compile script. We can focus on the functionality provided by our AJAX applications and leave the browser-independent code generation and lower level XmlHttpRequest API to GWT.

More in Hosted Mode

You can also compile the SampleGWT application from the GWT development shell in hosted mode. Run the SampleGWT-shell command script to run the application in hosted mode. Click on the Compile/Browse button in the GWT development shell window. This will compile the application and launch the application in a separate web-browser window.

All this dynamic JavaScript magic means that when you try to view the source for the application from the web browser, you will always see the HTML from the host page. This can be disconcerting when you are trying to debug problems. But the fantastic Eclipse support in GWT means that you can debug issues from the comfort of a graphical debugger by setting breakpoints and stepping through the entire application one line at a time.

 
1 Comment

Posted by on October 12, 2008 in GWT/ JSNI / COMPILER

 

Tags: , , , ,

Google Web Toolkit – Hosted vs. Web Mode

What is Hosted Mode and Web Mode ?

When you invoked a GWT application you were using what Google calls hosted mode. Hosted mode is only used during development. When in production, your application will be running in web mode. Before going any further in using GWT you need to understand the difference between the two. Note that as of this writing, hosted mode is only available on Windows and Linux.

Hosted mode

Think of hosted mode as training wheels for your GWT application. It’s a hybrid development environment unique to GWT that lets your code run as real Java code, but still inside a browser. Execution in hosted mode is controlled by the Google Web Toolkit development shell.

The development shell is actually an Eclipse Rich Client application, consisting of the shell console, a tomcat server, and one or more hosted browsers.

The hosted browser has two connections back to the development shell. One is just a regular http connection to get the web pages, .css files, images, and other resources. All these are handled by the embedded Tomcat server using a servlet called com.google.gwt.dev.shell.GWTShellServlet.

The second connection is a back-door that intercepts all interactions inside the hosted browser and routes them not to JavaScript but to Java code in the shell. That Java code in turn calls your real client Java code, which was compiled to bytecode by your IDE. The exact details of how this is done are hidden in the shell code, which is not open source.

  • The Shell program opens a hosted browser window, which loads MyApp.html.
  • MyApp.html loads gwt.js with a <script> tag.
  • gwt.js scans MyApp.html and parses out the <meta name=’gwtmodule’> to get the module name.
  • GWT reads the module file (MyApp.gwt.xml) to find the name of the EntryPoint class (MyApp).
  • The MyApp class is instantiated and its onModuleLoad( ) method is called. Your application begins.
  • Your application code makes calls into the GWT user library (gwt-user.jar), which is also Java code.
  • Code in gwt-user.jar manipulates the hosted browser’s DOM to add UI components to the web page, and redirects all browser events back to the Java application code using special hooks in the browser.

Because real Java code is running, you can use Java tools like the Eclipse debugger, findbugs, pmd, JUnit, and so forth. It’s almost as if you were developing a rich client program with Swing or SWT because it’s Java end-to-end.

Once you’ve debugged and unit tested your code the next step is to compile it into a form that can be run inside a regular browser (not one that has been hijacked by the development shell). That’s where web mode comes in.

Web mode

When you click the Compile/Browse button in the hosted browser, the GWT compiler translates your .client package into JavaScript and opens a normal web browser to view the application. At this point pages are still served by the shell’s Tomcat instance, but they could just as easily come from the file system or a normal web server.

Another way to invoke the GWT compiler is with the shell script provided by the scaffolding (MyApp-compile). You could also write an Ant script to do it if you prefer. For example to maintain the gwtpowered site I have an ant script that does the compile and then copies everything to my hosting provider. You can find the source at http://code.google.com/p/gwtpowered.

However you invoke it, the GWT compiler combines your code with a JavaScript version of the GWT API (the equivalent of gwt-user.jar) in one JavaScript file. This code and several supporting files are placed in the www directory inside your project. Everything from your public directory is copied there as well. The table below explains what all the files do:

Filename ———————-Description
long-hex-name.cache.html ———–Compiled JavaScript
long-hex-name.cache.xml  ———–Implementation defined
module-name.nocache.html———–Cache file selection
gwt.js —————————-Common GWT bootstrap code
history.html ———————–Contents of history IFrame
MyApp.html ———————–Main page, copied from public
tree*.gif ————————–+/- images used by the Tree widget

(more on GWT Web Mode Files)

The flow of execution during a page load in web mode is a bit different than in hosted mode.
Here’s a breakdown of what happens:

  1. The web browser loads MyApp.html.
  2. MyApp.html loads gwt.js with a <script> tag.
  3. gwt.js scans MyApp.html and parses out the <meta name=’gwtmodule’> to get the module name.
  4. gwt.js modifies the page to include an <iframe> that causes the source file module-name.nocache.html to be loaded.
  5. JavaScript inside the file module-name.nocache.html looks at the browser’s userAgent field to determine what kind of browser the user is running (IE6, Mozilla, Opera, etc.). Then it selects the correct code (cache file) for that browser type and redirects the <iframe> there.
  6. The JavaScript equivalent of your onModuleLoad( ) method is executed, and the rest of your application goes from there.  Manipulations to the browser DOM are performed with ordinary dynamic HTML calls in the compiled JavaScript.

Obfuscation

By default, the GWT Java to JavaScript compiler will produce obfuscated output. Code that has been obfuscated is smaller than humanreadable code, and is harder to reverse-engineer. It’s very difficult to debug, though. Should you ever need to debug the JavaScript that GWT produces, you can turn off obfuscation with command line parameters on the GWT compiler (for example as arguments to the MyApp-compile.cmd script). Use the -style pretty option to produce good looking output with readable names and indentation. To see full Java types as part of the names, use the -style detailed option instead.

 
10 Comments

Posted by on October 7, 2008 in GWT/ JSNI / COMPILER

 

Tags: , , , , , , , , , , , , , ,

Javascript Native Interface – JSNI

JSNI ?

Sometimes when you’re writing Java code (especially if you’re doing systems programming) you find that you have to get closer to the metal and run code outside the Java virtual machine. For example, you might need to access a code library that’s in a different language. To do that in Java, you would declare a method as native and then provide the implementation of that method in another language, such as C. This is called the Java Native Interface (JNI). You can do the same thing with GWT Java code on the client, except instead of C code, the native language for the browser is JavaScript. That’s how Google came up with the name JavaScript Native Interface (JSNI).

Declaring a Native Method

To declare a native method in JSNI, use Java’s standard native keyword just like you would with JNI. In JNI, the native C code is in a separate file, compiled separately and dynamically loaded at run time. In JSNI, the native JavaScript code is embedded directly in your Java source in a specially formatted comment:

package com.xyz.client;
public class Alert {
public static native void alert(String msg)
/*-{
$wnd.alert(msg);
}-*/;

}

A JSNI comment block begins with /*-{ and ends with }-*/.

As this example shows, 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 instead of the frame.

How it Works
In Web mode, the GWT compiler converts the client half of your Java program into JavaScript. So normally, when the compiler sees a method declaration, code inside the braces has to go through some kind of translation process. If it’s a native method, however, the compiler’s job is easier. All it has to do is copy the JavaScript native code directly into the compiled result.

If you’ve used Microsoft’s Visual C++ or the GNU C++ compiler, the effect is much like inline assembler code, except with a much higher level language than assembler. Since JavaScript is interpreted, any errors in the JavaScript code won’t be evident until run-time.

Calling JSNI from Java
Calling a JSNI method from Java1 is no different than calling a regular Java method. Here’s an example:

button1.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
Alert.alert("clicked!");
}
});

The caller can’t really tell if the method is native or not. This gives you some flexibility in changing your mind later about how the method is implemented.

Calling Java from JSNI

Going the other way is a little trickier. For example, suppose you pass an object to a JSNI method and you need to access a field or call a method in that object. You’ll need to know how the GWT compiler mangles the Java field and method names so you can access them from your own JavaScript code.

Accessing Java fields

Object Oriented purists would say that you shouldn’t access fields of a Java class directly because it makes it harder to change the implementation of that class later. But hey, we’re writing native code here so we can cut a few corners. The syntax for accessing a Java field is:

obj.@class::field


where:
obj is the object instance being referenced. For static variables, leave off the instance expression and the trailing period.
class is the fully-qualified name of the class in which the field is declared (or a subclass thereof).
field is the name of the field being accessed.

Invoking Java methods

Calling methods uses a syntax similar to accessing fields, except you must also supply the signature of the method you’re calling. The reason for that is that Java methods can be overloaded, i.e., two methods can have the same name but take different parameters.

The syntax is:

obj.@class::method(sig)(args)

where:
obj is the object instance being referenced. For static methods,
omit the instance expression and the trailing period.
class is the fully-qualified name of the class in which the method is declared (or a subclass thereof).
method is the name of the method being called.
sig is the internal Java method signature (see Section 7.4, Method signatures ).
args is the actual argument list passed to the method.

Method signatures
JSNI method signatures are exactly the same as JNI method signatures except that the method return type is left off. That’s because it’s not needed to figure out which overloaded method you’re referring
to. The following table shows these type signatures:

For example, the Java method:
long f (int n, String s, int[] arr);

has the following type signature:
(ILjava/lang/String;[I)

We will discuss the specific rules for how values passing in and out of JSNI code must be treated.

Example

This code shows some examples of accessing Java fields and methods from within JSNI. It demonstrates passing numbers, strings, booleans, and Java objects into JavaScript. It also shows how a JavaScript method can make a method call on a Java object that was passed in.

public class J2JS {
/** Pass a Java numeric primitive */
public static void testJ2JSNumeric() {
int x = 42;
jsNumeric(x);
}

/**
* Method jsNumeric.
* @param x int
*/

private static native void jsNumeric(int x) /*-{
$wnd.alert(“x is ” + x);
}-*/
;

/** Pass a Java String */
public static void testJ2JSString() {
String s = "my string";
jsString(s);
}

/**
* Method jsString.
* @param s String
*/

private static native void jsString(String s) /*-{
$wnd.alert("s is " + s);
}-*/
;

/** Pass a boolean */
public static void testJ2JSBoolean() {
boolean b = true;
jsBoolean(b);
}

/**
* Method jsBoolean.
* @param b boolean
*/

private static native void jsBoolean(boolean b) /*-{
$wnd.alert("b is " + b);
}-*/;

/** Pass an arbitrary Java Object */
public static void testJ2JSObject() {
MyJavaObject obj = new MyJavaObject();
jsObject(obj);
}

/**
* Method jsObject.
* @param obj MyJavaObject
*/
private static native void jsObject(MyJavaObject obj) /*-{
$wnd.alert("Calling getText(): " + obj.@MyJavaObject::getTextAt(I)(3));
}-*/;

}

If you look at the source code for GWT you’ll see that much of it is defined in terms of JSNI. Most GWT programmers will never need to define JSNI methods themselves, but it’s nice to know the feature is there if you need it.

 
Leave a comment

Posted by on October 7, 2008 in GWT/ JSNI / COMPILER

 

Tags: , ,

JSNI Components

JavaScript Native Interface (JSNI)

JSNI is GWT’s mechanism to allow you as a programmer to embed JavaScript in the Java code. We can’t overemphasize the point that JSNI is almost a last-resort approach. Many issues that look like they need JSNI can be solved at the GWT Java level if you spend time looking. It’s possible to view the relationship between GWT Java and JSNI as you do the relationship between a high-level programming language and assembly code: Yes, you can do it, but it’s sensible only if there is a clear need to do so.

It’s possible to carry this analogy further, because JSNI, just like assembly language, is less portable across systems. If you write something in JSNI that works in one browser, there is a risk that it may not work at all, or perhaps may work in a different way, in other browsers. As an example, you can count the number of children for a DOM element using the simple Java GWT DOM.countChildren() method. If you were to write that method in JavaScript, you would have to, as GWT does for you, write several versions to cope with DOM differences between Internet Explorer and the other browsers (check out the DOMImplStandard and DOMImplIE6 classes in the GWT gwt-user.jar file to see the GWT definitions for this method in the different browsers). In JSNI, you can write only one of these methods, or you would have to add the own browser detection JavaScript as well. This isn’t in the spirit of GWT, which advocates writing once and running in many different browsers. There is also the risk that writing your own JSNI code could introduce memory leaks, unless you’re an expert at those matters.

  • NOTE JSNI is applicable only to client-side aspects of your application, because JavaScript doesn’t run on the server side. It’s therefore not possible to use JSNI code in any server-side code or to pass an object over remote procedure calling (RPC) to the server and expect to be able to execute any included JSNI code server-side.

However, let’s be a little more positive about JSNI. In the cases where you do have to use it, it can be powerful. JSNI lets you interface between Java and JavaScript in a type-safe way; you can use JavaScript objects in the Java code and rely on Java’s strong typing to protect you against various programming errors. But again, the more functionality you include in a single JSNI block, the less you can rely on Java’s strong typing to minimize errors.

JSNI also provides a seamless way of moving between Java and JavaScript, allowing you to pass objects and exceptions across the boundary in both directions. Through JSNI, you manage JavaScript objects from Java, and you can call back to the Java code from the JavaScript code you write. One use is to wrap a third-party JavaScript library, where you create JavaScript objects from the library and pass them around the GWT Java code before perhaps sending them back to the JavaScript library. One word of warning about JSNI: It’s potentially a moving target during the early stages of GWT adoption. The existing model works well in most cases, as you’ll see later in this chapter, but already several requests for reviews have been published about changing functionality of certain aspects. A guiding principle of JSNI coding is to spend as little time as possible in “the dark side”; each JSNI method should be at an atomic level (perform one clear function) so that you isolate issues and keep as much control as possible in the strongly-types Java realm. Let’s move on and assume that you’re in a situation where JSNI is the approach you need. The first thing you need to understand is how to use the syntax.

Understanding JSNI

If you’re familiar with writing native methods in Java for other languages, then JSNI will seem relatively familiar. If you’ve never written native methods before, don’t worry; their syntax is a little strange but not frightening. Java Native Interface (JNI) is the Java approach that allows Java code to interface with components written in other languages, for example C or C++ or assembly. JSNI is the GWT Java equivalent for interfacing with JavaScript components, and it follows a syntax similar to that of JNI.

In the next few sections, we’ll look at the syntax used to cross the boundary both ways between Java and JavaScript and how the objects you pass over that boundary are treated. Here’s a simple JSNI method call:

public static native void method_name(ObjectTyp someData)
/*-{
someData.@org.gwtbook.client.Data::data1 == "GWT In Action"
}-*/;

We hope that doesn’t look too scary, even with the @ and :: symbols sprinkled in. To start to understand why these are there, we’ll first look at how you call Java-Script functionality from a GWT Java program.

Crossing the boundary from Java to JavaScript

To include JavaScript code in a GWT application, you must write it in a specific way so that both the syntax checkers of Java and the GWT Java compiler can recognize it and deal with it appropriately. For syntax checkers, that means ignoring the code because it isn’t Java; and for the GWT compiler, it means merging it in a structured way into the JavaScript output of compilation.

A basic JSNI method is defined as shown here:

In the template, you define the method in a normal Java way, but you must include the keyword native as one of the modifiers (1); this identifies the code to the Java compiler as JNI code and to the GWT compiler as JSNI code. To help any syntax checkers know that they should avoid parsing the JavaScript code, you wrap it as a comment by using a modified standard comment, which starts with the characters /*- (a forward slash, an asterisk, and a dash) and ends with -*/ (a dash, an asterisk, and a forward slash) (2). It’s also important not to forget the trailing semicolon at the end of the definition; otherwise your code won’t compile!

Crossing the boundary from Java to JavaScript can come in two forms: writing JavaScript code in the Java application that performs some dedicated functionality, or writing JavaScript in the Java application that calls functionality in a Java- Script library already loaded into the web browser. Both methods follow the same syntax of extending the previous template to provide parameters, a return type if necessary (otherwise the return type must be defined as void), and the native code. You can consider this crossing of the boundary diagrammatically as shown in figure-1

Figure – 1 The interaction between Java and JavaScript code when crossing the Java-to-JavaScript boundary in a JSNI call from a GWT application

Here is some typical code required to cross the boundary from Java to JavaScript:


Overall, the definition is the same as a normal Java method; you provide a list of parameters that can be passed in and a possible return object type. If you provide a return type, rather than just a void, then the JavaScript must return an object of the correct type. (Be aware that JSNI code can’t create new Java objects; it can manipulate ones passed in or create new JavaScript objects, but not new Java objects.)

  • REMEMBER It isn’t possible to create new Java objects in a JSNI code block. Return types must either be primitive types, manipulated Java objects that have been passed in as input parameters, or references to newly created Java- Script objects (a JavaScriptObject type).

It’s important to understand how the objects you provide as parameters are handled across the Java-to-JavaScript boundary, as you’ll see in the next section.

Passing Java objects across the Java-to-JavaScript boundary

We have mentioned before that one of the benefits of using Java to develop the Ajax/rich Internet applications is the strong typing provided by the Java language, which isn’t present in JavaScript. This missing typing model could cause problems as you start crossing the boundary from Java to JavaScript.
Unfortunately, there isn’t much you can do about the typing capabilities of JavaScript. Once the objects have passed into the realm of JavaScript, they’re sadly on their own. This brings us back to the point we mentioned earlier—the shorter amount of time you can spend in this potentially lawless world of JavaScript, the better. If you have to spend a long time there, it’s preferable that you do so only to interact with stable third-party JavaScript libraries. What you can do, though, is ensure that a clearly defined and repeatable mapping exists between Java typed objects and JavaScript untyped objects, which is what GWT provides.

Primitive Java numeric types, such as byte, short, char, int, long, float, or double, become simple objects in JavaScript whose value is that of the original object. For example, if you have a Java char, char keyPress = ‘a’, then it will become the JavaScript variable var k = ‘a’. Similarly, the Java int, int val = 10, becomes the JavaScript variable var v = 10.

A Java String is translated across into JavaScript as a simple variable to which the original text is assigned. Therefore the Java object String name = “GWT In Action” becomes the JavaScript variable var s = “GWT In Action”. Finally the simple Java boolean, becomes another simple JavaScript variable; the Java boolean b = true becomes the JavaScript variable var b = true.

Moving on to more complicated Java objects that can be passed across the boundary, you have the Java array, a Java object, and a new object to GWT called the JavaScriptObject. We’ll discuss the last object more in the next section; for now, you should think of it as just a reference to a JavaScript object created somewhere else that can be passed around the Java code and on to other JavaScript methods—but you can’t look into its contents from the GWT Java code. This may sound strange, but we’ll explain in more detail later in the section on this object.

Passing an array across the Java-to-JavaScript boundary is treated in a similar opaque way; you know you have an array object, but you can’t look into its contents. This means that if the JavaScript code needs to use values in the array, then you should move them out of the array before you cross the boundary: either into separate parameters or into another type of user-defined Java object. You can manage Java objects in JavaScript through the JSNI interface, as we’ll discuss next.

You can also pass your own defined Java objects across the Java-to-JavaScript  boundary; GWT provides a special syntax allowing you to access the fields and methods of that Java object. This will take a little bit of explaining, so please, stick with us.

Let’s say you have an object of type Data, which is defined by the class shown below

Example class that will be accessed through the Java-to-JavaScript boundary

package org.gwtbook.client;
public class Data{
String data1 = "GWT In Action";
int version = 1;
}

You use an instance of this type in a new class defined called DataManip

Example class demonstrating accessing Java objects through the Java-to-JavaScript boundary

In the DataManip class, you have a couple of additional class variables: one called correct (1)and then other a static variable called checked (2)(it doesn’t matter what they stand for in this example). You also define a JSNI method (3) called doSomething(), which takes as a parameter an instance of the Data class but returns nothing (we’ll cover going across the JavaScript-to-Java boundary in a short while). When doSomething() is called, you want it to look at the DataManip class’ correct value (4); if that is false, then you want to check the static field checked (5). If that too is false, then you confirm whether the Data instance passed in as a parameter has its data1 field set to “GWT In Action” and the version value set to 1 (6); if they are, then you do something else in the code. To perform this functionality, you need to access an instance field, a static
field, and a field in a Java object passed in as a parameter, in that order. In each case, you need to use the JSNI-specific syntax for accessing Java objects, the template for which is shown in figure – 2


Figure – 2 Explanation of the JSNI method to access a field in a Java object. The first part comprises the name of the instance (an object name, the keyword this, or blank for a static field). Next are the fully
qualified class name and the field name.

When you access the instance field (4), the name of the instance is this, the class name of this instance is org.gwtbook.client.DataManip, and the field you’re after is called correct. Accessing this field is, therefore, performed by writing the following in the JSNI code:

this.@org.gwtbook.client.DataManip::correct

Accessing the static field (5) requires you to access a field where there is no defined objectName (because the field is static across all instances). In JSNI, you write

@org.gwtbook.client.DataManip::checked

(Notice that the period is missing and only the @ symbol is still required if there is no object name to reference.)

Finally, when you want to reference the data1 field in the parameter that you’ve passed in, then the parameter name, someData, is the objectName, and you write

someData.@org.gwtbook.client.Data::data1

You can also access the methods from the Java object passed across the boundary in a similar way. We’ll discuss how that works once you’ve seen how you return objects back across the boundary to the Java code.

Sending objects back across the JavaScript to Java boundary

When you’ve completed the functionality you need in JSNI, it’s common to pass an object back in return. As with all Java methods, you need to define the return type of the JSNI method, which will either be a Java primitive, a Java object, a GWT JavaScriptObject, or void. Diagrammatically, you’re performing the action shown in figure -3 ; once complete, program control is back in the hands of the GWT Java code.

Just as there was a defined mapping between Java and JavaScript objects for the parameters, such a mapping exists when going from JavaScript to Java for the return values.

To get a Java primitive numeric coming out of the method call, the value returned from the JavaScript must be a numeric value. You need to be careful with returning primitive numerics because GWT doesn’t determine whether the type is correct. If you define the Java method to return a Java int, and the Java-Script returns the value 1.5, then the result passed out of that surrounding Java method will be unpredictable.

Returning Strings and booleans is much simpler because they translate directly to their Java equivalents. Java objects can also be returned from the Java-Script; however, you can’t just create Java objects in the JavaScript. If you want to return a Java object, then it must have been passed in as one of the parameters.


Figure – 3
Examining the interaction between Java and JavaScript code when returning values across the JavaScript-to-Java boundary in a JSNI call from a GWT application

Take care if you’re returning null objects, because the JavaScript undefined value isn’t treated by JSNI as null; if it’s used, unpredictable results can occur (you must always use the null value). You may even want to ensure that any JavaScript variable you pass back is checked to be sure it isn’t the undefined value before it’s returned.

We mentioned briefly when passing in parameters that GWT provides a special object called the JavaScriptObject. This type of object can be returned by the JSNI method if a new JavaScript object is created as part of the call. You’ll see this in use often later in this chapter when you use JSNI methods to create new Java-Script objects from a third-party library. You need a reference to these third-party objects in the Java code because you’ll later be calling methods on them, and they’re therefore passed back as subclasses to the JavaScriptObject. This Java-ScriptObject is opaque to the Java code—you can’t use Java code to call the methods in it or even to see its fields; you need to pass them back into new JSNI methods to do that. But you’ll see this in action a little later. First we need to finish our journey through the JSNI syntax by looking at how you can call Java methods
from JavaScript.

Crossing the boundary from JavaScript to Java

As well as being able to access fields on Java objects from JavaScript, you can execute methods defined in those objects in a similar manner, as shown in figure – 4

Figure 4 Examining the interaction between JavaScript and a Java object when crossing the JavaScript to Java boundary in JSNI

To refer to a method, you use a syntax similar to that you used to refer to fields. There are, however, some slight differences. This time, the generic template for calls to methods is shown in figure  – 5

The first part of this should be familiar from when you were accessing fields, with the same discussion about there being no objectName if you’re accessing a static method, using this if you accessing a method in the current instance, and using the parameter name if you’re accessing a passed-in object to a method. The difference occurs in the second half of the template, where you see the values param-signature and arguments. The arguments part is a list of the various arguments whose types match the parameter signature. JSNI uses the internal Java

Figure 5Explanation of the JSNI method to access a method in a Java object. First is the
instance name, followed by the fully qualified class name. The method name is followed by the
parameter signature and then the arguments.

method signature to define the parameter signature, but it doesn’t require a definition of the return type to be included. Parameter type signatures are defined in  below table.

Java type signature for various Java types

Let’s look at a simple example

Sample attempts to call methods in a Java class from JavaScript


In (1), you call the m1() method in this class, which takes a Java String as its parameter; so, you must define the parameter signature as Ljava/lang/String;. Then, you call the m2() method (2), which expects an integer, so the method signature is I. (In your code, these definitions should all be on one line—it’s sometimes difficult to get all of them on one line in the book!) The final type of objects that can come out of the JSNI call are exceptions.

Handling exceptions

It’s strongly recommended that JavaScript exceptions be handled in the Java-Script segments of the JSNI method and that Java methods be handled in Java code. The reason is that when a JavaScript exception creeps over the JavaScript boundary into the Java, it becomes, and can only become, an object of type
JavaScriptException.

You don’t necessarily lose information about the JavaScript exception, because you can use the getName() and getDescription() methods to return String values about the original JavaScript exception. But relying on these methods leads to messy code requiring the use of String comparison to handle the exceptions, whereas they can be handled more gracefully in the JavaScript code. The only exception to this rule is where an exception is raised in Java code called by a JSNI method, which is then handed back to more Java code. In this case, the original Java exception typing is preserved through the boundaries.
With all these basics in place, let’s look at the occasions when we said you may need to use JSNI, starting with how you perform different types of communication between components (browser, GWT applications, and legacy code).

Summary

JSNI is an extremely powerful way of interfacing with existing JavaScript libraries and filling in the gaps where GWT may not yet have the functionality you need. It allows you to apply some of the good control and typing aspects of Java to the Java-Script interfaces; however, you should keep your use of JavaScript to a minimum. View using JSNI as you would writing assembly-language code segments in a highlevel language project—it’s for specialized tasks, not for everyday use. The main reason for restricting the use of JavaScript is cross-browser issues, just as assemblylanguage coding restricts your ability to move projects to other machines.

If you’re going to use JSNI, remember that it’s valid only in your client-side components, and you’ll need to use the $wnd and $doc variables instead of the standard JavaScript window and document variables because of the way GWT loads your application. Also remember that when you’re executing JavaScript code, you don’t have the protection of GWT when it comes to browser differences (for example, the JavaScript getElementById() method isn’t as robust as the GWT’s cross-browser DOM.getElementByID() method). Finally, GWT and JSNI don’t allow you to get around any normal restrictions of JavaScript coding; for example, you  still can’t subvert the security mechanisms that browsers employ.

We’ve reached the end of our journey through the more client-side related aspects of GWT, and it’s time to consider the flexibility that GWT provides when building a real-sized application—using GWT’s modularization aspects.

 
Leave a comment

Posted by on October 6, 2008 in GWT/ JSNI / COMPILER

 

Tags: , , , , ,

Abstract Syntax Tree for your own applications

This article shows how you can use the Abstract Syntax Tree for your own applications using ECLIPSE. This article is written by

By Thomas Kuhn, Eye Media GmbH
Olivier Thomann, IBM Ottawa Lab
Copyright ©2006 Thomas Kuhn, Olivier Thomann. Made available under the EPL v1.0
November 20, 2006

Summary

The Abstract Syntax Tree is the base framework for many powerful tools of the Eclipse IDE, including refactoring, Quick Fix and Quick Assist. The Abstract Syntax Tree maps plain Java source code in a tree form. This tree is more convenient and reliable to analyse and modify programmatically than text-based source.

Introduction

Are you wondering how Eclipse is doing all the magic like jumping conveniently to a declaration, when you press “F3″ on a reference to a field or method? Or how “Replace in file” solidly detects the declaration and all the references to the local variable and modifies them synchronously?

Well, these—and a big portion of the other source code modification and generation tools—are based upon the Abstract Syntax Tree (AST). The AST is comparable to the DOM tree model of an XML file. Just like with DOM, the AST allows you to modify the tree model and reflects these modifications in the Java source code.

This article refers to an example application which covers most of the interesting AST-related topics. Let us have a look at the application that was built to
illustrate this article:

Example Application

According to Java Practices [4], you should not declare local variables before using them. The goal of our application will be to detect contradicting variable declarations and to move them to their correct place. There are three cases our application has to deal with:

  1. Removal of unnecessary declaration. If a variable is declared and initialized, only to be overridden by another assignment later on, the first declaration of the variable is an unnecessary declaration.
  2. Move of declaration. If a variable is declared, and not immediately referenced within the following statement, this variable declaration has to be moved. The correct place for the declaration is the line before it is first referenced.
  3. Move of declaration of a variable that is referred to from within different blocks. This is a subcase of case 2. Imagine that a variable is used in both a try- and a catch clause. Here the declaration cannot be moved right before the first reference in the try-clause, since then it would not be declared in the catch-clause. Our application has to deal with that and has to move the declaration to the best possible place, which would be here one line above the try-clause.

In Appendix A, Code Fragments for Example Application Cases code snippets to each of these cases are provided.

You can import the example application into your workspace [1] or install the plug-in using the Eclipse Update Manager [2].

Workflow

A typical workflow of an application using AST looks like this:

Figure 1. AST Workflow


  1. Java source: To start off, you provide some source code to parse. This source code can be supplied as a Java file in your project or directly as a char[] that contains Java source
  2. Parse: The source code described at 1 is parsed. All you need for this step is provided by the class org.eclipse.jdt.core.dom.ASTParser. See the section called “Parsing source code”.
  3. The Abstract Syntax Tree is the result of step 2. It is a tree model that entirely represents the source you provided in step 1. If requested, the parser also computes and includes additional symbol resolved information called “bindings“.
  4. Manipulating the AST: If the AST of point 3 needs to be changed, this can be done in two ways:
    1. By directly modifying the AST.
    2. By noting the modifications in a separate protocol. This protocol is handled by an instance of ASTRewrite.

    See more in the section called “How to Apply Changes”.

  5. Writing changes back: If changes have been made, they need to be applied to the source code that was provided by 1.This is described in detail in the section called “Write it down”.
  6. IDocument: Is a wrapper for the source code of step 1 and is needed at point 5

The Abstract Syntax Tree (AST)

As mentioned, the Abstract Syntax Tree is the way that Eclipse looks at your source code: every Java source file is entirely represented as tree of AST nodes. These nodes are all subclasses of ASTNode. Every subclass is specialized for an element of the Java Programming Language. E.g. there are nodes for method declarations ( MethodDeclaration), variable declaration ( VariableDeclarationFragment), assignments and so on. One very frequently used node is SimpleName. A SimpleName is any string of Java source that is not a keyword, a Boolean literal ( true or false) or the null literal.

For example, in i = 6 + j;, i and j are represented by SimpleNames. In import net.sourceforge.earticleast, net sourceforge and
earticleast are mapped to SimpleNames.

All AST-relevant classes are located in the package org.eclipse.jdt.core.dom of the org.eclipse.jdt.core plug-in.

To discover how code is represented as AST, the AST Viewer plug-in [5] is a big help: Once installed you can simply mark source code in the editor and let it be displayed in a tree form in the AST Viewer view.

Parsing source code

Most of the time, an AST is not created from scratch, but rather parsed from existing Java code. This is done using the ASTParser. It processes whole Java files as well as portions of Java code. In the example application the method parse(ICompilationUnit unit) of the class AbstractASTArticle parses the source code stored in the file that unit points to:

protected CompilationUnit parse(ICompilationUnit unit) {
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setKind(ASTParser.K_COMPILATION_UNIT);
	parser.setSource(unit); // set source
	parser.setResolveBindings(true); // we need bindings later on
	return (CompilationUnit) parser
.createAST(null /* IProgressMonitor */); // parse
}

With ASTParser.newParser(AST.JLS3), we advise the parser to parse the code following to the Java Language Specification, Third Edition. JLS3 includes all Java Language Specifications up to the new syntax introduced in Java 5. With the update of Eclipse towards JLS3, changes have been made to the AST API. To preserve compatibility, the ASTParser can be run in the deprecated JLS2 mode.

parser.setKind(ASTParser.K_COMPILATION_UNIT) tells the parser, that it has to expect an ICompilationUnit as input. An ICompilationUnit is a pointer to a Java file. The parser supports five kinds of input:

Entire source file: The parser expects the source either as a pointer to a Java file (which means as an ICompilationUnit, see the section called “Java Model”) or as
char[].

  • K_COMPILATION_UNIT

Portion of Java code: The parser processes a portion of code. The input format is char[].

  • K_EXPRESSION: the input contains a Java expression. E.g. new String(), 4+6 or i.
  • K_STATEMENTS: the input contains a Java statement like new String(); or synchronized (this) { ... }.
  • K_CLASS_BODY_DECLARATIONS: the input contains elements of a Java class like method declarations, field declarations, static blocks, etc.

Java Model

The Java Model is a whole different story. It is out of scope of this article to dive deep into its details within. The parts looked at will be the ones which intersect with the AST. The motivation to discuss it here is, to use it as an entry point to build an Abstract Syntax Tree of a source file. Remember, the ICompilationUnit is one of the possible parameters for the AST parser.

The Java Model represents a Java Project in a tree structure, which is visualized by the well known “Package Explorer” view:

Figure 2. Java Model Overview


The nodes of the Java Model implement one of the following interfaces:

  • IJavaProject: Is the node of the Java Model and represents a Java Project. It contains IPackageFragmentRoots as child nodes.
  • IPackageFragmentRoot: can be a source or a class folder of a project, a .zip or a .jar file. IPackageFragmentRoot can hold source or binary
    files.
  • IPackageFragment: A single package. It contains  ICompilationUnits or IClassFiles, depending on whether the IPackageFragmentRoot is of type source or of type binary. Note that IPackageFragment are not organized as parent-children. E.g. net.sf.a is not the parent of net.sf.a.b. They are two independent children of the same IPackageFragmentRoot.
  • ICompilationUnit: a Java source file.
  • IImportDeclaration,  IType, IField, IInitializer, IMethod: children of ICompilationUnit. The information provided by these nodes is available from the AST, too.

In contrast to the AST, these nodes are lightweight handles. It costs much less to rebuild a portion of the Java Model than to rebuild an AST. That is also one reason why the Java Model is not only defined down to the level of ICompilationUnit. There are many cases where complete information, like that provided by the AST, is not needed.

If you want to see more info…. click here

ECLIPE CORNER ARTICLE – Abstract Syntax Tree

 
2 Comments

Posted by on October 4, 2008 in GWT/ JSNI / COMPILER

 

Tags: , ,

Abstract Syntax Tree

Compiler Structure

  • Source code parsed to produce AST
  • AST transformed to CFG
  • Data flow analysis operates on control flow graph (and other intermediate representations)

Abstract Syntax Tree (AST)

  • Programs are written in text
    ■ I.e., sequences of characters
    ■ Awkward to work with
  • First step: Convert to structured representation
    ■ Use lexer (like flex) to recognize tokens
    – Sequences of characters that make words in the language
    ■ Use parser (like bison) to group words structurally
    – And, often, to produce AST

Abstract Syntax Tree Example

ASTs

  • ASTs are abstract
    ■ They don’t contain all information in the program
    – E.g., spacing, comments, brackets, parentheses
    ■ Any ambiguity has been resolved
    – E.g., a + b + c produces the same AST as (a + b) + c
  • For more info, see CMSC 430
    ■ In this class, we will generally begin at the AST level

Disadvantages of ASTs

  • AST has many similar forms
    ■ E.g., for, while, repeat...until
    ■ E.g., if, ?:, switch
  • Expressions in AST may be complex, nested
    ■ (42 * y) + (z > 5 ? 12 * z : z + 20)
    • Want simpler representation for analysis
    ■ …at least, for dataflow analysis

Control-Flow Graph (CFG)

  • A directed graph where
    ■ Each node represents a statement
    ■ Edges represent control flow
  • Statements may be
    ■ Assignments x := y op z or x := op z
    ■ Copy statements x := y
    ■ Branches goto L or if x relop y goto L
    ■ etc.

Control-Flow Graph Example

Variations on CFGs

  • We usually don’t include declarations (e.g., int x;)
    ■ But there’s usually something in the implementation
  • May want a unique entry and exit node
    ■ Won’t matter for the examples we give
  • May group statements into basic blocks
    ■ A sequence of instructions with no branches into or out of the block

Control-Flow Graph w/Basic Blocks

  • Can lead to more efficient implementations
  • But more complicated to explain, so…
    ■ We’ll use single-statement blocks

CFG vs. AST

  • CFGs are much simpler than ASTs
    ■ Fewer forms, less redundancy, only simple expressions
  • But…AST is a more faithful representation
    ■ CFGs introduce temporaries
    ■ Lose block structure of program
  • So for AST,
    ■ Easier to report error + other messages
    ■ Easier to explain to programmer
    ■ Easier to unparse to produce readable code

Data Flow Analysis

  • A framework for proving facts about programs
  • Reasons about lots of little facts
  • Little or no interaction between facts
    ■ Works best on properties about how program computes
  • Based on all paths through program
    ■ Including infeasible paths

Available Expressions

  • An expression e is available at program point p if
    e is computed on every path to p, and
    ■ the value of e has not changed since the last time e is computed on p
  • Optimization
    ■ If an expression is available, need not be recomputed
    – (At least, if it’s still in a register somewhere)

Data Flow Facts

  • Is expression e available?
  • Facts:
    a + b is available
    a * b is available
    a + 1 is available

Gen and Kill

  • What is the effect of each statement on the set of facts?


Computing Available Expressions

Terminology

  • A joint point is a program point where two branches meet
  • Available expressions is a forward must problem
    ■ Forward = Data flow from in to out
    ■ Must = At join point, property must hold on all paths that are joined

Data Flow Equations

  • • Let s be a statement
    ■ succ(s) = { immediate successor statements of s }
    ■ pred(s) = { immediate predecessor statements of s}
    ■ In(s) = program point just before executing s
    ■ Out(s) = program point just after executing s

■ Note: These are also called transfer functions

Liveness Analysis

  • A variable v is live at program point p if
    ■ v will be used on some execution path originating from p…
    ■ before v is overwritten
  • Optimization
    ■ If a variable is not live, no need to keep it in a register
    ■ If variable is dead at assignment, can eliminate assignment

Data Flow Equations

  • Available expressions is a forward must analysis
    ■ Data flow propagate in same dir as CFG edges
    ■ Expr is available only if available on all paths
  • Liveness is a backward may problem
    ■ To know if variable live, need to look at future uses
    ■ Variable is live if available on some path

Gen and Kill

  • What is the effect of each statement on the set of facts?

Computing Live Variables

Very Busy Expressions

  • An expression e is very busy at point p if
    ■ On every path from p, e is evaluated before the value of e is changed
  • Optimization
    ■ Can hoist very busy expression computation
  • What kind of problem?
    ■ Forward or backward?  backward
    ■ May or must?  must

Reaching Definitions

  • A definition of a variable v is an assignment to v
  • A definition of variable v reaches point p if
    ■ There is no intervening assignment to v
  • Also called def-use information
  • What kind of problem?
    ■ Forward or backward? forward
    ■ May or must? may

Space of Data Flow Analyses

  • Most data flow analyses can be classified this way
    ■ A few don’t fit: bidirectional analysis
  • Lots of literature on data flow analysis
 
1 Comment

Posted by on October 4, 2008 in GWT/ JSNI / COMPILER

 

Tags: , , , , , ,

About GWT compiler

The GWT compiler is the fulcrum of GWT. The entire approach GWT takes, encapsulating browser differences and compiling JavaScript from Java, is made possible by the design and architecture of the compiler.

The GWT compiler compiles Java into JavaScript, but it’s important to understand that the compiler doesn’t compile Java the same way javac does. The GWT compiler is really a Java source to JavaScript source translator.

source : http://java.dzone.com/news/understanding-gwt-compiler

 
Leave a comment

Posted by on October 1, 2008 in GWT/ JSNI / COMPILER

 

Tags: , , , ,

GWT- About Generators and Exporters

Why do at runtime what you can do at compile time?

orginally this article is written by Ray (Google developer)

If GWT had a mantra, this would be it.

Introduction

The GWT compiler deals with a closed world — no dynamic class loading, but it does permit deferment of binding decisions until compile time via a rule based mechanism that is part of the external GWT Module metadata. You can choose to replace a given type with other preauthored types, or, and here’s the important part: you can replace types with classes that are generated on the fly.

This is the compile time equivalent of what you would do at runtime with libraries like CGLIB or the JDK’s Proxy/Interceptor classes, and similar to Sun’s APT (Annotation Processing Tool), except that it’s all integrated into GWT and you don’t need to worry about running separate APT-passes.

The deferred binding mechanism is used heavily in GWT to replace standard implementations of browser widgets with quirky implementations for browsers with divergent behavior. GWT then compiles multiple permutations of your code base, running the binding rules separately for each browser. Thus, if you have rules to target 4 different browsers, you end up with GWT compiling 4 different code bases and producing 4 compiled outputs.

Why does it do this? Because the result is more optimal code. Otherwise, you would have to include all 4 Implementation subclasses in your main code base, and use runtime logic to dynamically call the appropriate target, e.g. “if(brokenDom) DOMImplIE.foo(), else… DOMImplStandard.foo()…” It shortens load time by only forcing your browser to load what is neccessary, and it shortens run time by removing another level of indirection. Finally, it permits the optimizer to actually inline the appropriate implementation directly into the call site.

Generators

GWT also uses compile time generation of Java code to implement many platform features. The most famous of course is the RPC/Serialization mechanism. Here, GWT takes an interface, such as MyServiceAsync, and generates an implementation of this class on the fly, which contains all of the logic needed to serialize non-primitive types, send them across the wire via XMLHttpRequest, invoke the RemoteService, deserialize the rule, and invoke the async handler. It is probably the most complex generator in GWT, but not the only one.

Internationalization and Localization are also handled by the generator mechanism. Instead of loading ResourceBundles at runtime, you instead pre-process them and turn them into an interface, with one method per property. GWT will then use a generator to fill in the implementation of this interface which returns the values that are in the property file when the corresponding method is invoked. And what if you don’t use some of the properties? The GWT compiler will remove any unused (uncalled) properties from the compiled application, and the number of HTTP requests is reduced because the locale data is bundled inline with your code.

Finally, truly the coolest and most innovative application of generators to date is the ImageBundle. In the world of 3D graphics programming, there is a technique called Texture Atlas, wherein you combine many textures into a single large texture, because on many graphics accelerators, changing pipeline state, such as binding a new texture before drawing geometry, is an expensive operation or may stall the pipeline. A program using texture atlases instead, binds one or more mondo-big textures, and simply uses texture coordinate manipulations to render portions of them as needed.

GWT 1.4 uses a similar technique to reduce load times and network traffic. With ImageBundle, like the I18N mechanism, you create an interface with a bunch of methods, one for each Image, as well as metadata annotations telling the GWT compiler which image file on disk you want returned by the method. Then, at compile time, the GWT compiler combines all of the images together into one large image file and generates an implementation class to return, essentially, the bounding box location of where each image is located within the overall atlas. Finally, when drawing the images, you just draw the same image (the large one) over and over, but use clipping rectangles to show only the part which corresponds to the image you need.

This reduces the number of HTTP requests drastically, speeds up startup time, and also centralizes media resources to a factory. The I18N and ImageBundle technique may even be combined to produce localized image bundles.

You’re starting to imagine the possibilities?

How about buttons rendered with drop-shadows? Rounded corners done at compile time? Object-relational mapping to Google Gears or serialized RowSets? Type-safe JSON wrappers?

The project that I have created as my first generator is one designed specifically to suit my needs. Chronoscope has a JavaScript API that allows pure JS developers to access functionality provided in GWT classes. The way it does this is by creating what I call “bridge” classes and methods in the top level browser namespace. These bridge classes contain the public names (non-obfuscated) of GWT methods that will be invoked by the Javascript-to-Java JSNI Mechanism.

The problem is, everytime I added a method to one of my GWT classes, I had to go write a bridge method for it, and as Chronoscope grew in size and complexity, I needed a more automatic, and safe, mechanism for exporting an external JS interface.

GWT Exporter

The first step is to decide what your generator is going to do. In my case, I want the generator to introspect one of my GWT classes, and generate an exported JS API with bridge methods.

What’s a bridge method?

Imagine you have the following GWT Class:

package org.foo.bar;

public class Util {
public static String doSomethingUseful(int x) {
return “Hello “+x;
}
}

And you want to allow JS users to call the doSomethingUseful() function?

Today, you would use JSNI to export ‘bridge methods’ like so:

package org.foo.bar;
public class Util {
public static String doSomethingUseful(int x) {
return “Hello “+x;
}
public native void export() /*-{
$wnd.doSomethingUseful = function(x) {
@org.foo.bar.Util::doSomethingUseful(I)(x);
}-*/;
}
}

$wnd stands for the top-level window object, and by assigning to its doSomethingUseful property, you ensure GWT won’t obfuscate it. The JSNI call to Util.doSomethingUseful will be obfuscated however, thus the bridge method is neccessary to export the obfuscated symbol.

It gets more complicated if you want to bridge a non-static function, but here’s an example:

public class Employee {
private String firstName, lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}public String getFirstName() {
return firstName;
}public String getLastName() {
return getLastName;
}public static Employee createEmployee(String firstName,
String lastName) {
return new Employee(firstName, lastName);
}public native void export() /*-{
$wnd.Employee = function(firstName, lastName) {
// call factory method and store GWT reference
this.instance =
@org.foo.bar.Employee::createEmployee(Ljava/lang/String;
Ljava/lang/String)(firstName, lastName);
}

var _=$wnd.Employee.prototype;
_.getFirstName = function() {
this.instance.@org.foo.bar.Employee::getFirstName()();
}
_.getLastName = function() {
this.instance.@org.foo.bar.Employee::getLastName()();
}
}-*/;
}

Which you may use as

x = new Employee(‘Ray’, ‘Cromwell’);
alert(x.getFirstName());

As you can see, manual bridging gets tedious!

Generators to the rescue!
The first step in implementing a generator is to decide on a type that will be used to trigger the generator. So let’s introduce a new marker interface called ‘Exportable’. GWT also want the generated class to implement the Exporter interface, primarily, the export() method.

Here they are:

package org.timepedia.exporter.client.Exportable;
public interface Exportable {
}public interface Exporter {
public void export();
}

Simple eh? Next we’ll add the following line to our GwtExporter.gwt.xml module file:

<generate-with
class=”org.timepedia.exporter.rebind.ExporterGenerator”>
<when-type-assignable
class=”org.timepedia.exporter.client.Exportable”/>
</generate-with>

What does this mean?

It means that when GWT.create() is invoked with a type that can be assigned to an Exportable, invoke the generator. That is, we want to write

public class Employee implements Exportable { … }

Exporter x=(Exporter)GWT.create(Employee.class);
x.export();

and have it invoke the generator.

Specifying what gets exported

Next we have to decide on the rules for exporting. Which methods of an Exportable get exported? How do we control the generated JS namespace? etc. For now, let’s settle on the following logic — a method is exportable IF and ONLY IF:

  1. The class enclosing the method implements Exportable
  2. Metadata has determined it’s ok to export (more on this later)

Also, we need error checking. It is an error to export a method if any parameter or return type is not one of:

  1. a primitive type (int, float, etc)
  2. another Exportable
  3. an immutable JRE type (String, Integer, Double, etc)
  4. JavaScriptObject

Metadata

GWT has its own form of annotations similar to JavaDoc/XDocLet tags. We will use this to control export policy. We will support two forms of export policy:

  1. White List
    1. By default, nothing exported.
    2. Each method to be exported must have a “@gwt.export” metadata annotation
  2. Black List
    1. Place “@gwt.export” on class itself (in JavaDoc for class)
    2. By default, all public methods exported
    3. Each method to be removed from export consideration tagged with “@gwt.noexport”

Finally, by default, the GWT Class’s package will be used as the JS’s namespace, (e.g. new $wnd.org.foo.bar.Employee). If you wish to use another package for the JS export, place “@gwt.exportPackage [package1.package2...]” on the class JavaDoc.

As an example:

package org.foo.bar;
/**
* @gwt.export
* @gwt.exportPackage examples
*/
public class Employee implements Exportable {
private String firstName, lastName;
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}public String getFirstName() {
return firstName;
}
/**
* @gwt.noexport
*/
public String getLastName() {
return getLastName;
}

and uses black-list policy to export getFirstName() but supress the export of getLastName(); Using white-list policy, you would write:

package org.foo.bar;
/**
* @gwt.exportPackage examples
*/
public class Employee implements Exportable {
private String firstName, lastName;
/**
* @gwt.export
*/
public Employee(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
/**
* @gwt.export
*/
public String getFirstName() {
return firstName;
}public String getLastName() {
return getLastName;
}

to achieve the same effect.

At this time, GWT are not considering function overloading.

 
2 Comments

Posted by on October 1, 2008 in GWT/ JSNI / COMPILER

 

Tags: , , , , , , ,

GWT Demystified

The Google Web Toolkit can be considered a package of three fundamental technologies: The Java to Javascript Compiler, the runtime library/APIs, and the Hosted Mode browser. All three are very important components of GWT in their own right, but because the APIs and the Hosted browser are the most visual pieces (you can SEE THEM operating) they tend to have more impact on people, while the real heavy duty stuff being done by the GWT compiler goes mostly unnoticed.

This is why I am not surprised that many language zealots engaged in language wars often appear grimaced when I tell them I am rewriting my Javascript code in GWT. “Huh!? Why!?” Then the inevitable signs of misunderstanding crop up: “Didn’t applets show running Java in the browser is slow?”, “Doesn’t GWT produce bloated code?”, etc. Now, I am by no means a zealot for the Java language, but there does appear to be frequent misunderstandings about what the GWT Compiler is, and does.

The GWT Compiler is a real compiler. Not a simple translator that walks an abstract syntax tree turning Java expressions and statements into the nearest Javascript equivalents. In fact, the GWT Compiler performs optimizations that are very hard to do statically on raw Javascript, and hard to do even in regular Java.

For example, static dead code elimination is very hard to do safely in Javascript, and limited in Java as well (at the bytecode level). You can never really be sure that a public method in Java won’t be called, because of dynamic class loading, and frankly, you can’t even be sure that private methods won’t be invoked due to reflection and interception techniques, thus the only safe way to do dead code elimination is to defer it to runtime and let Hotspot deal with it.

In contrast, GWT has very good information on which methods are reachable, and is extremely aggressive at removing unused methods, saving both bandwidth and start up time. The closest equivalent in the Java world would be MIDLets, since the same sorts of closed-world assumptions can be made.

GWT does more than just remove dead code. It performs inlining, polymorphic-to-monomorphic call conversion (devirtualization), a form of type-inferencing which GWT calls Type-Tightening (GWT can infer that a field of type Animal is only ever assigned type Cat. In fact, it can infer that such a field is always null!), and lots of other little tricks. It doesn’t appear to have common subexpression elimination, copy propagation, or in-block dead code elimination yet, but in my third tutorial, I will demonstrate a simple naive way to achieve this.

What this means is that in GWT, you don’t pay much for what you don’t use, and you don’t have to worry about figuring out what’s used. It means GWT’s Javascript output is not bloated. It has a constant factor overhead related to the bootstrap process, but as your applications grow bigger, this code becomes smaller.

The GWT compiler already does a good job producing compact javascript code (Chronoscope is 30,000 lines of Java, 3.2 Megabytes of source, 1.9 Megabyte of compiled byte code, and 137k of Javascript after GWT 1.4 compiles it, and 45k after gzip -9), and there is a lot of headroom still left in terms of optimization that it can do.

So why do I use GWT? Besides the fact that we want to run in environments that don’t have Javascript, GWT’s Hosted Mode is extremely helpful providing full access to the universe of Java debuggers, and automatic code completion and popup Javadoc is very nice. (Even though I use IntelliJ IDEA, which already has good Javascript code completion and popup documentation)

GWT is a good platform for building AJAX/RIA applications and allows one to easily port or repurpose existing Java codebases and tools — another good option for developers. It has a bright future ahead of it.

 
Leave a comment

Posted by on October 1, 2008 in GWT/ JSNI / COMPILER

 

Tags: ,

GWT JSNI: Talking to GWT code from JavaScript

Bruce Johnson has written an expansive post on understanding the GWT JavaScript Native Interface (JSNI). It starts out with the piece that some people know about, namely inlining native JavaScript such as this:

PLAIN TEXT

JAVA:

  1. // Java method declaration…
  2. native String flipName(String name) /*-{
  3. // …implemented with JavaScript
  4. var re = /(\w+)\s(\w+)/;
  5. return name.replace(re, ‘$2, $1′);
  6. }-*/;

But what about calling back out to Java from within native land?

JAVA:

  1. package org.example.foo;
  2. public class Flipper {
  3. public native void flipName(String name) /*-{
  4. var re = /(\w+)\s(\w+)/;
  5. var s = name.replace(re, ‘$2, $1′);
  6. this.@org.example.foo.Flipper::onFlip(Ljava/lang/String;)(s);
  7. }-*/;
  8. private void onFlip(String flippedName) {
  9. // do something useful with the flipped name
  10. }
  11. }

You can also access any JavaScript, loaded from a script source or however via:

JAVA:

  1. // A Java method using JSNI
  2. native void sayHelloInJava(String name) /*-{
  3. $wnd.sayHello(name); // $wnd is a JSNI synonym for ‘window’
  4. }-*/;

But finally, what about if you wrote a bunch of Java code for GWT, and you want JavaScript to call that? Simply link the code back through the $wnd world:

JAVA:

  1. package org.example.yourcode.format.client;
  2. public class DateFormatterLib implements EntryPoint {
  3. // Expose the following method into JavaScript.
  4. private static String formatAsCurrency(double x) {
  5. return NumberFormat.getCurrencyFormat().format(x);
  6. }
  7. // Set up the JS-callable signature as a global JS function.
  8. private native void publish() /*-{
  9. $wnd.formatAsCurrency =
  10. @org.example.yourcode.format.client.
  11. DateFormatterLib::formatAsCurrency(D);
  12. }-*/;
  13. // Auto-publish the method into JS when the GWT module loads.
  14. public void onModuleLoad() {
  15. publish();
  16. }
  17. }
 
Leave a comment

Posted by on September 28, 2008 in GWT/ JSNI / COMPILER

 

Tags: ,

GWT: JSNI (Javascript Native Interface)

 
3 Comments

Posted by on September 28, 2008 in GWT/ JSNI / COMPILER

 

Tags: , , ,

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: