Monthly Archives: June 2007

Asynchrony is Everything

You may know “Position is Everything” already. And I believe you should also know “Asynchony is Everything” or “Everything is Asynchronous” in RIA development.

Asynchrony is not only very important in web application development but also vital in normal desktop applications and embed systems. Asynchronous programming may help a lot in improving user experience. In normal desktop applications, if the main thread blocks UI for its long-time-consuming computing, users will feel desperately, waiting the busy-cursor to turn into default. But if such computing is run in background, user would find other things to do, such as switching focuses or typing something.

What about the definition of Asynchronous Computing? It is not only about asynchronous loading or asynchronous remote procedure call (RPC), it is also about local calculating. One thing should be mentioned here is UI layout computing. Lots of UI need complex layout calculating. For example, rendering a web page, rendering a 3D interfaces, or rending a complex dialog box. This CPU times required is especially obvious when it’s performed in a slow computer or in a slow computing environment, such as JavaScript runtime in browsers.

Here, I concerns about asynchronous layout. In implementing Java2Script’s SWT library, there is a huge problem for us. JavaScript is so slow that it can not finish a complex layout in less than 5 seconds. Or a complex layout requires more than 1 second will freeze browser UI, which make the user experience very bad and unacceptable. In order to overcome such problems. Java2Script introduced “Asynchronous Layout”.

Asynchronous layout is about to split the layout jobs into small pieces of jobs and run them step by step. As you may know, in SWT, all widgets are placed inside some containers. And to make a layout over container, the bounds of parent container, which is a Composite widget, is calculated first. And then the bounds will be passed as constraints of its child widgets to make children layouts. In such layout algorithms, we could split the layout jobs into parent container layout and child widget layout jobs, queue these jobs, and monitor each job’s required CPU times to avoid complex layout takes more than 200ms. If layout computing takes more than 200ms, then sleep for about 50ms before calling the next layout job.

Here are some snippets about Asynchronous Layout:

Display#readAndDispatch

public boolean readAndDispatch () {
checkDevice ();
drawMenuBars ();
runPopups ();
/*
if (OS.PeekMessage (msg, 0, 0, 0, OS.PM_REMOVE)) {
if (!filterMessage (msg)) {
OS.TranslateMessage (msg);
OS.DispatchMessage (msg);
}
runDeferredEvents ();
return true;
}
return runAsyncMessages (false);
*/

if (messageProc != 0) {
return true; //already hooked, return directly
}
messageProc = window.setInterval(new RunnableCompatibility() {
private boolean messageLoop = false;
public void run() {
runPopups ();
MESSAGE[] msgs = Display.this.msgs;
if (msgs.length == 0 && messageLoop)
/**
* @j2sNative
* var layoutFinished = window["j2s.swt.shell.finish.layout"];
* if (layoutFinished != null) {
* layoutFinished ();
* }
* this.messageLoop = false;
*/
{ }
if (msgs.length != 0) {
messageLoop = true;
MESSAGE[] defered = new MESSAGE[0];

int defsize = 0;
for (int i = msgs.length - 1; i >= 0; i--) {
MESSAGE m1 = msgs[i];
if (m1 == null) {
continue;
}
m1.defer = false;
for (int j = i - 1; j >= 0; j--) {
MESSAGE m2 = msgs[j];
if (m2 != null && m2.control == m1.control
&& m2.type == m1.type) {
msgs[j] = null;
}
}

if(m1.type == MESSAGE.CONTROL_LAYOUT){
if(m1.control.parent != null && m1.control.parent.waitingForLayout){
m1.defer = true;
defered[defsize++] = m1;
}
}

}
long time = 0;

for (int i = 0; i < msgs.length; i++) {
MESSAGE m = msgs[i];

if(m != null && m.defer){
continue;
}
msgs[i] = null;
if (m != null && m.type == MESSAGE.CONTROL_LAYOUT) {
m.control.waitingForLayout = false;
if (!m.control.isVisible()) { continue; }
Date d = new Date();
Composite c = (Composite) m.control;
if(c.waitingForLayoutWithResize){
c.setResizeChildren (false);
}
if(c.layout != null){
c.layout.layout (c, (c.state & Composite.LAYOUT_CHANGED) != 0);
c.state &= ~(Composite.LAYOUT_NEEDED | Composite.LAYOUT_CHANGED);
}
if(c.waitingForLayoutWithResize){
c.setResizeChildren (true);
c.waitingForLayoutWithResize = false;
}

if (m.data != null) {
boolean[] bs = (boolean[]) m.data;
c.updateLayout(bs[0], bs[1]);
} else {
c.layout();
}
time += new Date().getTime() - d.getTime();
if (time > 200) {
for (int j = i + 1; j < msgs.length; j++) {
msgs[j - i - 1] = msgs[j];
}
int length = msgs.length - i - 1;
for(int j = 0; j < defsize; j++){
msgs[length + j] = defered[j];
}
/**
* @j2sNativeSrc
* msgs.length -= i + 1;
* @j2sNative
* a.length -= f + 1;
*/
{}
return ;
}
}
}
/**
* @j2sNativeSrc
* msgs.length = 0;
* @j2sNative
* a.length = 0;
*/
{}
Display.this.msgs = defered;
// for(int j = 0; j < defsize; j++){
// msgs[j] = defered[j];
// }
}
}
}, 100);
return true;
}

Composite#updateLayout

void updateLayout (boolean resize, boolean all) {
if (isLayoutDeferred ()) return;
if ((state & LAYOUT_NEEDED) != 0 && !waitingForLayout) {
// boolean changed = (state & LAYOUT_CHANGED) != 0;
// state &= ~(LAYOUT_NEEDED | LAYOUT_CHANGED);
// if (resize) setResizeChildren (false);
// layout.layout (this, changed);
// if (resize) setResizeChildren (true);
this.waitingForLayout = true;
this.waitingForLayoutWithResize = resize;
display.sendMessage(new MESSAGE(this, MESSAGE.CONTROL_LAYOUT, new boolean[] {resize, all}));
}

if (all) {
Control [] children = _getChildren ();
int length = children.length;
for (int i=0; i<length; i++) {
// children [i].updateLayout (resize, all);
if (children[i] instanceof Composite) {
display.sendMessage(new MESSAGE(children[i], MESSAGE.CONTROL_LAYOUT, new boolean[] {resize, all}));
}
}
}
}

Control#setBounds:

void setBounds (int x, int y, int width, int height, int flags, boolean defer) {
/**
* A patch to send bounds to support mirroring features like what Windows have.
*/

boundsSet = true;
int tempX = x;
if(parent != null){
if((parent.style & SWT.RIGHT_TO_LEFT) != 0){
x = Math.max(0, parent.getClientArea().width - x - width);
}
}
Element topHandle = topHandle ();
if (defer && parent != null) {
forceResize ();
WINDOWPOS [] lpwp = parent.lpwp;
if (lpwp == null) {
/*
* This code is intentionally commented. All widgets that
* are created by SWT have WS_CLIPSIBLINGS to ensure that
* application code does not draw outside of the control.
*/

// int count = parent.getChildrenCount ();
// if (count > 1) {
// int bits = OS.GetWindowLong (handle, OS.GWL_STYLE);
// if ((bits & OS.WS_CLIPSIBLINGS) == 0) flags |= OS.SWP_NOCOPYBITS;
// }
if ((width != this.width || height != this.height)
&& this instanceof Composite) {
display.sendMessage(new MESSAGE(this, MESSAGE.CONTROL_LAYOUT, null));
}
this.left = x;
this.top = y;
this.width = width;
this.height = height;
SetWindowPos (topHandle, null, x, y, width, height, flags);
} else {
int index = 0;
while (index < lpwp.length) {
if (lpwp [index] == null) break;
index ++;
}
if (index == lpwp.length) {
WINDOWPOS [] newLpwp = new WINDOWPOS [lpwp.length + 4];
System.arraycopy (lpwp, 0, newLpwp, 0, lpwp.length);
parent.lpwp = lpwp = newLpwp;
}
WINDOWPOS wp = new WINDOWPOS ();
wp.hwnd = topHandle;
wp.x = x;
wp.y = y;
wp.cx = width;
wp.cy = height;
wp.flags = flags;
lpwp [index] = wp;
}
} else {
if ((width != this.width || height != this.height)
&& this instanceof Composite) {
display.sendMessage(new MESSAGE(this, MESSAGE.CONTROL_LAYOUT, null));
}
this.left = x;
this.top = y;
this.width = width;
this.height = height;
SetWindowPos (topHandle, null, x, y, width, height, flags);
}
/*
* The x coordination should be preserved, because the right to left emulation is just
* for the view, not the data!
*/

this.left = tempX;
}

For more details about Java2Script’s SWT Asynchronous Layout implementation, please check the sources history from SVN repository at http://j2s.svn.sourceforge.net/

Posted in Architecture, Hacks | 1 Comment

Browser Statistics Among Web Developers

Here are some numbers about browsers used among web developers:

1. Firefox 54.63%
2. Internet Explorer 38.10%
3. Opera 3.84%
4. Safari 1.56%
5. Mozilla 1.34%

Firefox versions:
1. 2.0.0.3 50.74%
2. 2.0.0.4 30.25%
3. 1.5.0.11 6.05%
4. 1.5.0.12 3.65%
5. 2.0.0.2 1.88%
6. 2.0.0.1 1.26%
7. 2.0 1.26%
8. 1.0.7 1.26%

Internet Explorer versions:
1. 6.0 67.27%
2. 7.0 32.65%

BTW: From the latest 15 days, more and more people update their Firefox to 2.0.0.4/1.5.0.12:
1. 2.0.0.4 71.76% (up)
2. 2.0.0.3 11.11%
3. 1.5.0.12 8.10% (up)
4. 2.0.0.2 1.44%

Posted in Architecture, Browser | 1 Comment

QoS of JavaScript

You must be aware of QoS when you are writing Rich Internet Application (RIA), especially when you are using AJAX. Why? And what aspects should be considered in QoS of RIA?

Here are some points:

1. Loading JavaScript file *.js by <script> tag may fail without acknowledge by the following JavaScript, which may result in a total page error;
2. Loading CSS style file *.css by <link> tag may fail, which results in ugly page layout;
3. Loading images by <img> tag may fail, which may confuse users;
4. …

The above scenarios do not occurs often in development period. Because you may using local HTTP server to serve resources, or you may have high bandwidth with slow latency. But if you deploy your applications to server, your server may be busy all the time to serve resources, and will fail to serve some resources at some uncertain time. And people may report such bugs if they are in beta tests, but people may lose their deals or money if such failures happen in real online.

So, QoS is required.

How to make sure the RIA’s qualities? First, make sure that such HTTP timeouts or failures does not interrupt normal business logics. To do so, try reload resources if such failures are detected. It would be easy to reload *.js file by <script> tag, or other resources by other tags. In order to detect failures, you may have your own loader. This is the reason why there is ClassLoader in Java2Script. To detect failures is also easy. Just hook the onerror or onreadystatechange event of loading JavaScript. Or you can setup a thread looping to check whether a *.css or an image is loaded or not.

There are other QoS aspects. Stay tuned for more coming discussions.

Posted in Architecture, Hacks, JavaScript | 6 Comments

Compressing and Deploying JavaScript

For AJAX, deploying JavaScript files may be important for you or not. If you are professional in AJAX, you must know the details of JavaScript deployment.

First, you can compress your JavaScript files before deploying them. Common compressors may cut 50% off of file size for normal JavaScript. That is to say, if your packed *.js is about 100k, the compressed *.js may be 50k. The compressed *.js may take about 100ms to decompress, but it when comparing to 50k over 1Mb/s bandwidth ( 50k * 8 / 1M = 0.4 s = 400ms). It worths such compressing. Usually bandwidth is not quite good as 1Mb/s, it will much better for compressed JavaScript.

Some well-known JavaScript compressors are Dean Edwards’ Packer and Shrink Safe by Alex at Dojo. You may find some other compressors, like Java2Script’s LZ77 JavaScript Compressor.

Second, you can send out your JavaScript files as gzip-encoded by Apache server. For most of modern browsers, gzip-encoding can be accepted. So you should configure your Apache server to do so especially when your JavaScript is over 200k. In common cases, gzip-encoding saves over 75% of JavaScript bandwidth. That is to say, 200k JavaScript only takes up 50k transmission. What a great improvement.

But please pay attention to some defects of JavaScript gzip-encoding for some browsers, like IE. Well, Internet Explorer takes up 80%+ of browser shares. You must not ignore IE’s defects on dealing JavaScript gzip-encoding. As IE6.0 SP2 and IE7+ already fixed this bug. You should support these two browsers, as it may get more and more market share.

So when configure .htaccess file for Apache httpd server, you should ignore those buggy IE browser or non-supported browsers. Here is my .htaccess file:

<IfModule mod_deflate.c>
# Netscape 4.x or IE 5.5/6.0
BrowserMatch ^Mozilla/4 no-gzip
# IE 5.5 and IE 6.0 have bugs! Ignore them until IE 7.0+
BrowserMatch \bMSIE\s7 !no-gzip
# IE 6.0 after SP2 has no gzip bugs!
BrowserMatch \bMSIE.*SV !no-gzip
# Sometimes Opera pretends to be IE with "Mozila/4.0"
BrowserMatch \bOpera !no-gzip
AddOutputFilterByType DEFLATE text/css text/javascript application/x-javascript
Header append Vary User-Agent
</IfModule>

For more information about this gzip-encoding configuration, please google “IE gzip javascript encoding” or read Joshua Eichorn’s blog article “Compressing JavaScript and CSS”.

Third, this is still about gzip-encoding. But this method tries to include JavaScript in HTML sources directly. As IE has no bugs on decoding gzip-encoded HTML files, compress JavaScript in this way will suite for most IE6 users. As far as I know, GWT uses this way to send out their JavaScript. But loading those HTML files in an embed IFRAME may make the whole architecture a little strange or hard to understand. Few people uses this method.

Maybe there are some other ways to compress and deploy JavaScript. Please let me know or discuss with me if you have a new one.

Posted in Architecture, Hacks, JavaScript | 25 Comments

Packing in Java2Script

Usually, when you develop new features, you split functions into pieces and implement them one by one. And in Java development, there will be implemented by one *.java file and another. If you want to deploy the finished feature, you need to pack them up.

In Java development, deployment means that you need to pack compiled *.class files and other related resource files into a *.jar and place it to correct location. There are lots of tools to do this job. Or if you are using IDE, such as Eclipse, the IDE will provide a whole development life management tools for you.

In JavaScript world, tools are rare. And for the loading speed and performance considerations, packing JavaScript and deploy them need your attentions.

Small *.js file should be packed into some bigger *.js file. But each *.js file should not be too big, or each time you update only one small *.js, you have to update a big *.js file. But *.js files should not be too many. Because *.js files are downloaded from servers in some specific orders, two many *.js files may be queued, which may mean a long latency. Lots of *.js compiled from *.java by Java2Script compiler is very small. In order to get a shorter loading time, most of these *.js files are packed into a big *.z.js file. Please check out the packing ant script. But packing *.js into a big *.z.js is not a simple job in Java2Script. As there is ClassLoader inside Java2Script system. The packed *.z.js file must be dealt correctly by ClassLoader. This issue is very complicate. And I would like to talk about it in another post.

Small size images can be packed into a bigger size one two. This is especially useful if there are icons for tool-bar. When a small icon needed, just display the big image with given position and size. This trick is a CSS tip. For example, create a DIV block with size 16×16, and set its style with some background image started from given position:

<div style="width:16px; height:16px; background-image:url(big.gif); background-position:16px 32px; background-repeat:no-repeat;"></div>

“background-position:16px 32px;” means the icon place at the 2nd row, the 3rd column. That is the image packing trick. Java2Script SWT implementation uses these tricks, you can check the Shell.css. In there, there are no absolute positions but relative positions, such as “center right”. This is because 9 icons are packed as 3×3 squares.

Small *.css can also be packed into a big *.css files too. But in practices of Java2Script packing, *.css files are packed into *.js files. All *.css files are only applied when necessary. For example, when a widget is loaded, the widget related *.css rules are applied to the page so that widget may be in correct style. For this trick, please check Java2Script CSS hacks.

And there are also some other packing tricks which I may introduce later. As packing is for deployment. And deployed resources are for loading. And loading will affect the whole object oriented inheritance simulator. And things are a whole integrated system.

Posted in Architecture, Hacks | 2 Comments

Asynchronous Programming

In my early Java2Script development days, I think a lot about asynchronous programming. AJAX was hot and is still hot. What is most important factor in AJAX technologies? I think it is “Asynchronous”. Without asynchronous programming, visitors still need to waste their time waiting for browser to fetch the next page. What a bad user experience.

In fact, asynchronous programming is not an easy work. Lots of callbacks, lots of threads, lots of locks or semaphores. All these stuffs may be messed up into an unmaintainable geeky thing.

Actually, if there are tools helping to design and maintain such codes, it is not a big job. If you use Java, you won’t get stuck at those threads of synchronized locks, as lots of debug tools help you figure out how those things work together at any moment you want to take a look. In fact, there are lots asynchronous programmings in Java design patterns or codes. But in Java world, asynchronous programming is not an outstanding features, and it is seldom discussed as an important issue.

But in JavaScript world, in browser world, asynchronous programming is a huge thing. In JavaScript (also known as EMCAScript)? language specification, there are no threads, no semaphores, no locks. All things are designed in synchronized mode. And before AJAX was hot, there are no robust tools for developers to write and debug JavaScript. If JavaScript sources file size exceeds 100K, it would be a hard-ass job to maintain. And if there are 3 layers of callbacks, it would drive developers crazy to develop new features. From my early experience, I designed a web form with digital signature functions, I used Java Applet in the back-end and used AJAX-style dialogs. And in oder to make a correct call from dialogs to Java Applet, its parameters may be passed through about 4-6 callback layers, because there are security issues over JavaScript calling Java Applet and Java Applet’s own sandbox mechanism. At that time, I sometimes found myself at the peak of being crazy or being collapsed.

So as I explain, asynchronous programming is not funny. And we would like to accept synchronous programming. Now let’s take a look at those Java synchronous programming which need to be JavaScript asynchronous programming:

Java snippet:

Display display = Display.getDefault();
SimpleSWTRPC shell = new SimpleSWTRPC(display, SWT.SHELL_TRIM);
shell.open();
shell.layout();
while (!shell.isDisposed()) { // waiting loop
if (!display.readAndDispatch())
display.sleep();
}
// continue other codes...

But in JavaScript, the above waiting loop will use up all CPU times and freeze browser. So such waiting loop must be avoided. And callback mechanism is used:

var display = $wt.widgets.Display.getDefault ();
var shell = new org.java2script.demo.simplerpc.SimpleSWTRPC (display, 1264);
shell.open ();
shell.layout ();
Sync2Async.block (shell, this, function () {
// continue other codes...
});

The above codes use Sync2Async technology. Such technologies have lots of defects. The biggest defect is that it can not stop browser to execute the following codes outside the method closure. For example, if the above codes are in method #openUpDialog, and in another method say #setUp call this method and then call other methods:

this.openUpDialog();
this.checkState();
this.sendOutRequest();

When the above codes are executed in Java mode, #checkState and #sendOutRequest will never be called until user closes the dialog. But in JavaScript Sync2Async mode, the callback technology can not block browser from executing #checkState and #sendOutRequest, which may result in incorrect result. This is the key defect of Sync2Async technology. Even though it has defects, such technology helps developes a lots for some simple tasks.

In order to fulfill some complicate task, designers should design the whole architecture as asynchronous programming patter from the beginning. Even in Java language, all things in asynchronous mode are still difficult.

More should be discussed for this issue.

Posted in Architecture, Hacks | 17 Comments

Tutorial of Java2Script SWT and Simple RPC Application

In this article, I will show you a simple example using Java2Script Simple RPC (For “what is Java2Script Simple RPC? “, please read this post).

Step 1. Create a Java2Script Servlet Project

Here are instructions: File -> New -> Project … -> Java2Script -> Java2Script Servlet Proejct -> Next -> Key in project name and select “Create separate folders for sources and class files” -> Next or Finish or Finish on next page

Create Java2Script Project Menu Screenshot

Create Java2Script Project Select Screenshot

Create Java2Script Project Wizard Screenshot

When finish this step, try to expand the project sources, you should get similar structures as below:

Java2Script Servlet Project Sources Structure

Later, I will explain more about every files.

Step 2. Create an SWT Application

Here are instructions: Select “src” source folder and create package named “org.java2script.demo.simplerpc”, and create a class name “SimpleSWTRPC” in that package. The class’ source is as following:

package org.java2script.demo.simplerpc;

import net.sf.j2s.ajax.SimpleRPCSWTRequest;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class SimpleSWTRPC extends Shell {

private Text responseText;
private Text requestText;
private Label statusLabel;
/**
* Launch the application
* @param args
*/

public static void main(String args[]) {
try {
Display display = Display.getDefault();
SimpleSWTRPC shell = new SimpleSWTRPC(display, SWT.SHELL_TRIM);
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Create the shell
* @param display
* @param style
*/

public SimpleSWTRPC(Display display, int style) {
super(display, style);
createContents();
setLayout(new FillLayout());
}

/**
* Create contents of the window
*/

protected void createContents() {
setText("Hello SWT & Simple RPC");
setSize(371, 300);

final Composite composite = new Composite(this, SWT.NONE);
composite.setLayout(new GridLayout());

final Label requestLabel = new Label(composite, SWT.NONE);
final GridData gd_requestLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
requestLabel.setLayoutData(gd_requestLabel);
requestLabel.setText("Request:");

requestText = new Text(composite, SWT.MULTI | SWT.BORDER);
final GridData gd_requestText = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_requestText.heightHint = 80;
gd_requestText.minimumHeight = 80;
requestText.setLayoutData(gd_requestText);

final Button sendButton = new Button(composite, SWT.NONE);
sendButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
statusLabel.setText("Sending request ...");
String text = requestText.getText();
text = "[Server echo]:" + text;
responseText.setText(text);
statusLabel.setText("Server responded.");
}
});
final GridData gd_sendButton = new GridData(SWT.RIGHT, SWT.CENTER, false, false);
sendButton.setLayoutData(gd_sendButton);
sendButton.setText("Send Simple RPC Request");

final Label reponseLabel = new Label(composite, SWT.NONE);
reponseLabel.setText("Reponse:");

responseText = new Text(composite, SWT.MULTI | SWT.READ_ONLY | SWT.BORDER);
final GridData gd_responseText = new GridData(SWT.FILL, SWT.FILL, true, true);
gd_responseText.heightHint = 80;
responseText.setLayoutData(gd_responseText);

statusLabel = new Label(composite, SWT.BORDER);
final GridData gd_statusLabel = new GridData(SWT.FILL, SWT.CENTER, true, false);
statusLabel.setLayoutData(gd_statusLabel);
statusLabel.setText("...");
//
}

@Override
protected void checkSubclass() {
// Disable the check that prevents subclassing of SWT components
}

}

Use Instantiations’ WindowBuilder Pro to Design SWT Application

I used Instantiations’ WindowBuilder Pro (also known as SWT Designer) to generate the above codes. I only wrote a few lines as:

sendButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
statusLabel.setText("Sending request ...");
String text = requestText.getText();
text = "[Server echo]:" + text;
responseText.setText(text);
statusLabel.setText("Server responded.");
}
});

Step 3. Run as Java Application and Java2Script.

Use context menu to “Run as” -> Java Application, and “Run as” -> Java2Script Application. You should get things work.

Java2Script Example Run as Native SWT Desktop Application

Java2Script Example Run as Java2Script Application Inside Browser

Step 4. Add Simple RPC into Example

Now it is time to move

text = "[Server echo]:" + text;

to the server side.

First, create a new EchoRunnable class extending net.sf.j2s.ajax.SimpleRPCRunnable as follow:

package org.java2script.demo.simplerpc;

import net.sf.j2s.ajax.SimpleRPCRunnable;

public class EchoRPCRunnable extends SimpleRPCRunnable {

public String text;

public void ajaxRun() {
text = "[Server echo]:" + text;
}

}

Then modify button’s event handler as follow:

sendButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
statusLabel.setText("Sending request ...");
SimpleRPCSWTRequest.swtRequest(new EchoRPCRunnable() {

public void ajaxIn() {
text = requestText.getText();;
}

public void ajaxOut() {
responseText.setText(text);
statusLabel.setText("Server responded.");
}

public void ajaxFail() {
statusLabel.setText("Request failed.");
}

});
}
});

Re-test the application in native Java SWT application mode. It should work as expected.

Step 5.? Deploy Java2Script Simple RPC Application

Open WEB-INF/web.xml and add org.java2script.demo.simplerpc.EchoRunnable to simple.rpc.runnables list. Here is the web.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Java2Script</display-name>
<description>Java2Script application</description>
<servlet>
<servlet-name>simplerpc</servlet-name>
<servlet-class>net.sf.j2s.ajax.SimpleRPCHttpServlet</servlet-class>
<init-param>
<param-name>simple.rpc.runnables</param-name>
<!--
Qualified names of inherited net.sf.j2s.ajax.SimpleRPCRunnable
classes, seperated by ";".
-->
<param-value>
org.java2script.demo.simplerpc.EchoRPCRunnable
</param-value>
</init-param>
<init-param>
<param-name>simple.rpc.xss.support</param-name>
<param-value>true</param-value>
</init-param>
<!--
<init-param>
<param-name>simple.rpc.post.limit</param-name>
<param-value>16777216</param-value>
</init-param>
<init-param>
<param-name>simple.rpc.xss.max.parts</param-name>
<param-value>8</param-value>
</init-param>
<init-param>
<param-name>simple.rpc.xss.max.latency</param-name>
<param-value>6000</param-value>
</init-param>
-->
</servlet>
<servlet-mapping>
<servlet-name>simplerpc</servlet-name>
<url-pattern>/simplerpc</url-pattern>
</servlet-mapping>
</web-app>

Select build.xml file, right click to bring up context-menu and “Run as” -> Ant Build, and then select the project and right click and select “Refresh” to refresh the project files, you will see a “org.java2script.demo.simplerpc.war” file. Now try to deploy this war file to a Java servlet container, such as Tomcat server.

If your Tomcat? server is installed in localhost, try url:

http://localhost:8080/manager/html

to deploy the above mentioned war file.

Deploy Java2Script Simple RPC Application *.war Package

But you haven’t finish deployment yet, because you still need to deploy Java2Script’s core *.js library files to the server.

Add the following to build.xml:

<target name="pack.plugins.j2slib.war">
<delete file="${basedir}/../plugins.war" quiet="true"/>
<zip destfile="${basedir}/../plugins.war">
<fileset dir="${basedir}/../../../plugins/">
<include name="net.sf.j2s.lib_1.0.0/**"/>
<exclude name="net.sf.j2s.lib_1.0.0/library.jar"/>
<exclude name="net.sf.j2s.lib_1.0.0/plugin.xml"/>
<exclude name="net.sf.j2s.lib_1.0.0/META-INF/**"/>
</fileset>
</zip>
</target>

And “Run as” -> “Ant Build …”, select “pack.plugins.j2slib.war” in the “Targets” tab and “Run”. Then refresh the project, and deploy the “plugins.war” to Tomcat server.

And after all things deployed, please visit:

http://localhost:8080/org.java2script.demo.simplerpc/org.java2script.demo.simplerpc.SimpleSWTRPC.html

Here is the online demo of this Simple RPC example.

(To be continued)

Posted in Tutorials | 601 Comments